diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/framework/java/com/flexive/shared/value/FxValue.java b/src/framework/java/com/flexive/shared/value/FxValue.java index 9c48c27c..3c5ceeeb 100644 --- a/src/framework/java/com/flexive/shared/value/FxValue.java +++ b/src/framework/java/com/flexive/shared/value/FxValue.java @@ -1,1164 +1,1164 @@ /*************************************************************** * This file is part of the [fleXive](R) framework. * * Copyright (c) 1999-2010 * UCS - unique computing solutions gmbh (http://www.ucs.at) * All rights reserved * * The [fleXive](R) project is free software; you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public * License version 2.1 or higher as published by the Free Software Foundation. * * The GNU Lesser General Public License can be found at * http://www.gnu.org/licenses/lgpl.html. * A copy is found in the textfile LGPL.txt and important notices to the * license from the author are found in LICENSE.txt distributed with * these libraries. * * 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 General Public License for more details. * * For further information about UCS - unique computing solutions gmbh, * please see the company website: http://www.ucs.at * * For further information about [fleXive](R), please see the * project website: http://www.flexive.org * * * This copyright notice MUST APPEAR in all copies of the file! ***************************************************************/ package com.flexive.shared.value; import com.flexive.shared.FxContext; import com.flexive.shared.FxFormatUtils; import com.flexive.shared.FxLanguage; import com.flexive.shared.FxSharedUtils; import com.flexive.shared.content.FxValueChangeListener; import com.flexive.shared.exceptions.FxInvalidParameterException; import com.flexive.shared.exceptions.FxInvalidStateException; import com.flexive.shared.exceptions.FxNoAccessException; import com.flexive.shared.security.UserTicket; import com.flexive.shared.value.renderer.FxValueRendererFactory; import org.apache.commons.lang.ArrayUtils; import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; /** * Abstract base class of all value objects. * Common base classed is used for multilingual properties, etc. * <p/> * To check if a value is empty a flag is used for each language resp. the single value. * Use the setEmpty() method to explicity set a value to be empty * * @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at) */ public abstract class FxValue<T, TDerived extends FxValue<T, TDerived>> implements Serializable, Comparable<FxValue> { private static final long serialVersionUID = -5005063788615664383L; public static final boolean DEFAULT_MULTILANGUAGE = true; public static final Integer VALUE_NODATA = null; protected boolean multiLanguage; protected long defaultLanguage = FxLanguage.SYSTEM_ID; private long selectedLanguage; private int maxInputLength; private String XPath = ""; private Integer valueData = VALUE_NODATA; private FxValueChangeListener changeListener = null; private final static long[] SYSTEM_LANG_ARRAY = new long[]{FxLanguage.SYSTEM_ID}; /** * Data if <code>multiLanguage</code> is enabled */ protected Map<Long, T> translations; protected Map<Long, Boolean> emptyTranslations; /** * Data if <code>multiLanguage</code> is disabled */ protected T singleValue; private boolean singleValueEmpty; private boolean readOnly; /** * Constructor * * @param multiLanguage multilanguage value? * @param defaultLanguage the default language * @param translations HashMap containing language->translation mapping */ protected FxValue(boolean multiLanguage, long defaultLanguage, Map<Long, T> translations) { this.defaultLanguage = defaultLanguage; this.multiLanguage = multiLanguage; this.maxInputLength = -1; this.readOnly = false; if (multiLanguage) { if (translations == null) { //valid to pass null, create an empty one this.translations = new HashMap<Long, T>(4); this.emptyTranslations = new HashMap<Long, Boolean>(4); } else { this.translations = new HashMap<Long, T>(translations); this.emptyTranslations = new HashMap<Long, Boolean>(translations.size()); } if (this.defaultLanguage < 0) { this.defaultLanguage = FxLanguage.SYSTEM_ID; this.selectedLanguage = FxLanguage.SYSTEM_ID; if (translations != null && !translations.entrySet().isEmpty()) for (Entry<Long, T> e : translations.entrySet()) if (e.getValue() != null) { this.selectedLanguage = e.getKey(); break; } } else this.selectedLanguage = this.defaultLanguage; for (Long lang : this.translations.keySet()) emptyTranslations.put(lang, this.translations.get(lang) == null); } else { if (translations != null && !translations.isEmpty()) { //a translation is provided, use the defaultLanguage element or very first element if not present singleValue = translations.get(defaultLanguage); if (singleValue == null) singleValue = translations.values().iterator().next(); } this.defaultLanguage = FxLanguage.SYSTEM_ID; this.selectedLanguage = FxLanguage.SYSTEM_ID; this.translations = null; this.singleValueEmpty = false; } } /** * Initialize an empty FxValue (used for initalization for XML import, etc.) * * @param defaultLanguage default language * @param multiLanguage multilanguage value? */ protected FxValue(long defaultLanguage, boolean multiLanguage) { this.multiLanguage = multiLanguage; this.defaultLanguage = defaultLanguage; this.maxInputLength = -1; this.readOnly = false; if (this.multiLanguage) { this.translations = new HashMap<Long, T>(4); this.emptyTranslations = new HashMap<Long, Boolean>(4); if (this.defaultLanguage < 0) { this.defaultLanguage = FxLanguage.SYSTEM_ID; this.selectedLanguage = FxLanguage.SYSTEM_ID; } else this.selectedLanguage = this.defaultLanguage; for (Long lang : this.translations.keySet()) emptyTranslations.put(lang, this.translations.get(lang) == null); } else { this.defaultLanguage = FxLanguage.SYSTEM_ID; this.selectedLanguage = FxLanguage.SYSTEM_ID; this.translations = null; this.singleValueEmpty = false; } } /** * Constructor * * @param defaultLanguage the default language * @param translations HashMap containing language->translation mapping */ protected FxValue(long defaultLanguage, Map<Long, T> translations) { this(DEFAULT_MULTILANGUAGE, defaultLanguage, translations); } /** * Constructor * * @param multiLanguage multilanguage value? * @param translations HashMap containing language->translation mapping */ protected FxValue(boolean multiLanguage, Map<Long, T> translations) { this(multiLanguage, FxLanguage.SYSTEM_ID, translations); } /** * Constructor * * @param translations HashMap containing language->translation mapping */ protected FxValue(Map<Long, T> translations) { this(DEFAULT_MULTILANGUAGE, FxLanguage.SYSTEM_ID, translations); } /** * Constructor - create value from an array of translations * * @param translations HashMap containing language->translation mapping * @param pos position (index) in the array to use */ protected FxValue(Map<Long, T[]> translations, int pos) { this(DEFAULT_MULTILANGUAGE, FxLanguage.SYSTEM_ID, new HashMap<Long, T>((translations == null ? 5 : translations.size()))); if (multiLanguage) { if (translations == null) return; for (Entry<Long, T[]> e : translations.entrySet()) if (e.getValue()[pos] != null) this.translations.put(e.getKey(), e.getValue()[pos]); else this.emptyTranslations.put(e.getKey(), Boolean.TRUE); } else { this.singleValue = (translations == null || translations.isEmpty() ? null : translations.values().iterator().next()[pos]); if( this.singleValue == null ) this.singleValueEmpty = true; } } /** * Constructor * * @param multiLanguage multilanguage value? * @param defaultLanguage the default language and the language for the value * @param value single initializing value */ protected FxValue(boolean multiLanguage, long defaultLanguage, T value) { this(multiLanguage, defaultLanguage, (Map<Long, T>) null); if (value == null) { if(multiLanguage) this.emptyTranslations.put(defaultLanguage, Boolean.TRUE); else this.singleValueEmpty = true; } else { if (multiLanguage) this.translations.put(defaultLanguage, value); else this.singleValue = value; } } /** * Constructor * * @param defaultLanguage the default language * @param value single initializing value */ protected FxValue(long defaultLanguage, T value) { this(DEFAULT_MULTILANGUAGE, defaultLanguage, value); } /** * Constructor * * @param multiLanguage multilanguage value? * @param value single initializing value */ protected FxValue(boolean multiLanguage, T value) { this(multiLanguage, FxLanguage.DEFAULT_ID, value); } /** * Constructor * * @param value single initializing value */ protected FxValue(T value) { this(DEFAULT_MULTILANGUAGE, value); } /** * Constructor * * @param clone original FxValue to be cloned */ @SuppressWarnings("unchecked") protected FxValue(FxValue<T, TDerived> clone) { this(clone.isMultiLanguage(), clone.getDefaultLanguage(), new HashMap<Long, T>((clone.translations != null ? clone.translations.size() : 1))); this.XPath = clone.XPath; this.maxInputLength = clone.maxInputLength; this.valueData = clone.valueData; this.changeListener = clone.changeListener; if (clone.isImmutableValueType()) { if (multiLanguage) { // clone only hashmap this.translations = new HashMap(clone.translations); this.emptyTranslations = new HashMap(clone.emptyTranslations); } else { this.singleValue = clone.singleValue; this.singleValueEmpty = clone.singleValueEmpty; } } else { if (multiLanguage) { // clone hashmap values Method meth = null; for (long k : clone.translations.keySet()) { T t = clone.translations.get(k); if (t == null) this.translations.put(k, null); else { try { if (meth != null) { this.translations.put(k, (T) meth.invoke(t)); } else { Class<?> clzz = t.getClass(); meth = clzz.getMethod("clone"); } } catch (Exception e) { throw new IllegalArgumentException("clone not supported", e); } } } this.emptyTranslations = new HashMap(clone.emptyTranslations); } else { try { this.singleValue = (T) clone.singleValue.getClass(). getMethod("clone").invoke(clone.singleValue); } catch (Exception e) { throw new IllegalArgumentException("clone not supported", e); } this.singleValueEmpty = clone.singleValueEmpty; } } } /** * Get the XPath for this value - the XPath is optional and can be an empty String if * not explicitly assigned! * * @return XPath (optional! can be an empty String) */ public String getXPath() { return XPath; } /** * Returns the name of the value from the xpath. * <p/> * If the xpath is an empty string the name will also return an emptry String. * * @return the property name */ public String getXPathName() { try { String xpathSplit[] = getXPath().split("/"); return xpathSplit[xpathSplit.length - 1].split("\\[")[0]; } catch (Throwable t) { return ""; } } /** * Set the XPath (unless readonly) * * @param XPath the XPath to set, will be ignored if readonly * @return this */ @SuppressWarnings({"unchecked"}) public TDerived setXPath(String XPath) { if (!this.readOnly) { this.XPath = XPath != null ? XPath.toUpperCase(Locale.ENGLISH) : null; } return (TDerived) this; } /** * One-time operation to flag this FxValue as read only. * This is not reversible! */ public void setReadOnly() { this.readOnly = true; } /** * Mark this FxValue as empty * * @return this */ @SuppressWarnings("unchecked") public TDerived setEmpty() { if (this.multiLanguage) { if (this.emptyTranslations == null) this.emptyTranslations = new HashMap<Long, Boolean>(this.translations.size()); for (Long lang : this.translations.keySet()) this.emptyTranslations.put(lang, true); } else { this.singleValueEmpty = true; } return (TDerived) this; } /** * Mark the entry for the given language as empty * * @param language the language to flag as empty */ public void setEmpty(long language) { if (this.multiLanguage) { if (this.emptyTranslations == null) this.emptyTranslations = new HashMap<Long, Boolean>(this.translations.size()); this.emptyTranslations.put(language, true); } else { this.singleValueEmpty = true; } } /** * Return the class instance of the value type. * * @return the class instance of the value type. */ public abstract Class<T> getValueClass(); /** * Evaluates the given string value to an object of type T. * * @param value string value to be evaluated * @return the value interpreted as T */ public abstract T fromString(String value); /** * Convert from a portable (not locale specific format) * * @param value portable string value to be evaluated * @return the value interpreted as T */ public T fromPortableString(String value) { return fromString(value); } /** * Converts the given instance of T to a string that can be * parsed again by {@link FxValue#fromString(String)}. * * @param value the value to be converted * @return a string representation of the given value that can be parsed again using * {@link FxValue#fromString(String)}. */ public String getStringValue(T value) { return String.valueOf(value); } /** * Converts the given instance of T to a string that can be * parsed again by {@link FxValue#fromPortableString(String)}. * * @param value the value to be converted * @return a string representation of the given value that can be parsed again using * {@link FxValue#fromPortableString(String)}. */ public String getPortableStringValue(T value) { return getStringValue(value); } /** * Creates a copy of the given object (useful if the actual type is unknown). * * @return a copy of the given object (useful if the actual type is unknown). */ public abstract TDerived copy(); /** * Return true if T is immutable (e.g. java.lang.String). This prevents cloning * of the translations in copy constructors. * * @return true if T is immutable (e.g. java.lang.String) */ public boolean isImmutableValueType() { return true; } /** * Is this value editable by the user? * This always returns true except it is a FxNoAccess value or flagged as readOnly * * @return if this value editable? * @see FxNoAccess */ public boolean isReadOnly() { return readOnly; } /** * Returns true if this value is valid for the actual type (e.g. if * a FxNumber property actually contains only valid numbers). * * @return true if this value is valid for the actual type */ public boolean isValid() { //noinspection UnusedCatchParameter try { getErrorValue(); // an error value exists, thus this instance is invalid return false; } catch (IllegalStateException e) { // this instance is valid, thus no error value could be retrieved return true; } } /** * Returns true if the translation for the given language is valid. An empty translation * is always valid. * * @param languageId the language ID * @return true if the translation for the given language is valid * @since 3.1 */ public boolean isValid(long languageId) { final T value = getTranslation(languageId); if (value == null || !(value instanceof String)) { // empty or non-string translations are always valid return true; } // try a conversion to the native type try { fromString((String) value); return true; } catch (Exception e) { return false; } } /** * Returns true if the translation for the given language is valid. An empty translation * is always valid. * * @param language the language * @return true if the translation for the given language is valid * @since 3.1 */ public boolean isValid(FxLanguage language) { return isValid(language != null ? language.getId() : -1); } /** * Returns the value that caused {@link #isValid} to return false. If isValid() is true, * a RuntimeException is thrown. * * @return the value that caused the validation via {@link #isValid} to fail * @throws IllegalStateException if the instance is valid and the error value is undefined */ @SuppressWarnings({"UnusedCatchParameter"}) public T getErrorValue() throws IllegalStateException { if (multiLanguage) { for (T translation : translations.values()) { if (translation instanceof String) { // if a string was used, check if it is a valid representation of our type try { fromString((String) translation); } catch (Exception e) { return translation; } } } } else if (singleValue instanceof String) { try { fromString((String) singleValue); } catch (Exception e) { return singleValue; } } throw new IllegalStateException(); } /** * Get a representation of this value in the default translation * * @return T */ public T getDefaultTranslation() { if (!multiLanguage) return singleValue; T def = getTranslation(getDefaultLanguage()); if (def != null) return def; if (translations.size() > 0) return translations.values().iterator().next(); //first available translation if default does not exist return def; //empty as last fallback } /** * Get the translation for a requested language * * @param lang requested language * @return translation or an empty String if it does not exist */ public T getTranslation(long lang) { return (multiLanguage ? translations.get(lang) : singleValue); } /** * Get a String representation of this value in the requested language or * an empty String if the translation does not exist * * @param lang requested language id * @return T translation */ public T getTranslation(FxLanguage lang) { if (!multiLanguage) //redundant but faster return singleValue; return getTranslation((int) lang.getId()); } /** * Get the translation that best fits the requested language. * The requested language is queried and if it does not exist the * default translation is returned * * @param lang requested best-fit language * @return best fit translation */ public T getBestTranslation(long lang) { if (!multiLanguage) //redundant but faster return singleValue; T ret = getTranslation(lang); if (ret != null) return ret; return getDefaultTranslation(); } /** * Get the translation that best fits the requested language. * The requested language is queried and if it does not exist the * default translation is returned * * @param language requested best-fit language * @return best fit translation */ public T getBestTranslation(FxLanguage language) { if (!multiLanguage) //redundant but faster return singleValue; if (language == null) // user ticket language return getBestTranslation(); return getBestTranslation((int) language.getId()); } /** * Get the translation that best fits the requested users language. * The requested users language is queried and if it does not exist the * default translation is returned * * @param ticket UserTicket to obtain the users language * @return best fit translation */ public T getBestTranslation(UserTicket ticket) { if (!multiLanguage) //redundant but faster return singleValue; return getBestTranslation((int) ticket.getLanguage().getId()); } /** * Get the translation that best fits the current users language. * The user language is obtained from the FxContext thread local. * * @return best fit translation */ public T getBestTranslation() { if (!multiLanguage) //redundant but faster return singleValue; return getBestTranslation(FxContext.getUserTicket().getLanguage()); } /** * Get all languages for which translations exist * * @return languages for which translations exist */ public long[] getTranslatedLanguages() { return (multiLanguage ? ArrayUtils.toPrimitive(translations.keySet().toArray(new Long[translations.keySet().size()])) : SYSTEM_LANG_ARRAY.clone()); } /** * Does a translation exist for the given language? * * @param languageId language to query * @return translation exists */ public boolean translationExists(long languageId) { return !multiLanguage || translations.get(languageId) != null; } /** * Like empty(), for JSF EL, since empty cannot be used. * * @return true if the value is empty */ public boolean getIsEmpty() { return isEmpty(); } /** * Is this value empty? * * @return if value is empty */ public boolean isEmpty() { if (multiLanguage) { syncEmptyTranslations(); for (boolean check : emptyTranslations.values()) if (!check) return false; return true; } else return singleValueEmpty; } /** * Check if the translation for the given language is empty * * @param lang language to check * @return if translation for the given language is empty */ public boolean isTranslationEmpty(FxLanguage lang) { return lang != null ? isTranslationEmpty(lang.getId()) : isEmpty(); } /** * Check if the translation for the given language is empty * * @param lang language to check * @return if translation for the given language is empty */ public boolean isTranslationEmpty(long lang) { if (!multiLanguage) return singleValueEmpty; syncEmptyTranslations(); return !emptyTranslations.containsKey(lang) || emptyTranslations.get(lang); } /** * Synchronize - and create if needed - empty tanslations */ private void syncEmptyTranslations() { if (!multiLanguage) return; if (emptyTranslations == null) emptyTranslations = new HashMap<Long, Boolean>(translations.size()); if (emptyTranslations.size() != translations.size()) { //resync for (Long _lang : translations.keySet()) { if (!emptyTranslations.containsKey(_lang)) emptyTranslations.put(_lang, translations.get(_lang) == null); } } } /** * Get the language selected in user interfaces * * @return selected language */ public long getSelectedLanguage() { return selectedLanguage; } /** * Set the user selected language * * @param selectedLanguage selected language ID * @return self * @throws FxNoAccessException if the selected Language is not contained */ public FxValue setSelectedLanguage(long selectedLanguage) throws FxNoAccessException { if (selectedLanguage < 0 || !multiLanguage) return this; //throw exception if selectedLanguage is not contained! if (!translations.containsKey(selectedLanguage)) throw new FxNoAccessException("ex.content.value.invalid.language", selectedLanguage); this.selectedLanguage = selectedLanguage; return this; } /** * Set the translation for a language or override the single language value if * this value is not flagged as multi language enabled. This method cannot be * overridden since it not only accepts parameters of type T, but also of type * String for web form handling. * * @param language language to set the translation for * @param value translation * @return this */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) public final TDerived setTranslation(long language, T value) { if (value instanceof FxValue) { throw new FxInvalidParameterException("value", "ex.content.invalid.translation.fxvalue", value.getClass().getCanonicalName()).asRuntimeException(); } if (value instanceof String) { try { - value = this.fromPortableString((String) value); + value = this.fromString((String) value); } catch (Exception e) { // do nothing. The resulting FxValue will be invalid, // but the invalid value will be preserved. // TODO: use a "safer" concept of representing invalid translations, // since this may lead to unexpeced ClassCastExceptions in parameterized // methods expecting a <T> value } } if (!multiLanguage) { if (value == null && !isAcceptsEmptyDefaultTranslations()) { throw new FxInvalidParameterException("value", "ex.content.invalid.default.empty", getClass().getSimpleName()).asRuntimeException(); } if(this.XPath != null && this.changeListener != null) { if(value != null) { if(this.singleValueEmpty) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Add); else if(!this.singleValue.equals(value)) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Update); } else if(!this.singleValueEmpty) { this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Remove); } } //override the single value if (singleValue == null || !singleValue.equals(value)) this.singleValue = value; this.singleValueEmpty = value == null; //noinspection unchecked return (TDerived) this; } if (translations == null) { //create an empty one, not yet initialized this.translations = new HashMap<Long, T>(4); this.emptyTranslations = new HashMap<Long, Boolean>(4); } if (language == FxLanguage.SYSTEM_ID) throw new FxInvalidParameterException("language", "ex.content.value.invalid.multilanguage.sys").asRuntimeException(); if(this.XPath != null && this.changeListener != null && value != null) { if(this.isEmpty()) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Add); else { if(!value.equals(translations.get(language))) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Update); } } boolean wasEmpty = this.changeListener != null && isEmpty(); //only evaluate if we have a change listener attached if (value == null) { translations.remove(language); emptyTranslations.remove(language); } else { if (!value.equals(translations.get(language))) { translations.put(language, value); } emptyTranslations.put(language, false); } if(this.XPath != null && this.changeListener != null && value == null && !wasEmpty && isEmpty()) { this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Remove); } //noinspection unchecked return (TDerived) this; } /** * Set the translation for a language or override the single language value if * this value is not flagged as multi language enabled * * @param lang language to set the translation for * @param translation translation * @return this */ public TDerived setTranslation(FxLanguage lang, T translation) { return setTranslation((int) lang.getId(), translation); } /** * For multilanguage values, set the default translation. * For single language values, set the value. * * @param value the value to be stored */ public void setValue(T value) { setTranslation(getDefaultLanguage(), value); } /** * Set the translation in the default language. For single-language values, * sets the value. * * @param translation the default translation * @return this */ public FxValue setDefaultTranslation(T translation) { return setTranslation(defaultLanguage, translation); } /** * Get the default language of this value * * @return default language */ public long getDefaultLanguage() { if (!isMultiLanguage()) return FxLanguage.SYSTEM_ID; return this.defaultLanguage; } /** * Returns the maximum input length an input field should have for this value * (or -1 for unlimited length). * * @return the maximum input length an input field should have for this value */ public int getMaxInputLength() { return maxInputLength; } /** * Set the maximum input length for this value (-1 for unlimited length). * * @param maxInputLength the maximum input length for this value (-1 for unlimited length). */ public void setMaxInputLength(int maxInputLength) { this.maxInputLength = maxInputLength; } /** * Set the default language. * It will only be set if a translation in the requested default language * exists! * * @param defaultLanguage requested default language */ public void setDefaultLanguage(long defaultLanguage) { setDefaultLanguage(defaultLanguage, false); } /** * Set the default language. Will have no effect if the value is not multi language enabled * * @param defaultLanguage requested default language * @param force if true, the default language will also be updated if no translation exists (for UI input) */ public void setDefaultLanguage(long defaultLanguage, boolean force) { if (multiLanguage && (force || translationExists(defaultLanguage))) { this.defaultLanguage = defaultLanguage; } } /** * Reset the default language to the system language */ public void clearDefaultLanguage() { this.defaultLanguage = FxLanguage.SYSTEM_ID; } /** * Is a default value set for this FxValue? * * @return default value set */ public boolean hasDefaultLanguage() { return defaultLanguage != FxLanguage.SYSTEM_ID && isMultiLanguage(); } /** * Check if the passed language is the default language * * @param language the language to check * @return passed language is the default language */ public boolean isDefaultLanguage(long language) { return !isMultiLanguage() && language == FxLanguage.SYSTEM_ID || hasDefaultLanguage() && language == defaultLanguage; } /** * Remove the translation for the given language * * @param language the language to remove the translation for */ public void removeLanguage(long language) { if (!multiLanguage) { setEmpty(); // ensure that the old value is not "leaked" to clients that don't check isEmpty() // and that the behaviour is consistent with multi-language inputs (FX-485) singleValue = getEmptyValue(); } else { translations.remove(language); emptyTranslations.remove(language); } } /** * Is this value available for multiple languages? * * @return value available for multiple languages */ public boolean isMultiLanguage() { return this.multiLanguage; } protected boolean isAcceptsEmptyDefaultTranslations() { return true; } /** * Format this FxValue for inclusion in a SQL statement. For example, * a string is wrapped in single quotes and escaped properly (' --> ''). * For multilanguage values the default translation is used. If the value is * empty (@link #isEmpty()), a runtime exception is thrown. * * @return the formatted value */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) public String getSqlValue() { if (isEmpty()) { throw new FxInvalidStateException("ex.content.value.sql.empty").asRuntimeException(); } return FxFormatUtils.escapeForSql(getDefaultTranslation()); } /** * Returns an empty value object for this FxValue type. * * @return an empty value object for this FxValue type. */ public abstract T getEmptyValue(); /** * {@inheritDoc} */ @Override public String toString() { // format value in the current user's locale - also used in the JSF UI return FxValueRendererFactory.getInstance().format(this); } /** * {@inheritDoc} */ @Override public boolean equals(Object other) { if (this == other) return true; if (other == null) return false; if (this.getClass() != other.getClass()) return false; FxValue<?, ?> otherValue = (FxValue<?, ?>) other; if (this.isEmpty() != otherValue.isEmpty()) return false; if (this.hasValueData() != otherValue.hasValueData() || (this.hasValueData() && otherValue.hasValueData() && this.getValueDataRaw().intValue() != otherValue.getValueDataRaw().intValue())) return false; if (this.isMultiLanguage() != otherValue.isMultiLanguage()) return false; if (multiLanguage) { return this.translations.equals(otherValue.translations) && this.defaultLanguage == otherValue.defaultLanguage; } else { if (!this.isEmpty()) if (!this.singleValue.equals(otherValue.singleValue)) return false; } return true; } /** * {@inheritDoc} */ @Override public int hashCode() { int hash = 7; if (translations != null) { hash = 31 * hash + translations.hashCode(); } hash = 31 * hash + (int) defaultLanguage + (hasValueData() ? getValueDataRaw() : 0); return hash; } /** * A generic comparable implementation based on the value's string representation. * * @param o the other object * @return see {@link Comparable#compareTo}. */ @SuppressWarnings({"unchecked"}) public int compareTo(FxValue o) { if (o == null) { return 1; } if (isEmpty() && !o.isEmpty()) { return -1; } if (isEmpty() && o.isEmpty()) { return 0; } if (!isEmpty() && o.isEmpty()) { return 1; } final String value = getStringValue(getBestTranslation()); final String oValue = o.getStringValue(o.getBestTranslation()); if (value == null && oValue == null) { return 0; } else if (value == null) { return -1; } else if (oValue == null) { return 1; } else { return FxSharedUtils.getCollator().compare(value, oValue); } } /** * Get attached value data (optional, if not set will return <code>VALUE_NODATA</code>). * As value data might contain some bit-coded flags in the future, it is not certain if the full Integer range * will be available as some bits might be masked out. * * @return attached value data, if not set will return <code>VALUE_NODATA</code> * @since 3.1.4 */ public Integer getValueData() { return valueData; } /** * Get attached value data (optional, if not set will return <code>VALUE_NODATA</code>) including any bit-coded flags. * Internal use only! * * @return raw attached value data, if not set will return <code>VALUE_NODATA</code> * @since 3.1.4 */ public Integer getValueDataRaw() { return valueData; } /** * Attach additional data to this value instance * * @param valueData value data to attach * @return this * @since 3.1.4 */ @SuppressWarnings({"unchecked"}) public TDerived setValueData(int valueData) { this.valueData = valueData; return (TDerived) this; } /** * Unset value data * @since 3.1.4 */ public void clearValueData() { this.valueData = VALUE_NODATA; } /** * Are additional value data set for this value instance? * * @return value data set * @since 3.1.4 */ public boolean hasValueData() { return this.valueData != null; } /** * Set the change listener * * @param changeListener change listener * @since 3.1.6 */ public void setChangeListener(FxValueChangeListener changeListener) { this.changeListener = changeListener; } }
true
true
public final TDerived setTranslation(long language, T value) { if (value instanceof FxValue) { throw new FxInvalidParameterException("value", "ex.content.invalid.translation.fxvalue", value.getClass().getCanonicalName()).asRuntimeException(); } if (value instanceof String) { try { value = this.fromPortableString((String) value); } catch (Exception e) { // do nothing. The resulting FxValue will be invalid, // but the invalid value will be preserved. // TODO: use a "safer" concept of representing invalid translations, // since this may lead to unexpeced ClassCastExceptions in parameterized // methods expecting a <T> value } } if (!multiLanguage) { if (value == null && !isAcceptsEmptyDefaultTranslations()) { throw new FxInvalidParameterException("value", "ex.content.invalid.default.empty", getClass().getSimpleName()).asRuntimeException(); } if(this.XPath != null && this.changeListener != null) { if(value != null) { if(this.singleValueEmpty) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Add); else if(!this.singleValue.equals(value)) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Update); } else if(!this.singleValueEmpty) { this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Remove); } } //override the single value if (singleValue == null || !singleValue.equals(value)) this.singleValue = value; this.singleValueEmpty = value == null; //noinspection unchecked return (TDerived) this; } if (translations == null) { //create an empty one, not yet initialized this.translations = new HashMap<Long, T>(4); this.emptyTranslations = new HashMap<Long, Boolean>(4); } if (language == FxLanguage.SYSTEM_ID) throw new FxInvalidParameterException("language", "ex.content.value.invalid.multilanguage.sys").asRuntimeException(); if(this.XPath != null && this.changeListener != null && value != null) { if(this.isEmpty()) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Add); else { if(!value.equals(translations.get(language))) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Update); } } boolean wasEmpty = this.changeListener != null && isEmpty(); //only evaluate if we have a change listener attached if (value == null) { translations.remove(language); emptyTranslations.remove(language); } else { if (!value.equals(translations.get(language))) { translations.put(language, value); } emptyTranslations.put(language, false); } if(this.XPath != null && this.changeListener != null && value == null && !wasEmpty && isEmpty()) { this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Remove); } //noinspection unchecked return (TDerived) this; }
public final TDerived setTranslation(long language, T value) { if (value instanceof FxValue) { throw new FxInvalidParameterException("value", "ex.content.invalid.translation.fxvalue", value.getClass().getCanonicalName()).asRuntimeException(); } if (value instanceof String) { try { value = this.fromString((String) value); } catch (Exception e) { // do nothing. The resulting FxValue will be invalid, // but the invalid value will be preserved. // TODO: use a "safer" concept of representing invalid translations, // since this may lead to unexpeced ClassCastExceptions in parameterized // methods expecting a <T> value } } if (!multiLanguage) { if (value == null && !isAcceptsEmptyDefaultTranslations()) { throw new FxInvalidParameterException("value", "ex.content.invalid.default.empty", getClass().getSimpleName()).asRuntimeException(); } if(this.XPath != null && this.changeListener != null) { if(value != null) { if(this.singleValueEmpty) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Add); else if(!this.singleValue.equals(value)) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Update); } else if(!this.singleValueEmpty) { this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Remove); } } //override the single value if (singleValue == null || !singleValue.equals(value)) this.singleValue = value; this.singleValueEmpty = value == null; //noinspection unchecked return (TDerived) this; } if (translations == null) { //create an empty one, not yet initialized this.translations = new HashMap<Long, T>(4); this.emptyTranslations = new HashMap<Long, Boolean>(4); } if (language == FxLanguage.SYSTEM_ID) throw new FxInvalidParameterException("language", "ex.content.value.invalid.multilanguage.sys").asRuntimeException(); if(this.XPath != null && this.changeListener != null && value != null) { if(this.isEmpty()) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Add); else { if(!value.equals(translations.get(language))) this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Update); } } boolean wasEmpty = this.changeListener != null && isEmpty(); //only evaluate if we have a change listener attached if (value == null) { translations.remove(language); emptyTranslations.remove(language); } else { if (!value.equals(translations.get(language))) { translations.put(language, value); } emptyTranslations.put(language, false); } if(this.XPath != null && this.changeListener != null && value == null && !wasEmpty && isEmpty()) { this.changeListener.onValueChanged(this.XPath, FxValueChangeListener.ChangeType.Remove); } //noinspection unchecked return (TDerived) this; }
diff --git a/src/edu/isi/pegasus/planner/catalog/transformation/client/TCQuery.java b/src/edu/isi/pegasus/planner/catalog/transformation/client/TCQuery.java index a406cdd72..d8218ba57 100644 --- a/src/edu/isi/pegasus/planner/catalog/transformation/client/TCQuery.java +++ b/src/edu/isi/pegasus/planner/catalog/transformation/client/TCQuery.java @@ -1,497 +1,501 @@ /** * Copyright 2007-2008 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.isi.pegasus.planner.catalog.transformation.client; /** * This is a TCClient class which handles the Query Operations. * * @author Gaurang Mehta [email protected] * @version $Revision$ */ import edu.isi.pegasus.planner.classes.Profile; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.planner.catalog.TransformationCatalog; import edu.isi.pegasus.planner.catalog.transformation.classes.TCType; import java.util.Iterator; import java.util.List; import java.util.Map; import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry; import edu.isi.pegasus.common.util.ProfileParser; import java.util.Date; import java.util.Comparator; import java.util.Collections; public class TCQuery extends Client { private final static int TABSPACE = 4; private final static String XML_NAMESPACE="http://pegasus.isi.edu/schema"; private final static String XML_VERSION="2.0"; public TCQuery( TransformationCatalog tc, LogManager mLogger, Map argsmap ) { this.fillArgs( argsmap ); this.tc = tc; this.mLogger = mLogger; } public void doQuery() { //SWitch for what triggers are defined. switch ( trigger ) { case 1: //query and return entire tc if ( !isxml ) { getTC(); } else { getTCXML(); } break; case 2: //query lfns getLfn( resource, type ); break; case 4: //query for PFN getPfn( namespace, name, version, resource, type ); break; case 8: //query for Resource getResource( type ); break; case 18: //query for LFN profiles getLfnProfile( namespace, name, version ); break; case 20: //query for PFN profiles getPfnProfile( pfn, resource, type ); break; default: mLogger.log( "Wrong trigger invoked in TC Query. Try tc-client --help for a detailed help.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } /** * Get logical transformations on a given resource and/or of a particular type. * @param resource The resource on which the transformations exist * @param type the type of the transformation. */ private void getLfn( String resource, String type ) { List l = null; TCType t = ( type == null ) ? null : TCType.valueOf( type ); try { mLogger.log( "Querying the TC for logical names on resource " + resource + " and type " + t, LogManager.DEBUG_MESSAGE_LEVEL ); l = tc.getTCLogicalNames( resource, t ); } catch ( Exception e ) { mLogger.log( "Unable to query for logicalnames", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { //int[] count = ( int[] ) l.get( l.size() - 1 ); int[] count = { 0, 0}; //l.remove( l.size() - 1 ); for ( Iterator itr = l.iterator(); itr.hasNext(); ) { String[] s = ( String[] ) itr.next(); columnLength(s, count); } System.out.println( "#RESID" + getSpace( count[ 0 ], "#RESID".length() ) + " LTX" + getSpace( count[ 1 ], " LTX".length() ) + "TYPE" ); System.out.println( "" ); for ( Iterator i = l.iterator(); i.hasNext(); ) { String[] s = ( String[] ) i.next(); System.out.println( " " + s[ 0 ] + getSpace( count[ 0 ], s[ 0 ].length() ) + s[ 1 ] + getSpace( count[ 1 ], s[ 1 ].length() ) + s[ 2 ] ); } } else { mLogger.log( "No Logical Transformations found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } /** * Get physical transformation for a particular logical transformation and/or on a resource and/or of a particular type * @param namespace String Namespace for the transformation. * @param name String Logical name for the transformation. * @param version String Version for the transformation. * @param resource String The resource for the transformation * @param type String The type of the transformation. */ private void getPfn( String namespace, String name, String version, String resource, String type ) { if ( name != null ) { List<TransformationCatalogEntry> l = null; TCType t = ( type == null ) ? null : TCType.valueOf( type ); try { mLogger.log( "Querying the TC for physical names for lfn " + lfn + " resource " + resource + " type " + type, LogManager.DEBUG_MESSAGE_LEVEL ); l = tc.lookupNoProfiles( namespace, name, version, resource, t ); } catch ( Exception e ) { mLogger.log( "Unable to query for physical names", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { //int[] count = ( int[] ) l.get( l.size() - 1 ); int count[] = { 0, 0, 0}; //l.remove( l.size() - 1 ); for ( TransformationCatalogEntry entry : l ) { String[] s = { entry.getResourceId(), entry.getPhysicalTransformation(), entry.getType().toString(), entry.getVDSSysInfo().toString()}; columnLength(s, count); } System.out.println( "#RESID" + getSpace( count[ 0 ], "#RESID".length() ) + " LTX" + getSpace( lfn.length(), " LTX".length() ) + " PFN" + getSpace( count[ 1 ], "PFN".length() ) + " TYPE" + getSpace( count[ 2 ], "TYPE".length() ) + " SYSINFO" ); System.out.println( "" ); - for ( Iterator i = l.iterator(); i.hasNext(); ) { - String[] s = ( String[] ) i.next(); + for ( TransformationCatalogEntry entry : l ) { + String[] s = { + entry.getResourceId(), + entry.getPhysicalTransformation(), + entry.getType().toString(), + entry.getVDSSysInfo().toString()}; System.out.println( s[ 0 ] + getSpace( count[ 0 ], s[ 0 ].length() ) + lfn + getSpace( lfn.length(), lfn.length() ) + s[ 1 ] + getSpace( count[ 1 ], s[ 1 ].length() ) + s[ 2 ] + getSpace( count[ 2 ], s[ 2 ].length() ) + s[ 3 ] ); } } else { mLogger.log( "No Physical Transformations found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } else { mLogger.log( "Provide an lfn to list the pfns", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } /** * Get the LFn profiles associated with a logical transformation * @param namespace String * @param name String * @param version String */ private void getLfnProfile( String namespace, String name, String version ) { if ( name != null ) { List l = null; try { mLogger.log( "Querying the TC for Profiles for lfn " + lfn, LogManager.DEBUG_MESSAGE_LEVEL ); l = tc.lookupLFNProfiles( namespace, name, version ); } catch ( Exception e ) { mLogger.log( "Unable to query the lfn profiles", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { System.out.println( "LFN Profiles :" ); for ( Iterator i = l.iterator(); i.hasNext(); ) { System.out.println( " " + ( Profile ) i.next() ); } } else { mLogger.log( "No LFN Profiles found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } else { mLogger.log( "Provide an lfn to list the lfn profiles", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } /** * Get the profiles associated with a physical transformation. * @param pfn String * @param resource String * @param type String */ private void getPfnProfile( String pfn, String resource, String type ) { if ( pfn != null && resource != null && type != null ) { List l = null; try { mLogger.log( "Query the TC for profiles with pfn=" + pfn + " type=" + type + " resource=" + resource, LogManager.FATAL_MESSAGE_LEVEL ); l = tc.lookupPFNProfiles( pfn, resource, TCType.valueOf( type ) ); } catch ( Exception e ) { mLogger.log( "Unable to query the pfn profiles", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { System.out.println( "PFN Profiles :" ); for ( Iterator i = l.iterator(); i.hasNext(); ) { System.out.println( " " + ( Profile ) i.next() ); } } else { mLogger.log( "No PFN Profiles found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } else { mLogger.log( "Please provide an pfn, resource and type to list the pfn profiles", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } /** * Get and print the Resource entries for a given logical transformation and transformation type * @param type the type of the transformation * @throws Exception Throws all kinds of exception */ private void getResource( String type ) { List l = null; TCType t = ( type == null ) ? null : TCType.valueOf( type ); try { l = tc.lookupSites( namespace, name, version, t ); } catch ( Exception e ) { mLogger.log( "Unable to query TC for resources", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { System.out.println( "Resources :" ); for ( Iterator i = l.iterator(); i.hasNext(); ) { System.out.println( " " + ( String ) i.next() ); } } else { mLogger.log( "No resources found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } /** * Print all the contents of the TC in pretty print */ private void getTC() { try { List l = tc.getContents(); if (l!=null && !l.isEmpty() ) { //this means entries are there. //get the pretty print column size information. int[] count = {0, 0, 0, 0, 0}; for ( Iterator i = l.iterator(); i.hasNext(); ) { TransformationCatalogEntry tcentry = ( TransformationCatalogEntry ) i.next(); String[] s = {tcentry.getResourceId(), tcentry.getLogicalTransformation(), tcentry.getPhysicalTransformation(), tcentry.getType().toString(), tcentry.getVDSSysInfo().toString(), ( ( tcentry.getProfiles() != null ) ? ProfileParser.combine( tcentry.getProfiles() ) : "NULL" )}; columnLength( s, count ); } System.out.println( "#RESID" + getSpace( count[ 0 ], "#RESID".length() ) + " LTX" + getSpace( count[ 1 ], " LTX".length() ) + " PTX" + getSpace( count[ 2 ], " PTX".length() ) + " TYPE" + getSpace( count[ 3 ], "TYPE".length() ) + " SYSINFO" + getSpace( count[ 4 ], "SYSINFO".length() ) + " PROFILES" ); System.out.println( "" ); //start printing the results. for ( Iterator i = l.iterator(); i.hasNext(); ) { TransformationCatalogEntry tcentry = ( TransformationCatalogEntry ) i.next(); StringBuffer sb=new StringBuffer(); sb.append(tcentry.getResourceId()); sb.append(getSpace(count[0],tcentry.getResourceId().length())); sb.append(tcentry.getLogicalTransformation()); sb.append(getSpace( count[ 1 ],tcentry.getLogicalTransformation().length())); sb.append(tcentry.getPhysicalTransformation()); sb.append(getSpace(count[2],tcentry.getPhysicalTransformation().length())); sb.append(tcentry.getType()); sb.append(getSpace(count[3],tcentry.getType().toString().length())); sb.append(tcentry.getVDSSysInfo()); sb.append(getSpace(count[4],tcentry.getVDSSysInfo().toString().length())); if( tcentry.getProfiles() != null ) { sb.append(ProfileParser.combine( tcentry.getProfiles())); } else { sb.append("NULL"); } System.out.println( sb ); } } else { mLogger.log( "No Entries found in the TC.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } catch ( Exception e ) { mLogger.log( "Unable to query entire TC", LogManager.FATAL_MESSAGE_LEVEL ); mLogger.log(convertException(e,mLogger.getLevel()),LogManager.FATAL_MESSAGE_LEVEL); System.exit( 1 ); } } private void getTCXML() { StringBuffer out = new StringBuffer(); out.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ); out.append( "<!--Generated " + new Date().toString() + "-->\n" ); out.append( "<!--Generated by " + System.getProperty( "user.name" ) + " [" + System.getProperty( "user.country" ) + "] " + "-->\n" ); out.append( "<transformationcatalog" ); out.append( " xmlns=\""+XML_NAMESPACE+"/transformationcatalog\"" ); out.append( " xsi:schemaLocation=\""+XML_NAMESPACE+"transformationcatalog "); out.append( XML_NAMESPACE+"/tc-"+XML_VERSION+".xsd\"" ); out.append( " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" ); out.append( " version=\""+XML_VERSION+"\">\n" ); try { List l=tc.getContents(); Collections.sort(l,new LFNComparator()); String prev=""; String current=""; for ( Iterator i = l.iterator(); i.hasNext(); ) { TransformationCatalogEntry tcEntry = ( TransformationCatalogEntry ) i.next(); current=tcEntry.getLogicalTransformation(); if(!current.equals(prev)){ if(!prev.equals("")){ out.append("\t</lfn>\n"); } out.append( "\t<lfn namespace=\"" ); if ( tcEntry.getLogicalNamespace() != null ) { out.append( tcEntry.getLogicalNamespace() ); } out.append( "\" name=\"" ) .append( tcEntry.getLogicalName() ) .append( "\" version=\"" ); if ( tcEntry.getLogicalVersion() != null ) { out.append( tcEntry.getLogicalVersion() ); } out.append( "\">\n" ); prev=current; } out.append( tcEntry.toXML() ); } out.append( "\t</lfn>\n" ); out.append( "</transformationcatalog>" ); } catch (Exception e) { mLogger.log("Unable to query entire TC",LogManager.ERROR_MESSAGE_LEVEL); } System.out.println( out ); } /** * Gets the required space for pretty printing. * @param maxlength int * @param currlength int * @return String */ private static String getSpace( int maxlength, int currlength ) { int length = maxlength + TABSPACE - currlength; StringBuffer sb = new StringBuffer( length ); for ( int i = 0; i < length; i++ ) { sb.append( " " ); } return sb.toString(); } /** * Computes the maximum column lenght for pretty printing. * * @param s String[] * @param length int[] */ private static void columnLength( String[] s, int[] length ) { for ( int i = 0; i < length.length; i++ ) { if ( s[ i ].length() > length[ i ] ) { length[ i ] = s[ i ].length(); } } } /** * The comparator that is used to group the RLSAttributeObject objects by the * value in the key field. This comparator should only be used for grouping * purposes not in Sets or Maps etc. */ private class LFNComparator implements Comparator { /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer if the first argument is * less than, equal to, or greater than the specified object. The * TransformationCatalogEntry object are compared by their lfn field. * * @param o1 is the first object to be compared. * @param o2 is the second object to be compared. * * @return a negative number, zero, or a positive number, if the * object compared against is less than, equals or greater than * this object. * @exception ClassCastException if the specified object's type * prevents it from being compared to this Object. */ public int compare(Object o1, Object o2) { if (o1 instanceof TransformationCatalogEntry && o2 instanceof TransformationCatalogEntry) { return ((TransformationCatalogEntry) o1).getLogicalTransformation().compareTo(((TransformationCatalogEntry) o2).getLogicalTransformation()); } else { throw new ClassCastException("object is not TranformationCatalogEntry"); } } } }
true
true
private void getPfn( String namespace, String name, String version, String resource, String type ) { if ( name != null ) { List<TransformationCatalogEntry> l = null; TCType t = ( type == null ) ? null : TCType.valueOf( type ); try { mLogger.log( "Querying the TC for physical names for lfn " + lfn + " resource " + resource + " type " + type, LogManager.DEBUG_MESSAGE_LEVEL ); l = tc.lookupNoProfiles( namespace, name, version, resource, t ); } catch ( Exception e ) { mLogger.log( "Unable to query for physical names", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { //int[] count = ( int[] ) l.get( l.size() - 1 ); int count[] = { 0, 0, 0}; //l.remove( l.size() - 1 ); for ( TransformationCatalogEntry entry : l ) { String[] s = { entry.getResourceId(), entry.getPhysicalTransformation(), entry.getType().toString(), entry.getVDSSysInfo().toString()}; columnLength(s, count); } System.out.println( "#RESID" + getSpace( count[ 0 ], "#RESID".length() ) + " LTX" + getSpace( lfn.length(), " LTX".length() ) + " PFN" + getSpace( count[ 1 ], "PFN".length() ) + " TYPE" + getSpace( count[ 2 ], "TYPE".length() ) + " SYSINFO" ); System.out.println( "" ); for ( Iterator i = l.iterator(); i.hasNext(); ) { String[] s = ( String[] ) i.next(); System.out.println( s[ 0 ] + getSpace( count[ 0 ], s[ 0 ].length() ) + lfn + getSpace( lfn.length(), lfn.length() ) + s[ 1 ] + getSpace( count[ 1 ], s[ 1 ].length() ) + s[ 2 ] + getSpace( count[ 2 ], s[ 2 ].length() ) + s[ 3 ] ); } } else { mLogger.log( "No Physical Transformations found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } else { mLogger.log( "Provide an lfn to list the pfns", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } }
private void getPfn( String namespace, String name, String version, String resource, String type ) { if ( name != null ) { List<TransformationCatalogEntry> l = null; TCType t = ( type == null ) ? null : TCType.valueOf( type ); try { mLogger.log( "Querying the TC for physical names for lfn " + lfn + " resource " + resource + " type " + type, LogManager.DEBUG_MESSAGE_LEVEL ); l = tc.lookupNoProfiles( namespace, name, version, resource, t ); } catch ( Exception e ) { mLogger.log( "Unable to query for physical names", e, LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } if ( l != null ) { //int[] count = ( int[] ) l.get( l.size() - 1 ); int count[] = { 0, 0, 0}; //l.remove( l.size() - 1 ); for ( TransformationCatalogEntry entry : l ) { String[] s = { entry.getResourceId(), entry.getPhysicalTransformation(), entry.getType().toString(), entry.getVDSSysInfo().toString()}; columnLength(s, count); } System.out.println( "#RESID" + getSpace( count[ 0 ], "#RESID".length() ) + " LTX" + getSpace( lfn.length(), " LTX".length() ) + " PFN" + getSpace( count[ 1 ], "PFN".length() ) + " TYPE" + getSpace( count[ 2 ], "TYPE".length() ) + " SYSINFO" ); System.out.println( "" ); for ( TransformationCatalogEntry entry : l ) { String[] s = { entry.getResourceId(), entry.getPhysicalTransformation(), entry.getType().toString(), entry.getVDSSysInfo().toString()}; System.out.println( s[ 0 ] + getSpace( count[ 0 ], s[ 0 ].length() ) + lfn + getSpace( lfn.length(), lfn.length() ) + s[ 1 ] + getSpace( count[ 1 ], s[ 1 ].length() ) + s[ 2 ] + getSpace( count[ 2 ], s[ 2 ].length() ) + s[ 3 ] ); } } else { mLogger.log( "No Physical Transformations found.", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } } else { mLogger.log( "Provide an lfn to list the pfns", LogManager.FATAL_MESSAGE_LEVEL ); System.exit( 1 ); } }
diff --git a/src/com/CompArch/ReservationStation.java b/src/com/CompArch/ReservationStation.java index 9e1624c..25b3f18 100644 --- a/src/com/CompArch/ReservationStation.java +++ b/src/com/CompArch/ReservationStation.java @@ -1,164 +1,164 @@ package com.CompArch; public class ReservationStation { private Simulator sim; private IAU iau; private int depth; // Location in the private int next; private int total; // Instruction memory section private int[][] instructBuffer; // Location of each instruction in the reorder buffer private int robLoc[]; // Whether inputs are available private boolean[][] available; public boolean isFree () { if (total > 0 || !iau.free) return false; else return true; } public ReservationStation (Simulator s, int size) { depth = size; next = 0; total = 0; instructBuffer = new int[size][4]; robLoc = new int[size]; iau = new IAU(s); available = new boolean[size][2]; for (int i = 0; i < size; i++) { available[i][0] = false; available[i][1] = false; } sim = s; } // Takes instruction, returns true if added to buffer, false if buffer full public boolean receive (int[] instruction) { if (total == depth) { return false; } /* Get the register values if needed*/ int toReserve[] = instruction; // Check if instruction is an overwrite boolean isWrite = instruction[0] == 1; boolean isWipe = instruction[0] == 5 && instruction[1] == instruction[2] && instruction[2] == instruction[3]; int overWrite = -1; if (isWrite || isWipe) { overWrite = sim.rrt.getReg(instruction[1]); } if (instruction[0] > 0 && instruction[0] < 19) { - toReserve[1] = sim.rrt.getReg(instruction[1]); + //toReserve[1] = sim.rrt.getReg(instruction[1]); } total++; int dest = (next + total - 1) % depth; /*System.out.println("--"); System.out.println(next + " " + total + " " + depth); System.out.println((next + total - 1) % depth); System.out.println("--");*/ instructBuffer[dest] = instruction; // Add instruction to the reorder buffer robLoc[dest] = sim.rob.insert(instruction, overWrite); // Get available operands /* if (sim.regFile.isFree(instruction[2])) { instructBuffer[dest][2] = sim.regFile.get(instruction[2]); available[dest][0] = true; } int in = instruction[0]; if (in != 3 && in != 9 && in != 11 && in != 13 && in != 14 && in != 16) { if (sim.regFile.isFree(instruction[3])) { instructBuffer[dest][3] = sim.regFile.get(instruction[3]); available[dest][1] = true; } } if (in != 0 && in != 19) { //Mark as issued } */ return true; } public void tick () { this.dispatch(); iau.tick(); } void dispatch () { // perform dependancy and IAU availability checking, if ready then send /*System.out.println(instructBuffer[next][0] + " " + instructBuffer[next][1] + " " + instructBuffer[next][2] + " " + instructBuffer[next][3]);*/ boolean depends = false; /* if (!sim.regFile.isFree(instructBuffer[next][2])) { depends = true; System.out.println(instructBuffer[next][2] + " NOT FREE1"); } int in = instructBuffer[next][0]; if (in != 3 && in != 9 && in != 11 && in != 13 && in != 14 && in != 16) { if (!sim.regFile.isFree(instructBuffer[next][3])) { depends = true; System.out.println(instructBuffer[next][3] + " NOT FREE2"); } } depends = false;*/ if (iau.free && total > 0 && !depends) { //System.out.println(instructBuffer[next][2] + " " + instructBuffer[next][3] + " FREE"); /*System.out.println("WORKING: " + total); System.out.println("running: " + instructBuffer[next][0] + " " + instructBuffer[next][1] + " " + instructBuffer[next][2] + " " + instructBuffer[next][3]);*/ iau.read(instructBuffer[next][0], instructBuffer[next][1], instructBuffer[next][2], instructBuffer[next][3], robLoc[next]); next++; next = next % depth; total--; } //System.out.println("---"); } }
true
true
public boolean receive (int[] instruction) { if (total == depth) { return false; } /* Get the register values if needed*/ int toReserve[] = instruction; // Check if instruction is an overwrite boolean isWrite = instruction[0] == 1; boolean isWipe = instruction[0] == 5 && instruction[1] == instruction[2] && instruction[2] == instruction[3]; int overWrite = -1; if (isWrite || isWipe) { overWrite = sim.rrt.getReg(instruction[1]); } if (instruction[0] > 0 && instruction[0] < 19) { toReserve[1] = sim.rrt.getReg(instruction[1]); } total++; int dest = (next + total - 1) % depth; /*System.out.println("--"); System.out.println(next + " " + total + " " + depth); System.out.println((next + total - 1) % depth); System.out.println("--");*/ instructBuffer[dest] = instruction; // Add instruction to the reorder buffer robLoc[dest] = sim.rob.insert(instruction, overWrite); // Get available operands /* if (sim.regFile.isFree(instruction[2])) { instructBuffer[dest][2] = sim.regFile.get(instruction[2]); available[dest][0] = true; } int in = instruction[0]; if (in != 3 && in != 9 && in != 11 && in != 13 && in != 14 && in != 16) { if (sim.regFile.isFree(instruction[3])) { instructBuffer[dest][3] = sim.regFile.get(instruction[3]); available[dest][1] = true; } } if (in != 0 && in != 19) { //Mark as issued } */ return true; }
public boolean receive (int[] instruction) { if (total == depth) { return false; } /* Get the register values if needed*/ int toReserve[] = instruction; // Check if instruction is an overwrite boolean isWrite = instruction[0] == 1; boolean isWipe = instruction[0] == 5 && instruction[1] == instruction[2] && instruction[2] == instruction[3]; int overWrite = -1; if (isWrite || isWipe) { overWrite = sim.rrt.getReg(instruction[1]); } if (instruction[0] > 0 && instruction[0] < 19) { //toReserve[1] = sim.rrt.getReg(instruction[1]); } total++; int dest = (next + total - 1) % depth; /*System.out.println("--"); System.out.println(next + " " + total + " " + depth); System.out.println((next + total - 1) % depth); System.out.println("--");*/ instructBuffer[dest] = instruction; // Add instruction to the reorder buffer robLoc[dest] = sim.rob.insert(instruction, overWrite); // Get available operands /* if (sim.regFile.isFree(instruction[2])) { instructBuffer[dest][2] = sim.regFile.get(instruction[2]); available[dest][0] = true; } int in = instruction[0]; if (in != 3 && in != 9 && in != 11 && in != 13 && in != 14 && in != 16) { if (sim.regFile.isFree(instruction[3])) { instructBuffer[dest][3] = sim.regFile.get(instruction[3]); available[dest][1] = true; } } if (in != 0 && in != 19) { //Mark as issued } */ return true; }
diff --git a/framework/src/com/polyvi/xface/view/XStartAppView.java b/framework/src/com/polyvi/xface/view/XStartAppView.java index c6ececc2..0c7400f7 100644 --- a/framework/src/com/polyvi/xface/view/XStartAppView.java +++ b/framework/src/com/polyvi/xface/view/XStartAppView.java @@ -1,171 +1,173 @@ /* Copyright 2012-2013, Polyvi Inc. (http://polyvi.github.io/openxface) This program is distributed under the terms of the GNU General Public License. This file is part of xFace. xFace 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. xFace 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 xFace. If not, see <http://www.gnu.org/licenses/>. */ package com.polyvi.xface.view; import java.util.Iterator; import android.content.Context; import android.util.Pair; import com.polyvi.xface.ams.XAppList; import com.polyvi.xface.ams.XAppManagement; import com.polyvi.xface.app.XApplication; import com.polyvi.xface.app.XApplicationCreator; import com.polyvi.xface.app.XIApplication; import com.polyvi.xface.core.XISystemContext; import com.polyvi.xface.event.XEvent; import com.polyvi.xface.event.XEventType; import com.polyvi.xface.event.XISystemEventReceiver; import com.polyvi.xface.event.XSystemEventCenter; public class XStartAppView extends XAppWebView implements XISystemEventReceiver { private final static int ONRESUME = 0; private final static int ONPAUSE = 1; private final static int ONDESTROY = 2; private XAppManagement mAms; public XStartAppView(XISystemContext systemContext) { super(systemContext); registerSystemEventReceiver(); } /** * 注册事件接收器 */ private void registerSystemEventReceiver() { XSystemEventCenter.getInstance().registerReceiver(this, XEventType.XAPP_MESSAGE); XSystemEventCenter.getInstance().registerReceiver(this, XEventType.CLOSE_APP); XSystemEventCenter.getInstance().registerReceiver(this, XEventType.CLEAR_MEMORY_CACHE); } public void setAppManagement(XAppManagement ams) { mAms = ams; } @Override public void handlePause(boolean keepRunning) { if (mAms != null) { iterateApp(ONPAUSE, keepRunning); } super.handlePause(keepRunning); } @Override public void handleResume(boolean keepRunning, boolean activityResultKeepRunning) { if (mAms != null) { iterateApp(ONRESUME, keepRunning, activityResultKeepRunning); } super.handleResume(keepRunning, activityResultKeepRunning); } private void iterateApp(int operate, boolean... objs) { XAppList list = mAms.getAppList(); Iterator<XIApplication> it = list.iterator(); while (it.hasNext()) { XIApplication app = it.next(); XApplication webApp = XApplicationCreator.toWebApp(app); if (null != webApp) { doOperate(webApp.getView(), operate, objs); } } } private void doOperate(XAppWebView appView, int operate, boolean... objs) { if (null == appView) { return; } switch (operate) { case ONRESUME: appView.handleResume(objs[0], objs[1]); break; case ONPAUSE: appView.handlePause(objs[0]); break; case ONDESTROY: appView.handleDestroy(); break; } } @Override public void handleDestroy() { if (mAms != null) { iterateApp(ONDESTROY); } super.handleDestroy(); } /** * 关闭app * * @param viewId * 须要被关闭app对应的viewid */ @Override public void handleCloseApplication(int viewId) { if (getViewId() != viewId) { mAms.closeApp(viewId); return; } super.handleCloseApplication(viewId); } /** * 处理xapp发送的消息数据 * * @param view * 发消息app对应的view * @param msgData * 消息数据 */ public void handleXAppMessage(XAppWebView view, String msgData) { if (null != mAms) { mAms.handleAppMessage(mOwnerApp, view, msgData); } } @Override public void onReceived(Context context, XEvent evt) { if (evt.getType() == XEventType.XAPP_MESSAGE) { @SuppressWarnings("unchecked") Pair<XAppWebView, String> data = (Pair<XAppWebView, String>) evt .getData(); handleXAppMessage(data.first, data.second); } else if (evt.getType() == XEventType.CLOSE_APP) { int viewId = (Integer) evt.getData(); handleCloseApplication(viewId); } else if (evt.getType() == XEventType.CLEAR_MEMORY_CACHE) { mSystemCtx.runOnUiThread(new Runnable() { @Override public void run() { mOwnerApp.clearCache(false); } }); + } else { + super.onReceived(context, evt); } } }
true
true
public void onReceived(Context context, XEvent evt) { if (evt.getType() == XEventType.XAPP_MESSAGE) { @SuppressWarnings("unchecked") Pair<XAppWebView, String> data = (Pair<XAppWebView, String>) evt .getData(); handleXAppMessage(data.first, data.second); } else if (evt.getType() == XEventType.CLOSE_APP) { int viewId = (Integer) evt.getData(); handleCloseApplication(viewId); } else if (evt.getType() == XEventType.CLEAR_MEMORY_CACHE) { mSystemCtx.runOnUiThread(new Runnable() { @Override public void run() { mOwnerApp.clearCache(false); } }); } }
public void onReceived(Context context, XEvent evt) { if (evt.getType() == XEventType.XAPP_MESSAGE) { @SuppressWarnings("unchecked") Pair<XAppWebView, String> data = (Pair<XAppWebView, String>) evt .getData(); handleXAppMessage(data.first, data.second); } else if (evt.getType() == XEventType.CLOSE_APP) { int viewId = (Integer) evt.getData(); handleCloseApplication(viewId); } else if (evt.getType() == XEventType.CLEAR_MEMORY_CACHE) { mSystemCtx.runOnUiThread(new Runnable() { @Override public void run() { mOwnerApp.clearCache(false); } }); } else { super.onReceived(context, evt); } }
diff --git a/src/main/java/org/cytoscape/rest/internal/NodeViewListener.java b/src/main/java/org/cytoscape/rest/internal/NodeViewListener.java index 38dcb62..0263f86 100644 --- a/src/main/java/org/cytoscape/rest/internal/NodeViewListener.java +++ b/src/main/java/org/cytoscape/rest/internal/NodeViewListener.java @@ -1,60 +1,60 @@ package org.cytoscape.rest.internal; import java.util.HashSet; import java.util.Properties; import org.cytoscape.model.CyNode; import org.cytoscape.property.CyProperty; import org.cytoscape.view.layout.CyLayoutAlgorithm; import org.cytoscape.view.layout.CyLayoutAlgorithmManager; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.View; import org.cytoscape.view.model.events.AddedNodeViewsEvent; import org.cytoscape.view.model.events.AddedNodeViewsListener; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.work.TaskIterator; import org.cytoscape.work.TaskManager; public class NodeViewListener implements AddedNodeViewsListener { private static final String DEF_LAYOUT = "force-directed"; private VisualMappingManager visMan; private CyLayoutAlgorithmManager layMan; private TaskManager tm; private Properties props; public NodeViewListener(VisualMappingManager visMan, CyLayoutAlgorithmManager layMan, TaskManager tm, CyProperty<Properties> cyPropertyServiceRef) { this.visMan = visMan; this.layMan = layMan; this.tm = tm; this.props = cyPropertyServiceRef.getProperties(); } public void handleEvent(AddedNodeViewsEvent e) { //update layout automatically (of new nodes) CyNetworkView networkView = e.getSource(); VisualStyle style = visMan.getVisualStyle(networkView); for (View<CyNode> v : e.getNodeViews()) { style.apply(networkView.getModel().getRow(v.getModel()), networkView.getNodeView(v.getModel())); } - String pref = CyLayoutAlgorithmManager.DEFAULT_LAYOUT_NAME; + String pref = CyLayoutAlgorithmManager.DEFAULT_LAYOUT_NAME;/* if (props != null) - pref = props.getProperty("preferredLayoutAlgorithm", DEF_LAYOUT); + pref = props.getProperty("preferredLayoutAlgorithm", DEF_LAYOUT);*/ final CyLayoutAlgorithm layout = layMan.getLayout(pref); if (layout != null) { TaskIterator ti = layout.createTaskIterator(networkView, layout.getDefaultLayoutContext(), new HashSet<View<CyNode>>(e.getNodeViews()), ""); tm.execute(ti); } else { throw new IllegalArgumentException("Couldn't find layout algorithm: " + pref); } networkView.updateView(); } }
false
true
public void handleEvent(AddedNodeViewsEvent e) { //update layout automatically (of new nodes) CyNetworkView networkView = e.getSource(); VisualStyle style = visMan.getVisualStyle(networkView); for (View<CyNode> v : e.getNodeViews()) { style.apply(networkView.getModel().getRow(v.getModel()), networkView.getNodeView(v.getModel())); } String pref = CyLayoutAlgorithmManager.DEFAULT_LAYOUT_NAME; if (props != null) pref = props.getProperty("preferredLayoutAlgorithm", DEF_LAYOUT); final CyLayoutAlgorithm layout = layMan.getLayout(pref); if (layout != null) { TaskIterator ti = layout.createTaskIterator(networkView, layout.getDefaultLayoutContext(), new HashSet<View<CyNode>>(e.getNodeViews()), ""); tm.execute(ti); } else { throw new IllegalArgumentException("Couldn't find layout algorithm: " + pref); } networkView.updateView(); }
public void handleEvent(AddedNodeViewsEvent e) { //update layout automatically (of new nodes) CyNetworkView networkView = e.getSource(); VisualStyle style = visMan.getVisualStyle(networkView); for (View<CyNode> v : e.getNodeViews()) { style.apply(networkView.getModel().getRow(v.getModel()), networkView.getNodeView(v.getModel())); } String pref = CyLayoutAlgorithmManager.DEFAULT_LAYOUT_NAME;/* if (props != null) pref = props.getProperty("preferredLayoutAlgorithm", DEF_LAYOUT);*/ final CyLayoutAlgorithm layout = layMan.getLayout(pref); if (layout != null) { TaskIterator ti = layout.createTaskIterator(networkView, layout.getDefaultLayoutContext(), new HashSet<View<CyNode>>(e.getNodeViews()), ""); tm.execute(ti); } else { throw new IllegalArgumentException("Couldn't find layout algorithm: " + pref); } networkView.updateView(); }
diff --git a/src/com/placella/bmi/MainActivity.java b/src/com/placella/bmi/MainActivity.java index 4ee0466..c7d4239 100644 --- a/src/com/placella/bmi/MainActivity.java +++ b/src/com/placella/bmi/MainActivity.java @@ -1,108 +1,108 @@ package com.placella.bmi; import com.placella.bmi.R; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private int imperialHeight; private int imperialWeight; private int metricHeight; private int metricWeight; private final int IMPERIAL = 0; private final int METRIC = 1; private SharedPreferences prefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prefs = getSharedPreferences("bmi_values", 0); imperialHeight = prefs.getInt("imperialHeight", 0); - imperialWeight = prefs.getInt("view_mode", 0); + imperialWeight = prefs.getInt("imperialWeight", 0); metricHeight = prefs.getInt("metricHeight", 0); metricWeight = prefs.getInt("metricWeight", 0); Button button = (Button) findViewById(R.id.choose_imperial); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleClick(true, imperialHeight, imperialWeight, IMPERIAL); } }); button = (Button) findViewById(R.id.choose_metric); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleClick(false, metricHeight, metricWeight, METRIC); } }); } private void handleClick(boolean imperial, int height, int weight, int requestCode) { Bundle b = new Bundle(); b.putBoolean("imperial", imperial); b.putInt("height", height); b.putInt("weight", weight); Intent intent = new Intent(this, DataInput.class); intent.putExtras(b); startActivityForResult(intent, requestCode); } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == IMPERIAL) { imperialHeight = intent.getIntExtra("height", 0); imperialWeight = intent.getIntExtra("weight", 0); } else { metricHeight = intent.getIntExtra("height", 0); metricWeight = intent.getIntExtra("weight", 0); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { MenuHandler.onOptionsItemSelected(item, this); return super.onOptionsItemSelected(item); } protected void onPause() { super.onPause(); SharedPreferences.Editor editor = prefs.edit(); editor.putInt("imperialHeight", imperialHeight); editor.putInt("imperialWeight", imperialWeight); editor.putInt("metricHeight", metricHeight); editor.putInt("metricWeight", metricWeight); editor.commit(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("imperialHeight", imperialHeight); outState.putInt("imperialWeight", imperialWeight); outState.putInt("metricHeight", metricHeight); outState.putInt("metricWeight", metricWeight); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); imperialHeight = savedInstanceState.getInt("imperialHeight"); imperialWeight = savedInstanceState.getInt("imperialWeight"); metricHeight = savedInstanceState.getInt("metricHeight"); metricWeight = savedInstanceState.getInt("metricWeight"); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prefs = getSharedPreferences("bmi_values", 0); imperialHeight = prefs.getInt("imperialHeight", 0); imperialWeight = prefs.getInt("view_mode", 0); metricHeight = prefs.getInt("metricHeight", 0); metricWeight = prefs.getInt("metricWeight", 0); Button button = (Button) findViewById(R.id.choose_imperial); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleClick(true, imperialHeight, imperialWeight, IMPERIAL); } }); button = (Button) findViewById(R.id.choose_metric); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleClick(false, metricHeight, metricWeight, METRIC); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prefs = getSharedPreferences("bmi_values", 0); imperialHeight = prefs.getInt("imperialHeight", 0); imperialWeight = prefs.getInt("imperialWeight", 0); metricHeight = prefs.getInt("metricHeight", 0); metricWeight = prefs.getInt("metricWeight", 0); Button button = (Button) findViewById(R.id.choose_imperial); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleClick(true, imperialHeight, imperialWeight, IMPERIAL); } }); button = (Button) findViewById(R.id.choose_metric); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleClick(false, metricHeight, metricWeight, METRIC); } }); }
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java index 5366bd025..d6e11d7f4 100644 --- a/src/com/android/settings/TextToSpeechSettings.java +++ b/src/com/android/settings/TextToSpeechSettings.java @@ -1,721 +1,720 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import static android.provider.Settings.Secure.TTS_USE_DEFAULTS; import static android.provider.Settings.Secure.TTS_DEFAULT_RATE; import static android.provider.Settings.Secure.TTS_DEFAULT_LANG; import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY; import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT; import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH; import static android.provider.Settings.Secure.TTS_ENABLED_PLUGINS; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; import android.preference.CheckBoxPreference; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.speech.tts.TextToSpeech; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; public class TextToSpeechSettings extends PreferenceActivity implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener, TextToSpeech.OnInitListener { private static final String TAG = "TextToSpeechSettings"; private static final String SYSTEM_TTS = "com.svox.pico"; private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example"; private static final String KEY_TTS_INSTALL_DATA = "tts_install_data"; private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings"; private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate"; private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang"; private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country"; private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant"; private static final String KEY_TTS_DEFAULT_SYNTH = "tts_default_synth"; private static final String KEY_PLUGIN_ENABLED_PREFIX = "ENABLED_"; private static final String KEY_PLUGIN_SETTINGS_PREFIX = "SETTINGS_"; // TODO move default Locale values to TextToSpeech.Engine private static final String DEFAULT_LANG_VAL = "eng"; private static final String DEFAULT_COUNTRY_VAL = "USA"; private static final String DEFAULT_VARIANT_VAL = ""; private static final String LOCALE_DELIMITER = "-"; private static final String FALLBACK_TTS_DEFAULT_SYNTH = TextToSpeech.Engine.DEFAULT_SYNTH; private Preference mPlayExample = null; private Preference mInstallData = null; private CheckBoxPreference mUseDefaultPref = null; private ListPreference mDefaultRatePref = null; private ListPreference mDefaultLocPref = null; private ListPreference mDefaultSynthPref = null; private String mDefaultLanguage = null; private String mDefaultCountry = null; private String mDefaultLocVariant = null; private String mDefaultEng = ""; private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE; // Array of strings used to demonstrate TTS in the different languages. private String[] mDemoStrings; // Index of the current string to use for the demo. private int mDemoStringIndex = 0; private boolean mEnableDemo = false; private boolean mVoicesMissing = false; private TextToSpeech mTts = null; private boolean mTtsStarted = false; /** * Request code (arbitrary value) for voice data check through * startActivityForResult. */ private static final int VOICE_DATA_INTEGRITY_CHECK = 1977; private static final int GET_SAMPLE_TEXT = 1983; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tts_settings); addEngineSpecificSettings(); mDemoStrings = getResources().getStringArray(R.array.tts_demo_strings); setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM); mEnableDemo = false; mTtsStarted = false; mTts = new TextToSpeech(this, this); } @Override protected void onStart() { super.onStart(); if (mTtsStarted){ // whenever we return to this screen, we don't know the state of the // system, so we have to recheck that we can play the demo, or it must be disabled. // TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount initClickers(); updateWidgetState(); checkVoiceData(); } } @Override protected void onDestroy() { super.onDestroy(); if (mTts != null) { mTts.shutdown(); } } private void addEngineSpecificSettings() { PreferenceGroup enginesCategory = (PreferenceGroup) findPreference("tts_engines_section"); Intent intent = new Intent("android.intent.action.START_TTS_ENGINE"); ResolveInfo[] enginesArray = new ResolveInfo[0]; PackageManager pm = getPackageManager(); enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray); for (int i = 0; i < enginesArray.length; i++) { String prefKey = ""; final String pluginPackageName = enginesArray[i].activityInfo.packageName; if (!enginesArray[i].activityInfo.packageName.equals(SYSTEM_TTS)) { CheckBoxPreference chkbxPref = new CheckBoxPreference(this); prefKey = KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName; chkbxPref.setKey(prefKey); chkbxPref.setTitle(enginesArray[i].loadLabel(pm)); enginesCategory.addPreference(chkbxPref); } if (pluginHasSettings(pluginPackageName)) { Preference pref = new Preference(this); prefKey = KEY_PLUGIN_SETTINGS_PREFIX + pluginPackageName; pref.setKey(prefKey); pref.setTitle(enginesArray[i].loadLabel(pm)); CharSequence settingsLabel = getResources().getString( R.string.tts_engine_name_settings, enginesArray[i].loadLabel(pm)); pref.setSummary(settingsLabel); pref.setOnPreferenceClickListener(new OnPreferenceClickListener(){ public boolean onPreferenceClick(Preference preference){ Intent i = new Intent(); i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings"); startActivity(i); return true; } }); enginesCategory.addPreference(pref); } } } private boolean pluginHasSettings(String pluginPackageName) { PackageManager pm = getPackageManager(); Intent i = new Intent(); i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings"); if (pm.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY) != null){ return true; } return false; } private void initClickers() { mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE); mPlayExample.setOnPreferenceClickListener(this); mInstallData = findPreference(KEY_TTS_INSTALL_DATA); mInstallData.setOnPreferenceClickListener(this); } private void initDefaultSettings() { ContentResolver resolver = getContentResolver(); // Find the default TTS values in the settings, initialize and store the // settings if they are not found. // "Use Defaults" int useDefault = 0; mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT); try { useDefault = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS); } catch (SettingNotFoundException e) { // "use default" setting not found, initialize it useDefault = TextToSpeech.Engine.USE_DEFAULTS; Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, useDefault); } mUseDefaultPref.setChecked(useDefault == 1); mUseDefaultPref.setOnPreferenceChangeListener(this); // Default synthesis engine mDefaultSynthPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH); loadEngines(); mDefaultSynthPref.setOnPreferenceChangeListener(this); String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH); if (engine == null) { // TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech engine = FALLBACK_TTS_DEFAULT_SYNTH; Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine); } mDefaultEng = engine; // Default rate mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE); try { mDefaultRate = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE); } catch (SettingNotFoundException e) { // default rate setting not found, initialize it mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE; Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, mDefaultRate); } mDefaultRatePref.setValue(String.valueOf(mDefaultRate)); mDefaultRatePref.setOnPreferenceChangeListener(this); // Default language / country / variant : these three values map to a single ListPref // representing the matching Locale mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG); initDefaultLang(); mDefaultLocPref.setOnPreferenceChangeListener(this); } /** * Ask the current default engine to launch the matching CHECK_TTS_DATA activity * to check the required TTS files are properly installed. */ private void checkVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK); } } } /** * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity * so the required TTS files are properly installed. */ private void installVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivity(intent); } } } /** * Ask the current default engine to return a string of sample text to be * spoken to the user. */ private void getSampleText() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); // TODO (clchen): Replace Intent string with the actual // Intent defined in the list of platform Intents. intent.setAction("android.speech.tts.engine.GET_SAMPLE_TEXT"); intent.putExtra("language", mDefaultLanguage); intent.putExtra("country", mDefaultCountry); intent.putExtra("variant", mDefaultLocVariant); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, GET_SAMPLE_TEXT); } } } /** * Called when the TTS engine is initialized. */ public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { mEnableDemo = true; if (mDefaultLanguage == null) { mDefaultLanguage = Locale.getDefault().getISO3Language(); } if (mDefaultCountry == null) { mDefaultCountry = Locale.getDefault().getISO3Country(); } if (mDefaultLocVariant == null) { mDefaultLocVariant = new String(); } mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); mTts.setSpeechRate((float)(mDefaultRate/100.0f)); initDefaultSettings(); initClickers(); updateWidgetState(); checkVoiceData(); mTtsStarted = true; Log.v(TAG, "TTS engine for settings screen initialized."); } else { Log.v(TAG, "TTS engine for settings screen failed to initialize successfully."); mEnableDemo = false; } updateWidgetState(); } /** * Called when voice data integrity check returns */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } - // TODO (clchen): Add these extras to TextToSpeech.Engine ArrayList<String> available = - data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES"); + data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES); ArrayList<String> unavailable = - data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES"); + data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } } public boolean onPreferenceChange(Preference preference, Object objValue) { if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) { // "Use Defaults" int value = (Boolean)objValue ? 1 : 0; Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS, value); Log.i(TAG, "TTS use default settings is "+objValue.toString()); } else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) { // Default rate mDefaultRate = Integer.parseInt((String) objValue); try { Settings.Secure.putInt(getContentResolver(), TTS_DEFAULT_RATE, mDefaultRate); if (mTts != null) { mTts.setSpeechRate((float)(mDefaultRate/100.0f)); } Log.i(TAG, "TTS default rate is " + mDefaultRate); } catch (NumberFormatException e) { Log.e(TAG, "could not persist default TTS rate setting", e); } } else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) { // Default locale ContentResolver resolver = getContentResolver(); parseLocaleInfo((String) objValue); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); Log.v(TAG, "TTS default lang/country/variant set to " + mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant); if (mTts != null) { mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } int newIndex = mDefaultLocPref.findIndexOfValue((String)objValue); Log.v("Settings", " selected is " + newIndex); mDemoStringIndex = newIndex > -1 ? newIndex : 0; } else if (KEY_TTS_DEFAULT_SYNTH.equals(preference.getKey())) { mDefaultEng = objValue.toString(); Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, mDefaultEng); if (mTts != null) { mTts.setEngineByPackageName(mDefaultEng); mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); checkVoiceData(); } Log.v("Settings", "The default synth is: " + objValue.toString()); } return true; } /** * Called when mPlayExample or mInstallData is clicked */ public boolean onPreferenceClick(Preference preference) { if (preference == mPlayExample) { // Get the sample text from the TTS engine; onActivityResult will do // the actual speaking getSampleText(); return true; } if (preference == mInstallData) { installVoiceData(); // quit this activity so it needs to be restarted after installation of the voice data finish(); return true; } return false; } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (Utils.isMonkeyRunning()) { return false; } if (preference instanceof CheckBoxPreference) { final CheckBoxPreference chkPref = (CheckBoxPreference) preference; if (!chkPref.getKey().equals(KEY_TTS_USE_DEFAULT)){ if (chkPref.isChecked()) { chkPref.setChecked(false); AlertDialog d = (new AlertDialog.Builder(this)) .setTitle(android.R.string.dialog_alert_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(getString(R.string.tts_engine_security_warning, chkPref.getTitle())) .setCancelable(true) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { chkPref.setChecked(true); loadEngines(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create(); d.show(); } else { loadEngines(); } return true; } } return false; } private void updateWidgetState() { mPlayExample.setEnabled(mEnableDemo); mUseDefaultPref.setEnabled(mEnableDemo); mDefaultRatePref.setEnabled(mEnableDemo); mDefaultLocPref.setEnabled(mEnableDemo); mInstallData.setEnabled(mVoicesMissing); } private void parseLocaleInfo(String locale) { StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER); mDefaultLanguage = ""; mDefaultCountry = ""; mDefaultLocVariant = ""; if (tokenizer.hasMoreTokens()) { mDefaultLanguage = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultCountry = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultLocVariant = tokenizer.nextToken().trim(); } } /** * Initialize the default language in the UI and in the preferences. * After this method has been invoked, the default language is a supported Locale. */ private void initDefaultLang() { // if there isn't already a default language preference if (!hasLangPref()) { // if the current Locale is supported if (isCurrentLocSupported()) { // then use the current Locale as the default language useCurrentLocAsDefault(); } else { // otherwise use a default supported Locale as the default language useSupportedLocAsDefault(); } } // Update the language preference list with the default language and the matching // demo string (at this stage there is a default language pref) ContentResolver resolver = getContentResolver(); mDefaultLanguage = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG); mDefaultCountry = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY); mDefaultLocVariant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT); // update the demo string mDemoStringIndex = mDefaultLocPref.findIndexOfValue(mDefaultLanguage + LOCALE_DELIMITER + mDefaultCountry); if (mDemoStringIndex > -1){ mDefaultLocPref.setValueIndex(mDemoStringIndex); } } /** * (helper function for initDefaultLang() ) * Returns whether there is a default language in the TTS settings. */ private boolean hasLangPref() { String language = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_LANG); return (language != null); } /** * (helper function for initDefaultLang() ) * Returns whether the current Locale is supported by this Settings screen */ private boolean isCurrentLocSupported() { String currentLocID = Locale.getDefault().getISO3Language() + LOCALE_DELIMITER + Locale.getDefault().getISO3Country(); return (mDefaultLocPref.findIndexOfValue(currentLocID) > -1); } /** * (helper function for initDefaultLang() ) * Sets the default language in TTS settings to be the current Locale. * This should only be used after checking that the current Locale is supported. */ private void useCurrentLocAsDefault() { Locale currentLocale = Locale.getDefault(); ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, currentLocale.getISO3Language()); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, currentLocale.getISO3Country()); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, currentLocale.getVariant()); } /** * (helper function for initDefaultLang() ) * Sets the default language in TTS settings to be one known to be supported */ private void useSupportedLocAsDefault() { ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, DEFAULT_LANG_VAL); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, DEFAULT_COUNTRY_VAL); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, DEFAULT_VARIANT_VAL); } private void loadEngines() { ListPreference enginesPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH); // TODO (clchen): Try to see if it is possible to be more efficient here // and not search for plugins again. Intent intent = new Intent("android.intent.action.START_TTS_ENGINE"); ResolveInfo[] enginesArray = new ResolveInfo[0]; PackageManager pm = getPackageManager(); enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray); ArrayList<CharSequence> entries = new ArrayList<CharSequence>(); ArrayList<CharSequence> values = new ArrayList<CharSequence>(); String enabledEngines = ""; for (int i = 0; i < enginesArray.length; i++) { String pluginPackageName = enginesArray[i].activityInfo.packageName; if (pluginPackageName.equals(SYSTEM_TTS)) { entries.add(enginesArray[i].loadLabel(pm)); values.add(pluginPackageName); } else { CheckBoxPreference pref = (CheckBoxPreference) findPreference( KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName); if ((pref != null) && pref.isChecked()){ entries.add(enginesArray[i].loadLabel(pm)); values.add(pluginPackageName); enabledEngines = enabledEngines + pluginPackageName + " "; } } } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_ENABLED_PLUGINS, enabledEngines); CharSequence entriesArray[] = new CharSequence[entries.size()]; CharSequence valuesArray[] = new CharSequence[values.size()]; enginesPref.setEntries(entries.toArray(entriesArray)); enginesPref.setEntryValues(values.toArray(valuesArray)); // Set the selected engine based on the saved preference String selectedEngine = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_SYNTH); int selectedEngineIndex = enginesPref.findIndexOfValue(selectedEngine); if (selectedEngineIndex == -1){ selectedEngineIndex = enginesPref.findIndexOfValue(SYSTEM_TTS); } enginesPref.setValueIndex(selectedEngineIndex); } }
false
true
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } // TODO (clchen): Add these extras to TextToSpeech.Engine ArrayList<String> available = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES"); ArrayList<String> unavailable = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES"); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } ArrayList<String> available = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES); ArrayList<String> unavailable = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } }
diff --git a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java index de053cf91..1c707ead4 100644 --- a/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java +++ b/src/com/redhat/ceylon/compiler/loader/AbstractModelLoader.java @@ -1,2569 +1,2570 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.loader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.lang.model.type.TypeKind; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.JDKUtils; import com.redhat.ceylon.common.Versions; import com.redhat.ceylon.compiler.java.codegen.Decl; import com.redhat.ceylon.compiler.java.codegen.Naming; import com.redhat.ceylon.compiler.java.util.Timer; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.loader.mirror.AnnotatedMirror; import com.redhat.ceylon.compiler.loader.mirror.AnnotationMirror; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.mirror.FieldMirror; import com.redhat.ceylon.compiler.loader.mirror.MethodMirror; import com.redhat.ceylon.compiler.loader.mirror.PackageMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeParameterMirror; import com.redhat.ceylon.compiler.loader.mirror.VariableMirror; import com.redhat.ceylon.compiler.loader.model.FieldValue; import com.redhat.ceylon.compiler.loader.model.JavaBeanValue; import com.redhat.ceylon.compiler.loader.model.JavaMethod; import com.redhat.ceylon.compiler.loader.model.LazyClass; import com.redhat.ceylon.compiler.loader.model.LazyClassAlias; import com.redhat.ceylon.compiler.loader.model.LazyContainer; import com.redhat.ceylon.compiler.loader.model.LazyElement; import com.redhat.ceylon.compiler.loader.model.LazyInterface; import com.redhat.ceylon.compiler.loader.model.LazyInterfaceAlias; import com.redhat.ceylon.compiler.loader.model.LazyMethod; import com.redhat.ceylon.compiler.loader.model.LazyModule; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.loader.model.LazyTypeAlias; import com.redhat.ceylon.compiler.loader.model.LazyValue; import com.redhat.ceylon.compiler.typechecker.analyzer.DeclarationVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Element; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ModuleImport; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.UnknownType; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.model.ValueParameter; /** * Abstract class of a model loader that can load a model from a compiled Java representation, * while being agnostic of the reflection API used to load the compiled Java representation. * * @author Stéphane Épardaud <[email protected]> */ public abstract class AbstractModelLoader implements ModelCompleter, ModelLoader { public static final String CEYLON_LANGUAGE = "ceylon.language"; private static final String TIMER_MODEL_LOADER_CATEGORY = "model loader"; public static final String JDK_MODULE_VERSION = "7"; public static final String CEYLON_CEYLON_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ceylon"; private static final String CEYLON_MODULE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Module"; private static final String CEYLON_PACKAGE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Package"; private static final String CEYLON_IGNORE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Ignore"; private static final String CEYLON_CLASS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Class"; public static final String CEYLON_NAME_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Name"; private static final String CEYLON_SEQUENCED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Sequenced"; private static final String CEYLON_DEFAULTED_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Defaulted"; private static final String CEYLON_SATISFIED_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes"; private static final String CEYLON_CASE_TYPES_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.CaseTypes"; private static final String CEYLON_TYPE_PARAMETERS = "com.redhat.ceylon.compiler.java.metadata.TypeParameters"; private static final String CEYLON_TYPE_INFO_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeInfo"; public static final String CEYLON_ATTRIBUTE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Attribute"; public static final String CEYLON_OBJECT_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Object"; public static final String CEYLON_METHOD_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Method"; public static final String CEYLON_CONTAINER_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Container"; private static final String CEYLON_MEMBERS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Members"; private static final String CEYLON_ANNOTATIONS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Annotations"; public static final String CEYLON_VALUETYPE_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.ValueType"; public static final String CEYLON_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.Alias"; public static final String CEYLON_TYPE_ALIAS_ANNOTATION = "com.redhat.ceylon.compiler.java.metadata.TypeAlias"; private static final TypeMirror OBJECT_TYPE = simpleObjectType("java.lang.Object"); private static final TypeMirror CEYLON_OBJECT_TYPE = simpleObjectType("ceylon.language.Object"); private static final TypeMirror CEYLON_BASIC_TYPE = simpleObjectType("ceylon.language.Basic"); private static final TypeMirror CEYLON_EXCEPTION_TYPE = simpleObjectType("ceylon.language.Exception"); private static final TypeMirror CEYLON_REIFIED_TYPE_TYPE = simpleObjectType("com.redhat.ceylon.compiler.java.runtime.model.ReifiedType"); private static final TypeMirror STRING_TYPE = simpleObjectType("java.lang.String"); private static final TypeMirror CEYLON_STRING_TYPE = simpleObjectType("ceylon.language.String"); private static final TypeMirror PRIM_BOOLEAN_TYPE = simpleObjectType("boolean", TypeKind.BOOLEAN); private static final TypeMirror BOOLEAN_TYPE = simpleObjectType("java.lang.Boolean"); private static final TypeMirror CEYLON_BOOLEAN_TYPE = simpleObjectType("ceylon.language.Boolean"); private static final TypeMirror PRIM_BYTE_TYPE = simpleObjectType("byte", TypeKind.BYTE); private static final TypeMirror BYTE_TYPE = simpleObjectType("java.lang.Byte"); private static final TypeMirror PRIM_SHORT_TYPE = simpleObjectType("short", TypeKind.SHORT); private static final TypeMirror SHORT_TYPE = simpleObjectType("java.lang.Short"); private static final TypeMirror PRIM_INT_TYPE = simpleObjectType("int", TypeKind.INT); private static final TypeMirror INTEGER_TYPE = simpleObjectType("java.lang.Integer"); private static final TypeMirror PRIM_LONG_TYPE = simpleObjectType("long", TypeKind.LONG); private static final TypeMirror LONG_TYPE = simpleObjectType("java.lang.Long"); private static final TypeMirror CEYLON_INTEGER_TYPE = simpleObjectType("ceylon.language.Integer"); private static final TypeMirror PRIM_FLOAT_TYPE = simpleObjectType("float", TypeKind.FLOAT); private static final TypeMirror FLOAT_TYPE = simpleObjectType("java.lang.Float"); private static final TypeMirror PRIM_DOUBLE_TYPE = simpleObjectType("double", TypeKind.DOUBLE); private static final TypeMirror DOUBLE_TYPE = simpleObjectType("java.lang.Double"); private static final TypeMirror CEYLON_FLOAT_TYPE = simpleObjectType("ceylon.language.Float"); private static final TypeMirror PRIM_CHAR_TYPE = simpleObjectType("char", TypeKind.CHAR); private static final TypeMirror CHARACTER_TYPE = simpleObjectType("java.lang.Character"); private static final TypeMirror CEYLON_CHARACTER_TYPE = simpleObjectType("ceylon.language.Character"); private static final TypeMirror CEYLON_ARRAY_TYPE = simpleObjectType("ceylon.language.Array"); // this one has no "_" postfix because that's how we look it up protected static final String JAVA_LANG_ARRAYS = "java.lang.arrays"; protected static final String JAVA_LANG_BYTE_ARRAY = "java.lang.ByteArray"; protected static final String JAVA_LANG_SHORT_ARRAY = "java.lang.ShortArray"; protected static final String JAVA_LANG_INT_ARRAY = "java.lang.IntArray"; protected static final String JAVA_LANG_LONG_ARRAY = "java.lang.LongArray"; protected static final String JAVA_LANG_FLOAT_ARRAY = "java.lang.FloatArray"; protected static final String JAVA_LANG_DOUBLE_ARRAY = "java.lang.DoubleArray"; protected static final String JAVA_LANG_CHAR_ARRAY = "java.lang.CharArray"; protected static final String JAVA_LANG_BOOLEAN_ARRAY = "java.lang.BooleanArray"; protected static final String JAVA_LANG_OBJECT_ARRAY = "java.lang.ObjectArray"; // this one has the "_" postfix because that's what we translate it to private static final String CEYLON_ARRAYS = "com.redhat.ceylon.compiler.java.language.arrays_"; private static final String CEYLON_BYTE_ARRAY = "com.redhat.ceylon.compiler.java.language.ByteArray"; private static final String CEYLON_SHORT_ARRAY = "com.redhat.ceylon.compiler.java.language.ShortArray"; private static final String CEYLON_INT_ARRAY = "com.redhat.ceylon.compiler.java.language.IntArray"; private static final String CEYLON_LONG_ARRAY = "com.redhat.ceylon.compiler.java.language.LongArray"; private static final String CEYLON_FLOAT_ARRAY = "com.redhat.ceylon.compiler.java.language.FloatArray"; private static final String CEYLON_DOUBLE_ARRAY = "com.redhat.ceylon.compiler.java.language.DoubleArray"; private static final String CEYLON_CHAR_ARRAY = "com.redhat.ceylon.compiler.java.language.CharArray"; private static final String CEYLON_BOOLEAN_ARRAY = "com.redhat.ceylon.compiler.java.language.BooleanArray"; private static final String CEYLON_OBJECT_ARRAY = "com.redhat.ceylon.compiler.java.language.ObjectArray"; private static final TypeMirror JAVA_BYTE_ARRAY_TYPE = simpleObjectType("java.lang.ByteArray"); private static final TypeMirror JAVA_SHORT_ARRAY_TYPE = simpleObjectType("java.lang.ShortArray"); private static final TypeMirror JAVA_INT_ARRAY_TYPE = simpleObjectType("java.lang.IntArray"); private static final TypeMirror JAVA_LONG_ARRAY_TYPE = simpleObjectType("java.lang.LongArray"); private static final TypeMirror JAVA_FLOAT_ARRAY_TYPE = simpleObjectType("java.lang.FloatArray"); private static final TypeMirror JAVA_DOUBLE_ARRAY_TYPE = simpleObjectType("java.lang.DoubleArray"); private static final TypeMirror JAVA_CHAR_ARRAY_TYPE = simpleObjectType("java.lang.CharArray"); private static final TypeMirror JAVA_BOOLEAN_ARRAY_TYPE = simpleObjectType("java.lang.BooleanArray"); private static final TypeMirror JAVA_OBJECT_ARRAY_TYPE = simpleObjectType("java.lang.ObjectArray"); private static TypeMirror simpleObjectType(String name) { return new SimpleReflType(name, TypeKind.DECLARED); } private static TypeMirror simpleObjectType(String name, TypeKind kind) { return new SimpleReflType(name, TypeKind.DECLARED); } protected Map<String, Declaration> declarationsByName = new HashMap<String, Declaration>(); protected Map<Package, Unit> unitsByPackage = new HashMap<Package, Unit>(); protected TypeParser typeParser; protected Unit typeFactory; protected final Set<String> loadedPackages = new HashSet<String>(); protected final Map<String,LazyPackage> packagesByName = new HashMap<String,LazyPackage>(); protected boolean packageDescriptorsNeedLoading = false; protected boolean isBootstrap; protected ModuleManager moduleManager; protected Modules modules; protected Map<String, ClassMirror> classMirrorCache = new HashMap<String, ClassMirror>(); protected boolean binaryCompatibilityErrorRaised = false; protected Timer timer; /** * Loads a given package, if required. This is mostly useful for the javac reflection impl. * * @param packageName the package name to load * @param loadDeclarations true to load all the declarations in this package. * @return */ public abstract boolean loadPackage(String packageName, boolean loadDeclarations); /** * Looks up a ClassMirror by name. Uses cached results, and caches the result of calling lookupNewClassMirror * on cache misses. * * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ public synchronized final ClassMirror lookupClassMirror(String name){ timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ // Java array classes are not where we expect them if (JAVA_LANG_OBJECT_ARRAY.equals(name) || JAVA_LANG_BOOLEAN_ARRAY.equals(name) || JAVA_LANG_BYTE_ARRAY.equals(name) || JAVA_LANG_SHORT_ARRAY.equals(name) || JAVA_LANG_INT_ARRAY.equals(name) || JAVA_LANG_LONG_ARRAY.equals(name) || JAVA_LANG_FLOAT_ARRAY.equals(name) || JAVA_LANG_DOUBLE_ARRAY.equals(name) || JAVA_LANG_CHAR_ARRAY.equals(name) || JAVA_LANG_ARRAYS.equals(name)) { // turn them into their real class location (get rid of the "java.lang" prefix) name = "com.redhat.ceylon.compiler.java.language" + name.substring(9); } // we use containsKey to be able to cache null results if(classMirrorCache.containsKey(name)) return classMirrorCache.get(name); ClassMirror mirror = lookupNewClassMirror(name); // we even cache null results classMirrorCache.put(name, mirror); return mirror; }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } protected boolean lastPartHasLowerInitial(String name) { int index = name.lastIndexOf('.'); if (index != -1){ name = name.substring(index+1); } if(!name.isEmpty()){ char c = name.charAt(0); return Util.isLowerCase(c); } return false; } /** * Looks up a ClassMirror by name. Called by lookupClassMirror on cache misses. * * @param name the name of the Class to load * @return a ClassMirror for the specified class, or null if not found. */ protected abstract ClassMirror lookupNewClassMirror(String name); /** * Adds the given module to the set of modules from which we can load classes. * * @param module the module * @param artifact the module's artifact, if any. Can be null. */ public abstract void addModuleToClassPath(Module module, ArtifactResult artifact); /** * Returns true if the given method is overriding an inherited method (from super class or interfaces). */ protected abstract boolean isOverridingMethod(MethodMirror methodMirror); /** * Logs a warning. */ protected abstract void logWarning(String message); /** * Logs a debug message. */ protected abstract void logVerbose(String message); /** * Logs an error */ protected abstract void logError(String message); public void loadStandardModules(){ // set up the type factory Module languageModule = findOrCreateModule(CEYLON_LANGUAGE); addModuleToClassPath(languageModule, null); Package languagePackage = findOrCreatePackage(languageModule, CEYLON_LANGUAGE); typeFactory.setPackage(languagePackage); // make sure the jdk modules are loaded for(String jdkModule : JDKUtils.getJDKModuleNames()) findOrCreateModule(jdkModule); for(String jdkOracleModule : JDKUtils.getOracleJDKModuleNames()) findOrCreateModule(jdkOracleModule); /* * We start by loading java.lang and ceylon.language because we will need them no matter what. */ loadPackage("java.lang", false); loadPackage("com.redhat.ceylon.compiler.java.metadata", false); /* * We do not load the ceylon.language module from class files if we're bootstrapping it */ if(!isBootstrap){ loadPackage(CEYLON_LANGUAGE, true); loadPackage("ceylon.language.descriptor", true); } } /** * This is meant to be called if your subclass doesn't call loadStandardModules for whatever reason */ public void setupWithNoStandardModules() { Module languageModule = modules.getLanguageModule(); if(languageModule == null) throw new RuntimeException("Assertion failed: language module is null"); Package languagePackage = languageModule.getPackage(CEYLON_LANGUAGE); if(languagePackage == null) throw new RuntimeException("Assertion failed: language package is null"); typeFactory.setPackage(languagePackage); } enum ClassType { ATTRIBUTE, METHOD, OBJECT, CLASS, INTERFACE; } private ClassMirror loadClass(String pkgName, String className) { ClassMirror moduleClass = null; try{ loadPackage(pkgName, false); moduleClass = lookupClassMirror(className); }catch(Exception x){ logVerbose("[Failed to complete class "+className+"]"); } return moduleClass; } private Declaration convertToDeclaration(TypeMirror type, Scope scope, DeclarationType declarationType) { String typeName; switch(type.getKind()){ case VOID: typeName = "ceylon.language.Anything"; break; case BOOLEAN: typeName = "java.lang.Boolean"; break; case BYTE: typeName = "java.lang.Byte"; break; case CHAR: typeName = "java.lang.Character"; break; case SHORT: typeName = "java.lang.Short"; break; case INT: typeName = "java.lang.Integer"; break; case LONG: typeName = "java.lang.Long"; break; case FLOAT: typeName = "java.lang.Float"; break; case DOUBLE: typeName = "java.lang.Double"; break; case ARRAY: return ((Class)convertToDeclaration(JAVA_LANG_OBJECT_ARRAY, DeclarationType.TYPE)); case DECLARED: typeName = type.getQualifiedName(); break; case TYPEVAR: return safeLookupTypeParameter(scope, type.getQualifiedName()); case WILDCARD: // FIXME: we shouldn't even get there, because if something contains a wildcard (Foo<?>) we erase it to // IdentifiableObject, so this shouldn't be reachable. typeName = "ceylon.language.Nothing"; break; default: throw new RuntimeException("Failed to handle type "+type); } return convertToDeclaration(typeName, declarationType); } protected Declaration convertToDeclaration(ClassMirror classMirror, DeclarationType declarationType) { // avoid ignored classes if(classMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) return null; // avoid module and package descriptors too if(classMirror.getAnnotation(CEYLON_MODULE_ANNOTATION) != null || classMirror.getAnnotation(CEYLON_PACKAGE_ANNOTATION) != null) return null; List<Declaration> decls = new ArrayList<Declaration>(); boolean[] alreadyExists = new boolean[1]; Declaration decl = getOrCreateDeclaration(classMirror, declarationType, decls, alreadyExists); if (alreadyExists[0]) { return decl; } // find its module String pkgName; String qualifiedName = classMirror.getQualifiedName(); // Java array classes we pretend come from java.lang if(qualifiedName.equals(CEYLON_OBJECT_ARRAY) || qualifiedName.equals(CEYLON_BOOLEAN_ARRAY) || qualifiedName.equals(CEYLON_BYTE_ARRAY) || qualifiedName.equals(CEYLON_SHORT_ARRAY) || qualifiedName.equals(CEYLON_INT_ARRAY) || qualifiedName.equals(CEYLON_LONG_ARRAY) || qualifiedName.equals(CEYLON_FLOAT_ARRAY) || qualifiedName.equals(CEYLON_DOUBLE_ARRAY) || qualifiedName.equals(CEYLON_CHAR_ARRAY) || qualifiedName.equals(CEYLON_ARRAYS) ) pkgName = "java.lang"; else pkgName = classMirror.getPackage().getQualifiedName(); Module module = findModuleForPackage(pkgName); LazyPackage pkg = findOrCreatePackage(module, pkgName); // find/make its Unit Unit unit = getCompiledUnit(pkg, classMirror); // set all the containers for(Declaration d : decls){ d.setShared(classMirror.isPublic()); // add it to its Unit d.setUnit(unit); unit.addDeclaration(d); setContainer(classMirror, d, pkg); } return decl; } private void setContainer(ClassMirror classMirror, Declaration d, LazyPackage pkg) { // add it to its package if it's not an inner class if(!classMirror.isInnerClass()){ pkg.addMember(d); d.setContainer(pkg); }else if(d instanceof ClassOrInterface || d instanceof TypeAlias){ // do overloads later, since their container is their abstract superclass's container and // we have to set that one first if(d instanceof Class == false || !((Class)d).isOverloaded()){ ClassOrInterface container = getContainer(classMirror); d.setContainer(container); // let's not trigger lazy-loading ((LazyContainer)container).addMember(d); // now we can do overloads if(d instanceof Class && ((Class)d).getOverloads() != null){ for(Declaration overload : ((Class)d).getOverloads()){ overload.setContainer(container); // let's not trigger lazy-loading ((LazyContainer)container).addMember(d); } } } } } private ClassOrInterface getContainer(ClassMirror classMirror) { AnnotationMirror containerAnnotation = classMirror.getAnnotation(CEYLON_CONTAINER_ANNOTATION); if(containerAnnotation != null){ String name = (String) containerAnnotation.getValue("name"); String javaClass = (String) containerAnnotation.getValue("javaClass"); String packageName = (String) containerAnnotation.getValue("packageName"); String javaClassName = assembleJavaClass(javaClass, packageName); Declaration containerDecl = convertToDeclaration(javaClassName, DeclarationType.TYPE); if(containerDecl == null) throw new ModelResolutionException("Failed to load outer type " + name + " for inner type " + classMirror.getQualifiedName().toString() + ", java class: " + javaClass); return (ClassOrInterface) containerDecl; }else{ return (ClassOrInterface) convertToDeclaration(classMirror.getEnclosingClass(), DeclarationType.TYPE); } } protected Declaration getOrCreateDeclaration(ClassMirror classMirror, DeclarationType declarationType, List<Declaration> decls, boolean[] alreadyExists) { alreadyExists[0] = false; Declaration decl = null; String className = classMirror.getQualifiedName(); ClassType type; String prefix; if(classMirror.isCeylonToplevelAttribute()){ type = ClassType.ATTRIBUTE; prefix = "V"; }else if(classMirror.isCeylonToplevelMethod()){ type = ClassType.METHOD; prefix = "V"; }else if(classMirror.isCeylonToplevelObject()){ type = ClassType.OBJECT; // depends on which one we want prefix = declarationType == DeclarationType.TYPE ? "C" : "V"; }else if(classMirror.isInterface()){ type = ClassType.INTERFACE; prefix = "C"; }else{ type = ClassType.CLASS; prefix = "C"; } String key = prefix + className; // see if we already have it if(declarationsByName.containsKey(key)){ alreadyExists[0] = true; return declarationsByName.get(key); } checkBinaryCompatibility(classMirror); // make it switch(type){ case ATTRIBUTE: decl = makeToplevelAttribute(classMirror); break; case METHOD: decl = makeToplevelMethod(classMirror); break; case OBJECT: // we first make a class Declaration objectClassDecl = makeLazyClass(classMirror, null, null, true); declarationsByName.put("C"+className, objectClassDecl); decls.add(objectClassDecl); // then we make a value for it Declaration objectDecl = makeToplevelAttribute(classMirror); declarationsByName.put("V"+className, objectDecl); decls.add(objectDecl); // which one did we want? decl = declarationType == DeclarationType.TYPE ? objectClassDecl : objectDecl; break; case CLASS: if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){ decl = makeClassAlias(classMirror); }else if(classMirror.getAnnotation(CEYLON_TYPE_ALIAS_ANNOTATION) != null){ decl = makeTypeAlias(classMirror); }else{ List<MethodMirror> constructors = getClassConstructors(classMirror); if (!constructors.isEmpty()) { if (constructors.size() > 1) { // If the class has multiple constructors we make a copy of the class // for each one (each with it's own single constructor) and make them // a subclass of the original Class supercls = makeLazyClass(classMirror, null, null, false); supercls.setAbstraction(true); List<Declaration> overloads = new ArrayList<Declaration>(constructors.size()); boolean isFromJDK = isFromJDK(classMirror); for (MethodMirror constructor : constructors) { // FIXME: tmp hack to skip constructors that have type params as we don't handle them yet if(!constructor.getTypeParameters().isEmpty()) continue; // We skip members marked with @Ignore if(constructor.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !constructor.isPublic()) continue; LazyClass subdecl = makeLazyClass(classMirror, supercls, constructor, false); subdecl.setOverloaded(true); overloads.add(subdecl); decls.add(subdecl); } supercls.setOverloads(overloads); decl = supercls; } else { MethodMirror constructor = constructors.get(0); decl = makeLazyClass(classMirror, null, constructor, false); } } else { decl = makeLazyClass(classMirror, null, null, false); } } break; case INTERFACE: if(classMirror.getAnnotation(CEYLON_ALIAS_ANNOTATION) != null){ decl = makeInterfaceAlias(classMirror); }else{ decl = makeLazyInterface(classMirror); } break; } // objects have special handling above if(type != ClassType.OBJECT){ declarationsByName.put(key, decl); decls.add(decl); } return decl; } private Declaration makeClassAlias(ClassMirror classMirror) { return new LazyClassAlias(classMirror, this); } private Declaration makeTypeAlias(ClassMirror classMirror) { return new LazyTypeAlias(classMirror, this); } private Declaration makeInterfaceAlias(ClassMirror classMirror) { return new LazyInterfaceAlias(classMirror, this); } private void checkBinaryCompatibility(ClassMirror classMirror) { // let's not report it twice if(binaryCompatibilityErrorRaised) return; AnnotationMirror annotation = classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION); if(annotation == null) return; // Java class, no check Integer major = (Integer) annotation.getValue("major"); if(major == null) major = 0; Integer minor = (Integer) annotation.getValue("minor"); if(minor == null) minor = 0; if(major != Versions.JVM_BINARY_MAJOR_VERSION || minor != Versions.JVM_BINARY_MINOR_VERSION){ logError("Ceylon class " + classMirror.getQualifiedName() + " was compiled by an incompatible version of the Ceylon compiler" +"\nThe class was compiled using "+major+"."+minor+"." +"\nThis compiler supports "+Versions.JVM_BINARY_MAJOR_VERSION+"."+Versions.JVM_BINARY_MINOR_VERSION+"." +"\nPlease try to recompile your module using a compatible compiler." +"\nBinary compatibility will only be supported after Ceylon 1.0."); binaryCompatibilityErrorRaised = true; } } private List<MethodMirror> getClassConstructors(ClassMirror classMirror) { LinkedList<MethodMirror> constructors = new LinkedList<MethodMirror>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isConstructor()) { constructors.add(methodMirror); } } return constructors; } protected Unit getCompiledUnit(LazyPackage pkg, ClassMirror classMirror) { Unit unit = unitsByPackage.get(pkg); if(unit == null){ unit = new LazyUnit(); unit.setPackage(pkg); unitsByPackage.put(pkg, unit); } return unit; } protected LazyValue makeToplevelAttribute(ClassMirror classMirror) { LazyValue value = new LazyValue(classMirror, this); return value; } protected LazyMethod makeToplevelMethod(ClassMirror classMirror) { LazyMethod method = new LazyMethod(classMirror, this); return method; } protected LazyClass makeLazyClass(ClassMirror classMirror, Class superClass, MethodMirror constructor, boolean forTopLevelObject) { LazyClass klass = new LazyClass(classMirror, this, superClass, constructor, forTopLevelObject); klass.setAnonymous(classMirror.getAnnotation(CEYLON_OBJECT_ANNOTATION) != null); if(klass.isCeylon()) klass.setAbstract(isAnnotated(classMirror, "abstract")); else klass.setAbstract(classMirror.isAbstract()); klass.setFormal(isAnnotated(classMirror, "formal")); klass.setDefault(isAnnotated(classMirror, "default")); klass.setActual(isAnnotated(classMirror, "actual")); klass.setFinal(classMirror.isFinal()); return klass; } protected LazyInterface makeLazyInterface(ClassMirror classMirror) { LazyInterface iface = new LazyInterface(classMirror, this); return iface; } public synchronized Declaration convertToDeclaration(String typeName, DeclarationType declarationType) { // FIXME: this needs to move to the type parser and report warnings //This should be done where the TypeInfo annotation is parsed //to avoid retarded errors because of a space after a comma typeName = typeName.trim(); timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ if ("ceylon.language.Nothing".equals(typeName)) { return new NothingType(typeFactory); } else if ("java.lang.Throwable".equals(typeName)) { return convertToDeclaration("ceylon.language.Exception", declarationType); } ClassMirror classMirror = lookupClassMirror(typeName); if (classMirror == null) { String simpleName = typeName.substring(typeName.lastIndexOf(".")+1); Declaration languageModuleDeclaration = typeFactory.getLanguageModuleDeclaration(simpleName); if (languageModuleDeclaration != null) { return languageModuleDeclaration; } throw new ModelResolutionException("Failed to resolve "+typeName); } // we only allow source loading when it's java code we're compiling in the same go // (well, technically before the ceylon code) if(classMirror.isLoadedFromSource() && !classMirror.isJavaSource()) return null; return convertToDeclaration(classMirror, declarationType); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } protected TypeParameter safeLookupTypeParameter(Scope scope, String name) { TypeParameter param = lookupTypeParameter(scope, name); if(param == null) throw new ModelResolutionException("Type param "+name+" not found in "+scope); return param; } private TypeParameter lookupTypeParameter(Scope scope, String name) { if(scope instanceof Method){ Method m = (Method) scope; for(TypeParameter param : m.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!m.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else if(scope instanceof ClassOrInterface || scope instanceof TypeAlias){ TypeDeclaration decl = (TypeDeclaration) scope; for(TypeParameter param : decl.getTypeParameters()){ if(param.getName().equals(name)) return param; } if (!decl.isToplevel()) { // look it up in its container return lookupTypeParameter(scope.getContainer(), name); } else { // not found return null; } }else throw new ModelResolutionException("Type param "+name+" lookup not supported for scope "+scope); } // // Packages public synchronized Package findPackage(String pkgName) { pkgName = Util.quoteJavaKeywords(pkgName); return packagesByName.get(pkgName); } public synchronized LazyPackage findExistingPackage(Module module, String pkgName){ String quotedPkgName = Util.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // special case for the jdk module String moduleName = module.getNameAsString(); if(AbstractModelLoader.isJDKModule(moduleName)){ if(JDKUtils.isJDKPackage(moduleName, pkgName) || JDKUtils.isOracleJDKPackage(moduleName, pkgName)){ return findOrCreatePackage(module, pkgName); } return null; } // only create it if it exists if(loadPackage(pkgName, false)){ return findOrCreatePackage(module, pkgName); } return null; } private LazyPackage findCachedPackage(Module module, String quotedPkgName) { LazyPackage pkg = packagesByName.get(quotedPkgName); if(pkg != null){ // only return it if it matches the module we're looking for, because if it doesn't we have an issue already logged // for a direct dependency on same module different versions logged, so no need to confuse this further if(module != null && pkg.getModule() != null && !module.equals(pkg.getModule())) return null; return pkg; } return null; } public synchronized LazyPackage findOrCreatePackage(Module module, final String pkgName) { String quotedPkgName = Util.quoteJavaKeywords(pkgName); LazyPackage pkg = findCachedPackage(module, quotedPkgName); if(pkg != null) return pkg; // try to find it from the module, perhaps it already got created and we didn't catch it if(module instanceof LazyModule){ pkg = (LazyPackage) ((LazyModule) module).findPackageNoLazyLoading(pkgName); }else if(module != null){ pkg = (LazyPackage) module.getDirectPackage(pkgName); } boolean isNew = pkg == null; if(pkg == null){ pkg = new LazyPackage(this); // FIXME: some refactoring needed pkg.setName(pkgName == null ? Collections.<String>emptyList() : Arrays.asList(pkgName.split("\\."))); } packagesByName.put(quotedPkgName, pkg); // only bind it if we already have a module if(isNew && module != null){ pkg.setModule(module); if(module instanceof LazyModule) ((LazyModule) module).addPackage(pkg); else module.getPackages().add(pkg); } // only load package descriptors for new packages after a certain phase if(packageDescriptorsNeedLoading) loadPackageDescriptor(pkg); return pkg; } public synchronized void loadPackageDescriptors() { for(Package pkg : packagesByName.values()){ loadPackageDescriptor(pkg); } packageDescriptorsNeedLoading = true; } private void loadPackageDescriptor(Package pkg) { // let's not load package descriptors for Java modules if(pkg.getModule() != null && ((LazyModule)pkg.getModule()).isJava()){ pkg.setShared(true); return; } String quotedQualifiedName = Util.quoteJavaKeywords(pkg.getQualifiedNameString()); // FIXME: not sure the toplevel package can have a package declaration String className = quotedQualifiedName.isEmpty() ? "package" : quotedQualifiedName + ".package"; logVerbose("[Trying to look up package from "+className+"]"); ClassMirror packageClass = loadClass(quotedQualifiedName, className); if(packageClass == null){ logVerbose("[Failed to complete "+className+"]"); // missing: leave it private return; } // did we compile it from source or class? if(packageClass.isLoadedFromSource()){ // must have come from source, in which case we walked it and // loaded its values already logVerbose("[We are compiling the package "+className+"]"); return; } loadCompiledPackage(packageClass, pkg); } private void loadCompiledPackage(ClassMirror packageClass, Package pkg) { String name = getAnnotationStringValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "name"); Boolean shared = getAnnotationBooleanValue(packageClass, CEYLON_PACKAGE_ANNOTATION, "shared"); // FIXME: validate the name? if(name == null || name.isEmpty()){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no name, ignoring it"); return; } if(shared == null){ logWarning("Package class "+pkg.getQualifiedNameString()+" contains no shared, ignoring it"); return; } pkg.setShared(shared); } protected Module lookupModuleInternal(String packageName) { for(Module module : modules.getListOfModules()){ // don't try the default module because it will always say yes if(module.isDefault()) continue; if(module instanceof LazyModule){ if(((LazyModule)module).containsPackage(packageName)) return module; }else if(isSubPackage(module.getNameAsString(), packageName)) return module; } return modules.getDefaultModule(); } private boolean isSubPackage(String moduleName, String pkgName) { return pkgName.equals(moduleName) || pkgName.startsWith(moduleName+"."); } // // Modules /** * Finds or creates a new module. This is mostly useful to force creation of modules such as jdk * or ceylon.language modules. */ public synchronized Module findOrCreateModule(String moduleName) { boolean isJava = false; boolean defaultModule = false; // make sure it isn't loaded Module module = getLoadedModule(moduleName); if(module != null) return module; if(JDKUtils.isJDKModule(moduleName) || JDKUtils.isOracleJDKModule(moduleName)){ isJava = true; } java.util.List<String> moduleNameList = Arrays.asList(moduleName.split("\\.")); module = moduleManager.getOrCreateModule(moduleNameList, null); // make sure that when we load the ceylon language module we set it to where // the typechecker will look for it if(moduleName.equals(CEYLON_LANGUAGE) && modules.getLanguageModule() == null){ modules.setLanguageModule(module); } // TRICKY We do this only when isJava is true to prevent resetting // the value to false by mistake. LazyModule get's created with // this attribute to false by default, so it should work if (isJava && module instanceof LazyModule) { ((LazyModule)module).setJava(true); } // FIXME: this can't be that easy. module.setAvailable(true); module.setDefault(defaultModule); return module; } private Module findModuleForPackage(String pkgName) { Module module = lookupModuleInternal(pkgName); if (module != null) { return module; } throw new ModelResolutionException("Failed to find module for package "+pkgName); } public synchronized Module loadCompiledModule(String pkgName) { if(pkgName.isEmpty()) return null; String moduleClassName = pkgName + ".module"; logVerbose("[Trying to look up module from "+moduleClassName+"]"); ClassMirror moduleClass = loadClass(pkgName, moduleClassName); if(moduleClass != null){ // load its module annotation Module module = loadCompiledModule(moduleClass, moduleClassName); if(module != null) return module; } // keep looking up int lastDot = pkgName.lastIndexOf("."); if(lastDot == -1) return null; String parentPackageName = pkgName.substring(0, lastDot); return loadCompiledModule(parentPackageName); } private Module loadCompiledModule(ClassMirror moduleClass, String moduleClassName) { String name = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "name"); String version = getAnnotationStringValue(moduleClass, CEYLON_MODULE_ANNOTATION, "version"); // FIXME: validate the name? if(name == null || name.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no name, ignoring it"); return null; } if(version == null || version.isEmpty()){ logWarning("Module class "+moduleClassName+" contains no version, ignoring it"); return null; } Module module = moduleManager.getOrCreateModule(Arrays.asList(name.split("\\.")), version); int major = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "major", 0); int minor = getAnnotationIntegerValue(moduleClass, CEYLON_CEYLON_ANNOTATION, "minor", 0); module.setMajor(major); module.setMinor(minor); List<AnnotationMirror> imports = getAnnotationArrayValue(moduleClass, CEYLON_MODULE_ANNOTATION, "dependencies"); if(imports != null){ for (AnnotationMirror importAttribute : imports) { String dependencyName = (String) importAttribute.getValue("name"); if (dependencyName != null) { String dependencyVersion = (String) importAttribute.getValue("version"); Module dependency = moduleManager.getOrCreateModule(ModuleManager.splitModuleName(dependencyName), dependencyVersion); Boolean optionalVal = (Boolean) importAttribute.getValue("optional"); Boolean exportVal = (Boolean) importAttribute.getValue("export"); ModuleImport moduleImport = moduleManager.findImport(module, dependency); if (moduleImport == null) { boolean optional = optionalVal != null && optionalVal; boolean export = exportVal != null && exportVal; moduleImport = new ModuleImport(dependency, optional, export); module.getImports().add(moduleImport); } } } } module.setAvailable(true); modules.getListOfModules().add(module); Module languageModule = modules.getLanguageModule(); module.setLanguageModule(languageModule); if(module != languageModule){ ModuleImport moduleImport = moduleManager.findImport(module, languageModule); if (moduleImport == null) { moduleImport = new ModuleImport(languageModule, false, false); module.getImports().add(moduleImport); } } return module; } // // Utils for loading type info from the model @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type, String field) { return (List<T>) getAnnotationValue(mirror, type, field); } @SuppressWarnings("unchecked") private <T> List<T> getAnnotationArrayValue(AnnotatedMirror mirror, String type) { return (List<T>) getAnnotationValue(mirror, type); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type) { return getAnnotationStringValue(mirror, type, "value"); } private String getAnnotationStringValue(AnnotatedMirror mirror, String type, String field) { return (String) getAnnotationValue(mirror, type, field); } private Boolean getAnnotationBooleanValue(AnnotatedMirror mirror, String type, String field) { return (Boolean) getAnnotationValue(mirror, type, field); } private int getAnnotationIntegerValue(AnnotatedMirror mirror, String type, String field, int defaultValue) { Integer val = (Integer) getAnnotationValue(mirror, type, field); return val != null ? val : defaultValue; } private Object getAnnotationValue(AnnotatedMirror mirror, String type) { return getAnnotationValue(mirror, type, "value"); } private Object getAnnotationValue(AnnotatedMirror mirror, String type, String fieldName) { AnnotationMirror annotation = mirror.getAnnotation(type); if(annotation != null){ return annotation.getValue(fieldName); } return null; } // // ModelCompleter @Override public synchronized void complete(LazyInterface iface) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyInterface iface) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(iface, iface.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void complete(LazyClass klass) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); complete(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyClass klass) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeTypeParameters(klass, klass.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyClassAlias lazyClassAlias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyClassAlias, lazyClassAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyInterfaceAlias lazyInterfaceAlias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyInterfaceAlias, lazyInterfaceAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void completeTypeParameters(LazyTypeAlias lazyTypeAlias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAliasTypeParameters(lazyTypeAlias, lazyTypeAlias.classMirror); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void complete(LazyInterfaceAlias alias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } @Override public synchronized void complete(LazyClassAlias alias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_ALIAS_ANNOTATION); // must be a class Class declaration = (Class) alias.getExtendedType().getDeclaration(); // copy the parameters from the extended type alias.setParameterList(copyParameterList(alias, declaration)); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } private ParameterList copyParameterList(LazyClassAlias alias, Class declaration) { ParameterList newList = new ParameterList(); // FIXME: multiple param lists? newList.setNamedParametersSupported(declaration.getParameterList().isNamedParametersSupported()); for(Parameter p : declaration.getParameterList().getParameters()){ // FIXME: functionalparams? Parameter newParam = new ValueParameter(); newParam.setName(p.getName()); newParam.setContainer(alias); DeclarationVisitor.setVisibleScope(newParam); newParam.setDeclaration(alias); newParam.setSequenced(p.isSequenced()); newParam.setUnboxed(p.getUnboxed()); newParam.setUncheckedNullType(p.hasUncheckedNullType()); newParam.setUnit(p.getUnit()); newParam.setType(p.getProducedTypedReference(alias.getExtendedType(), Collections.<ProducedType>emptyList()).getType()); alias.addMember(newParam); newList.getParameters().add(newParam); } return newList; } @Override public synchronized void complete(LazyTypeAlias alias) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); completeLazyAlias(alias, alias.classMirror, CEYLON_TYPE_ALIAS_ANNOTATION); timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } private void completeLazyAliasTypeParameters(TypeDeclaration alias, ClassMirror mirror) { // type parameters setTypeParameters(alias, mirror); } private void completeLazyAlias(TypeDeclaration alias, ClassMirror mirror, String aliasAnnotationName) { // now resolve the extended type AnnotationMirror aliasAnnotation = mirror.getAnnotation(aliasAnnotationName); String extendedTypeString = (String) aliasAnnotation.getValue(); ProducedType extendedType = decodeType(extendedTypeString, alias); alias.setExtendedType(extendedType); } private void completeTypeParameters(ClassOrInterface klass, ClassMirror classMirror) { setTypeParameters(klass, classMirror); } private void complete(ClassOrInterface klass, ClassMirror classMirror) { Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>(); boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } // Add the methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = methodMirrors.size() > 1; List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null; for (MethodMirror methodMirror : methodMirrors) { String methodName = methodMirror.getName(); if(methodMirror.isConstructor()) { if (methodMirror == constructor) { if(!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType()) setParameters((Class)klass, methodMirror, isCeylon, klass); } } else if(isGetter(methodMirror)) { // simple attribute addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon); } else if(isSetter(methodMirror)) { // We skip setters for now and handle them later variables.put(methodMirror, methodMirrors); } else if(isHashAttribute(methodMirror)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method addValue(klass, methodMirror, "hash", isCeylon); } else if(isStringAttribute(methodMirror)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method addValue(klass, methodMirror, "string", isCeylon); } else { // normal method Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded); if (isOverloaded) { overloads.add(m); } } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(new UnknownType(typeFactory).getType()); } } for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" if(klass.getDirectMember(name, null, false) != null) continue; addValue(klass, fieldMirror, isCeylon); } // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (Decl.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p instanceof ValueParameter) { ((ValueParameter)p).setHidden(true); } } } } // Now mark all Values for which Setters exist as variable for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){ MethodMirror setter = setterEntry.getKey(); String name = getJavaAttributeName(setter.getName()); Declaration decl = klass.getMember(name, null, false); boolean foundGetter = false; - if (decl != null && Decl.isValue(decl)) { + // skip Java fields, which we only get if there is no getter method, in that case just add the setter method + if (decl != null && Decl.isValue(decl) && decl instanceof FieldValue == false) { Value value = (Value)decl; VariableMirror setterParam = setter.getParameters().get(0); try{ ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, VarianceLocation.INVARIANT); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ foundGetter = true; value.setVariable(true); if(decl instanceof JavaBeanValue) ((JavaBeanValue)decl).setSetterName(setter.getName()); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); }catch(TypeParserException x){ logError("Invalid type signature for setter of "+klass.getQualifiedNameString()+"."+setter.getName()+": "+x.getMessage()); throw x; } } if(!foundGetter){ // it was not a setter, it was a method, let's add it as such addMethod(klass, setter, isCeylon, false); } } // In some cases, where all constructors are ignored, we can end up with no constructor, so // pretend we have one which takes no parameters (eg. ceylon.language.String). if(klass instanceof Class && !((Class) klass).isAbstraction() && !klass.isAnonymous() && ((Class) klass).getParameterList() == null){ ((Class) klass).setParameterList(new ParameterList()); } klass.setStaticallyImportable(!isCeylon && classMirror.isStatic()); setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); fillRefinedDeclarations(klass); setAnnotations(klass, classMirror); } private boolean isFromJDK(ClassMirror classMirror) { String pkgName = classMirror.getPackage().getQualifiedName(); return JDKUtils.isJDKAnyPackage(pkgName) || JDKUtils.isOracleJDKAnyPackage(pkgName); } private void setAnnotations(Declaration decl, AnnotatedMirror classMirror) { List<AnnotationMirror> annotations = getAnnotationArrayValue(classMirror, CEYLON_ANNOTATIONS_ANNOTATION); if(annotations == null) return; for(AnnotationMirror annotation : annotations){ decl.getAnnotations().add(readModelAnnotation(annotation)); } } private Annotation readModelAnnotation(AnnotationMirror annotation) { Annotation modelAnnotation = new Annotation(); modelAnnotation.setName((String) annotation.getValue()); @SuppressWarnings("unchecked") List<String> arguments = (List<String>) annotation.getValue("arguments"); if(arguments != null){ modelAnnotation.getPositionalArguments().addAll(arguments); }else{ @SuppressWarnings("unchecked") List<AnnotationMirror> namedArguments = (List<AnnotationMirror>) annotation.getValue("namedArguments"); if(namedArguments != null){ for(AnnotationMirror namedArgument : namedArguments){ String argName = (String) namedArgument.getValue("name"); String argValue = (String) namedArgument.getValue("value"); modelAnnotation.getNamedArguments().put(argName, argValue); } } } return modelAnnotation; } private void addInnerClasses(ClassOrInterface klass, ClassMirror classMirror) { AnnotationMirror membersAnnotation = classMirror.getAnnotation(CEYLON_MEMBERS_ANNOTATION); if(membersAnnotation == null) addInnerClassesFromMirror(klass, classMirror); else addInnerClassesFromAnnotation(klass, membersAnnotation); } private void addInnerClassesFromAnnotation(ClassOrInterface klass, AnnotationMirror membersAnnotation) { List<AnnotationMirror> members = (List<AnnotationMirror>) membersAnnotation.getValue(); for(AnnotationMirror member : members){ String name = (String) member.getValue("name"); String javaClass = (String) member.getValue("javaClass"); String packageName = (String) member.getValue("packageName"); String javaClassName = assembleJavaClass(javaClass, packageName); Declaration innerDecl = convertToDeclaration(javaClassName, DeclarationType.TYPE); if(innerDecl == null) throw new ModelResolutionException("Failed to load inner type " + name + " for outer type " + klass.getQualifiedNameString() + ", java class: " + javaClass); } } /** * Allows subclasses to do something to the class name */ protected String assembleJavaClass(String javaClass, String packageName) { return javaClass; } private void addInnerClassesFromMirror(ClassOrInterface klass, ClassMirror classMirror) { boolean isJDK = isFromJDK(classMirror); for(ClassMirror innerClass : classMirror.getDirectInnerClasses()){ // We skip members marked with @Ignore if(innerClass.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; // We skip anonymous inner classes if(innerClass.isAnonymous()) continue; // We skip private classes, otherwise the JDK has a ton of unresolved things if(isJDK && !innerClass.isPublic()) continue; Declaration innerDecl = convertToDeclaration(innerClass, DeclarationType.TYPE); // no need to set its container as that's now handled by convertToDeclaration } } private Method addMethod(ClassOrInterface klass, MethodMirror methodMirror, boolean isCeylon, boolean isOverloaded) { JavaMethod method = new JavaMethod(); method.setContainer(klass); method.setRealName(methodMirror.getName()); method.setName(Util.strip(methodMirror.getName())); method.setUnit(klass.getUnit()); method.setOverloaded(isOverloaded); setMethodOrValueFlags(klass, methodMirror, method); // type params first setTypeParameters(method, methodMirror); // now its parameters if(isEqualsMethod(methodMirror)) setEqualsParameters(method, methodMirror); else setParameters(method, methodMirror, isCeylon, klass); // and its return type try{ ProducedType type = obtainType(methodMirror.getReturnType(), methodMirror, method, VarianceLocation.COVARIANT); method.setType(type); method.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); method.setDeclaredAnything(methodMirror.isDeclaredVoid()); type.setRaw(isRaw(methodMirror.getReturnType())); }catch(TypeParserException x){ logError("Invalid type signature for method return type of "+klass.getQualifiedNameString()+"."+methodMirror.getName()+": "+x.getMessage()); throw x; } markUnboxed(method, methodMirror.getReturnType()); markTypeErased(method, methodMirror, methodMirror.getReturnType()); setAnnotations(method, methodMirror); klass.getMembers().add(method); return method; } private void fillRefinedDeclarations(ClassOrInterface klass) { for(Declaration member : klass.getMembers()){ // do not trigger a type load (by calling isActual()) for Java inner classes since they // can never be actual if(member instanceof ClassOrInterface && !Decl.isCeylon((ClassOrInterface)member)) continue; if(member.isActual()){ member.setRefinedDeclaration(findRefinedDeclaration(klass, member.getName(), getSignature(member), false)); } } } private List<ProducedType> getSignature(Declaration decl) { List<ProducedType> result = null; if (decl instanceof Functional) { Functional func = (Functional)decl; if (func.getParameterLists().size() > 0) { List<Parameter> params = func.getParameterLists().get(0).getParameters(); result = new ArrayList<ProducedType>(params.size()); for (Parameter p : params) { result.add(p.getType()); } } } return result; } private Declaration findRefinedDeclaration(ClassOrInterface decl, String name, List<ProducedType> signature, boolean ellipsis) { Declaration refinedDeclaration = decl.getRefinedMember(name, signature, ellipsis); if(refinedDeclaration == null) throw new ModelResolutionException("Failed to find refined declaration for "+name); return refinedDeclaration; } private boolean isStartOfJavaBeanPropertyName(char c){ return Character.isUpperCase(c) || c == '_'; } private boolean isGetter(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesGet = name.length() > 3 && name.startsWith("get") && isStartOfJavaBeanPropertyName(name.charAt(3)); boolean matchesIs = name.length() > 2 && name.startsWith("is") && isStartOfJavaBeanPropertyName(name.charAt(2)); boolean hasNoParams = methodMirror.getParameters().size() == 0; boolean hasNonVoidReturn = (methodMirror.getReturnType().getKind() != TypeKind.VOID); return (matchesGet || matchesIs) && hasNoParams && hasNonVoidReturn; } private boolean isSetter(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesSet = name.length() > 3 && name.startsWith("set") && isStartOfJavaBeanPropertyName(name.charAt(3)); boolean hasOneParam = methodMirror.getParameters().size() == 1; boolean hasVoidReturn = (methodMirror.getReturnType().getKind() == TypeKind.VOID); return matchesSet && hasOneParam && hasVoidReturn; } private boolean isHashAttribute(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesName = "hashCode".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isStringAttribute(MethodMirror methodMirror) { String name = methodMirror.getName(); boolean matchesName = "toString".equals(name); boolean hasNoParams = methodMirror.getParameters().size() == 0; return matchesName && hasNoParams; } private boolean isEqualsMethod(MethodMirror methodMirror) { String name = methodMirror.getName(); if(!"equals".equals(name) || methodMirror.getParameters().size() != 1) return false; VariableMirror param = methodMirror.getParameters().get(0); return sameType(param.getType(), OBJECT_TYPE); } private void setEqualsParameters(Method decl, MethodMirror methodMirror) { ParameterList parameters = new ParameterList(); decl.addParameterList(parameters); ValueParameter parameter = new ValueParameter(); parameter.setUnit(decl.getUnit()); parameter.setContainer((Scope) decl); parameter.setName("that"); parameter.setType(getType(CEYLON_OBJECT_TYPE, decl, VarianceLocation.INVARIANT)); parameter.setDeclaration((Declaration) decl); parameters.getParameters().add(parameter); } private String getJavaAttributeName(String getterName) { if (getterName.startsWith("get") || getterName.startsWith("set")) { return getJavaBeanName(getterName.substring(3)); } else if (getterName.startsWith("is")) { // Starts with "is" return getJavaBeanName(getterName.substring(2)); } else { throw new RuntimeException("Illegal java getter/setter name"); } } private String getJavaBeanName(String name) { // See https://github.com/ceylon/ceylon-compiler/issues/340 // make it lowercase until the first non-uppercase char[] newName = name.toCharArray(); for(int i=0;i<newName.length;i++){ char c = newName[i]; if(Character.isLowerCase(c)){ // if we had more than one upper-case, we leave the last uppercase: getURLDecoder -> urlDecoder if(i > 1){ newName[i-1] = Character.toUpperCase(newName[i-1]); } break; } newName[i] = Character.toLowerCase(c); } return new String(newName); } private void addValue(ClassOrInterface klass, FieldMirror fieldMirror, boolean isCeylon) { // make sure it's a FieldValue so we can figure it out in the backend Value value = new FieldValue(fieldMirror.getName()); value.setContainer(klass); // use the name annotation if present (used by Java arrays) String nameAnnotation = getAnnotationStringValue(fieldMirror, CEYLON_NAME_ANNOTATION); value.setName(nameAnnotation != null ? nameAnnotation : fieldMirror.getName()); value.setUnit(klass.getUnit()); value.setShared(fieldMirror.isPublic() || fieldMirror.isProtected()); value.setProtectedVisibility(fieldMirror.isProtected()); value.setStaticallyImportable(fieldMirror.isStatic()); // field can't be abstract or interface, so not formal // can we override fields? good question. Not really, but from an external point of view? // FIXME: figure this out: (default) // FIXME: for the same reason, can it be an overriding field? (actual) value.setVariable(!fieldMirror.isFinal()); try{ ProducedType type = obtainType(fieldMirror.getType(), fieldMirror, klass, VarianceLocation.INVARIANT); value.setType(type); value.setUncheckedNullType((!isCeylon && !fieldMirror.getType().isPrimitive()) || isUncheckedNull(fieldMirror)); type.setRaw(isRaw(fieldMirror.getType())); }catch(TypeParserException x){ logError("Invalid type signature for field "+klass.getQualifiedNameString()+"."+value.getName()+": "+x.getMessage()); throw x; } markUnboxed(value, fieldMirror.getType()); markTypeErased(value, fieldMirror, fieldMirror.getType()); klass.getMembers().add(value); } private boolean isRaw(TypeMirror type) { // dirty hack to get rid of bug where calling type.isRaw() on a ceylon type we are going to compile would complete() it, which // would try to parse its file. For ceylon types we don't need the class file info we can query it // See https://github.com/ceylon/ceylon-compiler/issues/1085 switch(type.getKind()){ case ARRAY: // arrays are never raw case BOOLEAN: case BYTE: case CHAR: case DOUBLE: case ERROR: case FLOAT: case INT: case LONG: case NULL: case SHORT: case TYPEVAR: case VOID: case WILDCARD: return false; case DECLARED: ClassMirror klass = type.getDeclaredClass(); if(klass.isJavaSource()){ // I suppose this should work return type.isRaw(); } List<String> path = new LinkedList<String>(); String pkgName = klass.getPackage().getQualifiedName(); String qualifiedName = klass.getQualifiedName(); String relativeName = pkgName.isEmpty() ? qualifiedName : qualifiedName.substring(pkgName.length()+1); for(String name : relativeName.split("[\\$\\.]")){ if(!name.isEmpty()){ path.add(0, klass.getName()); } } if(path.size() > 1){ // find the proper class mirror for the container klass = loadClass(pkgName, path.get(0)); if(klass == null) return false; } if(!path.isEmpty() && klass.isLoadedFromSource()){ // we need to find its model Scope scope = packagesByName.get(pkgName); if(scope == null) return false; for(String name : path){ Declaration decl = scope.getDirectMember(name, null, false); if(decl == null) return false; // if we get a value, we want its type if(Decl.isValue(decl) && ((Value)decl).getTypeDeclaration().getName().equals(name)) decl = ((Value)decl).getTypeDeclaration(); if(decl instanceof TypeDeclaration == false) return false; scope = (TypeDeclaration)decl; } TypeDeclaration typeDecl = (TypeDeclaration) scope; return !typeDecl.getTypeParameters().isEmpty() && type.getTypeArguments().isEmpty(); } return type.isRaw(); default: return false; } } private void addValue(ClassOrInterface klass, MethodMirror methodMirror, String methodName, boolean isCeylon) { JavaBeanValue value = new JavaBeanValue(); value.setGetterName(methodMirror.getName()); value.setContainer(klass); value.setName(methodName); value.setUnit(klass.getUnit()); setMethodOrValueFlags(klass, methodMirror, value); try{ ProducedType type = obtainType(methodMirror.getReturnType(), methodMirror, klass, VarianceLocation.INVARIANT); value.setType(type); value.setUncheckedNullType((!isCeylon && !methodMirror.getReturnType().isPrimitive()) || isUncheckedNull(methodMirror)); type.setRaw(isRaw(methodMirror.getReturnType())); }catch(TypeParserException x){ logError("Invalid type signature for getter type of "+klass.getQualifiedNameString()+"."+methodName+": "+x.getMessage()); throw x; } markUnboxed(value, methodMirror.getReturnType()); markTypeErased(value, methodMirror, methodMirror.getReturnType()); setAnnotations(value, methodMirror); klass.getMembers().add(value); } private boolean isUncheckedNull(AnnotatedMirror methodMirror) { Boolean unchecked = getAnnotationBooleanValue(methodMirror, CEYLON_TYPE_INFO_ANNOTATION, "uncheckedNull"); return unchecked != null && unchecked.booleanValue(); } private void setMethodOrValueFlags(ClassOrInterface klass, MethodMirror methodMirror, MethodOrValue decl) { decl.setShared(methodMirror.isPublic() || methodMirror.isProtected()); decl.setProtectedVisibility(methodMirror.isProtected()); if(// for class members we rely on abstract bit (klass instanceof Class && methodMirror.isAbstract()) // Java interfaces are formal || (klass instanceof Interface && !((LazyInterface)klass).isCeylon()) // For Ceylon interfaces we rely on annotation || isAnnotated(methodMirror, "formal")) { decl.setFormal(true); } else { if (// for class members we rely on final/static bits (klass instanceof Class && !methodMirror.isFinal() && !methodMirror.isStatic()) // Java interfaces are never final || (klass instanceof Interface && !((LazyInterface)klass).isCeylon()) // For Ceylon interfaces we rely on annotation || isAnnotated(methodMirror, "default")){ decl.setDefault(true); } } decl.setStaticallyImportable(methodMirror.isStatic()); if(isOverridingMethod(methodMirror) // For Ceylon interfaces we rely on annotation || (klass instanceof LazyInterface && ((LazyInterface)klass).isCeylon() && isAnnotated(methodMirror, "actual"))){ decl.setActual(true); } } private boolean isAnnotated(AnnotatedMirror annotatedMirror, String name) { AnnotationMirror annotations = annotatedMirror.getAnnotation(CEYLON_ANNOTATIONS_ANNOTATION); if(annotations == null) return false; @SuppressWarnings("unchecked") List<AnnotationMirror> annotationsList = (List<AnnotationMirror>)annotations.getValue(); for(AnnotationMirror annotation : annotationsList){ if(name.equals(annotation.getValue())) return true; } return false; } private void setExtendedType(ClassOrInterface klass, ClassMirror classMirror) { // look at its super type TypeMirror superClass = classMirror.getSuperclass(); ProducedType extendedType; if(klass instanceof Interface){ // interfaces need to have their superclass set to Object if(superClass == null || superClass.getKind() == TypeKind.NONE) extendedType = getType(CEYLON_OBJECT_TYPE, klass, VarianceLocation.INVARIANT); else extendedType = getType(superClass, klass, VarianceLocation.INVARIANT); }else{ String className = classMirror.getQualifiedName(); String superClassName = superClass == null ? null : superClass.getQualifiedName(); if(className.equals("ceylon.language.Anything")){ // ceylon.language.Anything has no super type extendedType = null; }else if(className.equals("java.lang.Object")){ // we pretend its superclass is something else, but note that in theory we shouldn't // be seeing j.l.Object at all due to unerasure extendedType = getType(CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); }else{ // read it from annotation first String annotationSuperClassName = getAnnotationStringValue(classMirror, CEYLON_CLASS_ANNOTATION, "extendsType"); if(annotationSuperClassName != null && !annotationSuperClassName.isEmpty()){ try{ extendedType = decodeType(annotationSuperClassName, klass); }catch(TypeParserException x){ logError("Invalid type signature for super class of "+className+": "+x.getMessage()); throw x; } }else{ // read it from the Java super type // now deal with type erasure, avoid having Object as superclass if("java.lang.Object".equals(superClassName)){ extendedType = getType(CEYLON_BASIC_TYPE, klass, VarianceLocation.INVARIANT); }else{ extendedType = getType(superClass, klass, VarianceLocation.INVARIANT); } } } } if(extendedType != null) klass.setExtendedType(extendedType); } private void setParameters(Functional decl, MethodMirror methodMirror, boolean isCeylon, Scope container) { ParameterList parameters = new ParameterList(); parameters.setNamedParametersSupported(isCeylon); decl.addParameterList(parameters); int parameterCount = methodMirror.getParameters().size(); int parameterIndex = 0; for(VariableMirror paramMirror : methodMirror.getParameters()){ // ignore some parameters if(paramMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; boolean isLastParameter = parameterIndex == parameterCount - 1; boolean isVariadic = isLastParameter && methodMirror.isVariadic(); ValueParameter parameter = new ValueParameter(); parameter.setContainer((Scope) decl); DeclarationVisitor.setVisibleScope(parameter); parameter.setUnit(((Element)decl).getUnit()); if(decl instanceof Class){ ((Class)decl).getMembers().add(parameter); } String paramName = getAnnotationStringValue(paramMirror, CEYLON_NAME_ANNOTATION); // use whatever param name we find as default if(paramName == null) paramName = paramMirror.getName(); parameter.setName(paramName); TypeMirror typeMirror = paramMirror.getType(); try{ ProducedType type; if(isVariadic){ // possibly make it optional TypeMirror variadicType = typeMirror.getComponentType(); // we pretend it's toplevel because we want to get magic string conversion for variadic methods type = obtainType(variadicType, (Scope)decl, TypeLocation.TOPLEVEL, VarianceLocation.CONTRAVARIANT); if(!isCeylon && !variadicType.isPrimitive()){ // Java parameters are all optional unless primitives ProducedType optionalType = typeFactory.getOptionalType(type); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } // turn it into a Sequential<T> type = typeFactory.getSequentialType(type); }else{ type = obtainType(typeMirror, paramMirror, (Scope) decl, VarianceLocation.CONTRAVARIANT); // variadic params may technically be null in Java, but it Ceylon sequenced params may not // so it breaks the typechecker logic for handling them, and it will always be a case of bugs // in the java side so let's not allow this if(!isCeylon && !typeMirror.isPrimitive()){ // Java parameters are all optional unless primitives ProducedType optionalType = typeFactory.getOptionalType(type); optionalType.setUnderlyingType(type.getUnderlyingType()); type = optionalType; } } parameter.setType(type); }catch(TypeParserException x){ logError("Invalid type signature for parameter "+paramName+" of "+container.getQualifiedNameString()+"."+methodMirror.getName()+": "+x.getMessage()); throw x; } if(paramMirror.getAnnotation(CEYLON_SEQUENCED_ANNOTATION) != null || isVariadic) parameter.setSequenced(true); if(paramMirror.getAnnotation(CEYLON_DEFAULTED_ANNOTATION) != null) parameter.setDefaulted(true); // if it's variadic, consider the array element type (T[] == T...) for boxing rules markUnboxed(parameter, isVariadic ? paramMirror.getType().getComponentType() : paramMirror.getType()); parameter.setDeclaration((Declaration) decl); parameters.getParameters().add(parameter); parameterIndex++; } } private void markTypeErased(TypedDeclaration decl, AnnotatedMirror typedMirror, TypeMirror type) { if (getAnnotationBooleanValue(typedMirror, CEYLON_TYPE_INFO_ANNOTATION, "erased") == Boolean.TRUE) { decl.setTypeErased(true); } else { decl.setTypeErased(sameType(type, OBJECT_TYPE)); } } private void markUnboxed(TypedDeclaration decl, TypeMirror type) { boolean unboxed = false; if(type.isPrimitive() || type.getKind() == TypeKind.ARRAY || sameType(type, STRING_TYPE) || Util.isUnboxedVoid(decl)) { unboxed = true; } decl.setUnboxed(unboxed); } @Override public synchronized void complete(LazyValue value) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = null; for (MethodMirror m : value.classMirror.getDirectMethods()) { // Do not skip members marked with @Ignore, because the getter is supposed to be ignored if (m.getName().equals( Naming.getGetterName(value)) && m.isStatic() && m.getParameters().size() == 0) { meth = m; } if (m.getName().equals( Naming.getSetterName(value)) && m.isStatic() && m.getParameters().size() == 1) { value.setVariable(true); } } if(meth == null || meth.getReturnType() == null) throw new ModelResolutionException("Failed to find toplevel attribute "+value.getName()); try{ value.setType(obtainType(meth.getReturnType(), meth, null, VarianceLocation.INVARIANT)); }catch(TypeParserException x){ logError("Invalid type signature for toplevel attribute of "+value.getQualifiedNameString()+": "+x.getMessage()); throw x; } setAnnotations(value, meth); markUnboxed(value, meth.getReturnType()); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } @Override public synchronized void complete(LazyMethod method) { timer.startIgnore(TIMER_MODEL_LOADER_CATEGORY); try{ MethodMirror meth = null; String lookupName = method.getName(); for(MethodMirror m : method.classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(m.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(Util.strip(m.getName()).equals(lookupName)){ meth = m; break; } } if(meth == null || meth.getReturnType() == null) throw new ModelResolutionException("Failed to find toplevel method "+method.getName()); // type params first setTypeParameters(method, meth); // now its parameters setParameters(method, meth, true /* toplevel methods are always Ceylon */, method); try{ method.setType(obtainType(meth.getReturnType(), meth, method, VarianceLocation.COVARIANT)); method.setDeclaredAnything(meth.isDeclaredVoid()); }catch(TypeParserException x){ logError("Invalid type signature for toplevel method of "+method.getQualifiedNameString()+": "+x.getMessage()); throw x; } markUnboxed(method, meth.getReturnType()); markTypeErased(method, meth, meth.getReturnType()); setAnnotations(method, meth); }finally{ timer.stopIgnore(TIMER_MODEL_LOADER_CATEGORY); } } // // Satisfied Types private List<String> getSatisfiedTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_SATISFIED_TYPES_ANNOTATION); } private void setSatisfiedTypes(ClassOrInterface klass, ClassMirror classMirror) { List<String> satisfiedTypes = getSatisfiedTypesFromAnnotations(classMirror); if(satisfiedTypes != null){ try{ klass.getSatisfiedTypes().addAll(getTypesList(satisfiedTypes, klass)); }catch(TypeParserException x){ logError("Invalid type signature for satisfied types of "+klass.getQualifiedNameString()+": "+x.getMessage()); throw x; } }else{ for(TypeMirror iface : classMirror.getInterfaces()){ // ignore ReifiedType interfaces if(sameType(iface, CEYLON_REIFIED_TYPE_TYPE)) continue; try{ klass.getSatisfiedTypes().add(getType(iface, klass, VarianceLocation.INVARIANT)); }catch(ModelResolutionException x){ PackageMirror classPackage = classMirror.getPackage(); if(JDKUtils.isJDKAnyPackage(classPackage.getQualifiedName())){ if(iface.getKind() == TypeKind.DECLARED){ // check if it's a JDK thing ClassMirror ifaceClass = iface.getDeclaredClass(); PackageMirror ifacePackage = ifaceClass.getPackage(); if(JDKUtils.isOracleJDKAnyPackage(ifacePackage.getQualifiedName())){ // just log and ignore it logMissingOracleType(iface.getQualifiedName()); continue; } } } } } } } // // Case Types private List<String> getCaseTypesFromAnnotations(AnnotatedMirror symbol) { return getAnnotationArrayValue(symbol, CEYLON_CASE_TYPES_ANNOTATION); } private String getSelfTypeFromAnnotations(AnnotatedMirror symbol) { return getAnnotationStringValue(symbol, CEYLON_CASE_TYPES_ANNOTATION, "of"); } private void setCaseTypes(ClassOrInterface klass, ClassMirror classMirror) { String selfType = getSelfTypeFromAnnotations(classMirror); if(selfType != null && !selfType.isEmpty()){ try{ ProducedType type = decodeType(selfType, klass); if(!(type.getDeclaration() instanceof TypeParameter)){ logError("Invalid type signature for self type of "+klass.getQualifiedNameString()+": "+selfType+" is not a type parameter"); }else{ klass.setSelfType(type); List<ProducedType> caseTypes = new LinkedList<ProducedType>(); caseTypes.add(type); klass.setCaseTypes(caseTypes); } }catch(TypeParserException x){ logError("Invalid type signature for self type of "+klass.getQualifiedNameString()+": "+x.getMessage()); throw x; } } else { List<String> caseTypes = getCaseTypesFromAnnotations(classMirror); if(caseTypes != null && !caseTypes.isEmpty()){ try{ klass.setCaseTypes(getTypesList(caseTypes, klass)); }catch(TypeParserException x){ logError("Invalid type signature for case types of "+klass.getQualifiedNameString()+": "+x.getMessage()); throw x; } } } } private List<ProducedType> getTypesList(List<String> caseTypes, Scope scope) { List<ProducedType> producedTypes = new LinkedList<ProducedType>(); for(String type : caseTypes){ producedTypes.add(decodeType(type, scope)); } return producedTypes; } // // Type parameters loading @SuppressWarnings("unchecked") private List<AnnotationMirror> getTypeParametersFromAnnotations(AnnotatedMirror symbol) { return (List<AnnotationMirror>) getAnnotationValue(symbol, CEYLON_TYPE_PARAMETERS); } // from our annotation @SuppressWarnings("deprecation") private void setTypeParametersFromAnnotations(Scope scope, List<TypeParameter> params, AnnotatedMirror mirror, List<AnnotationMirror> typeParameters) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. String selfTypeName = getSelfTypeFromAnnotations(mirror); for(AnnotationMirror typeParam : typeParameters){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.getMembers().add(param); param.setName((String)typeParam.getValue("value")); param.setExtendedType(typeFactory.getAnythingDeclaration().getType()); String varianceName = (String) typeParam.getValue("variance"); if(varianceName != null){ if(varianceName.equals("IN")){ param.setContravariant(true); }else if(varianceName.equals("OUT")) param.setCovariant(true); } // If this is a self type param then link it to its type's declaration if (param.getName().equals(selfTypeName)) { param.setSelfTypedDeclaration((TypeDeclaration)scope); } params.add(param); } // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(AnnotationMirror typeParam : typeParameters){ TypeParameter param = paramsIterator.next(); @SuppressWarnings("unchecked") List<String> satisfiesAttribute = (List<String>)typeParam.getValue("satisfies"); setListOfTypes(param.getSatisfiedTypes(), satisfiesAttribute, scope, "Invalid type signature for satisfies of type parameter "+param.getName()+" of "+scope.getQualifiedNameString()+": "); @SuppressWarnings("unchecked") List<String> caseTypesAttribute = (List<String>)typeParam.getValue("caseTypes"); if(caseTypesAttribute != null && !caseTypesAttribute.isEmpty()) param.setCaseTypes(new LinkedList<ProducedType>()); setListOfTypes(param.getCaseTypes(), caseTypesAttribute, scope, "Invalid type signature for case types of type parameter "+param.getName()+" of "+scope.getQualifiedNameString()+": "); @SuppressWarnings("unchecked") String defaultValueAttribute = (String)typeParam.getValue("defaultValue"); if(defaultValueAttribute != null && !defaultValueAttribute.isEmpty()){ try{ ProducedType decodedType = decodeType(defaultValueAttribute, scope); param.setDefaultTypeArgument(decodedType); param.setDefaulted(true); }catch(TypeParserException x){ logError("Failed to decode defaultValue for @TypeParameter: "+defaultValueAttribute); throw x; } } } } private void setListOfTypes(List<ProducedType> destinationTypeList, List<String> serialisedTypes, Scope scope, String errorPrefix) { if(serialisedTypes != null){ for (String serialisedType : serialisedTypes) { try{ ProducedType decodedType = decodeType(serialisedType, scope); destinationTypeList.add(decodedType); }catch(TypeParserException x){ logError(errorPrefix+x.getMessage()); throw x; } } } } // from java type info @SuppressWarnings("deprecation") private void setTypeParameters(Scope scope, List<TypeParameter> params, List<TypeParameterMirror> typeParameters) { // We must first add every type param, before we resolve the bounds, which can // refer to type params. for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = new TypeParameter(); param.setUnit(((Element)scope).getUnit()); param.setContainer(scope); param.setDeclaration((Declaration) scope); // let's not trigger the lazy-loading if we're completing a LazyClass/LazyInterface if(scope instanceof LazyContainer) ((LazyContainer)scope).addMember(param); else // must be a method scope.getMembers().add(param); param.setName(typeParam.getName()); param.setExtendedType(typeFactory.getAnythingDeclaration().getType()); params.add(param); } // Now all type params have been set, we can resolve the references parts Iterator<TypeParameter> paramsIterator = params.iterator(); for(TypeParameterMirror typeParam : typeParameters){ TypeParameter param = paramsIterator.next(); List<TypeMirror> bounds = typeParam.getBounds(); for(TypeMirror bound : bounds){ ProducedType boundType; // we turn java's default upper bound java.lang.Object into ceylon.language.Object if(sameType(bound, OBJECT_TYPE)){ // avoid adding java's default upper bound if it's just there with no meaning if(bounds.size() == 1) break; boundType = getType(CEYLON_OBJECT_TYPE, scope, VarianceLocation.INVARIANT); }else boundType = getType(bound, scope, VarianceLocation.INVARIANT); param.getSatisfiedTypes().add(boundType); } } } // method private void setTypeParameters(Method method, MethodMirror methodMirror) { List<TypeParameter> params = new LinkedList<TypeParameter>(); method.setTypeParameters(params); List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(methodMirror); if(typeParameters != null) { setTypeParametersFromAnnotations(method, params, methodMirror, typeParameters); } else { setTypeParameters(method, params, methodMirror.getTypeParameters()); } } // class private void setTypeParameters(TypeDeclaration klass, ClassMirror classMirror) { List<TypeParameter> params = new LinkedList<TypeParameter>(); klass.setTypeParameters(params); List<AnnotationMirror> typeParameters = getTypeParametersFromAnnotations(classMirror); if(typeParameters != null) { setTypeParametersFromAnnotations(klass, params, classMirror, typeParameters); } else { setTypeParameters(klass, params, classMirror.getTypeParameters()); } } // // TypeParsing and ModelLoader private ProducedType decodeType(String value, Scope scope) { try{ return typeParser.decodeType(value, scope); }catch(TypeParserException x){ logError(x.getMessage()); }catch(ModelResolutionException x){ logError(x.getMessage()); } return new UnknownType(typeFactory).getType(); } /** Warning: only valid for toplevel types, not for type parameters */ private ProducedType obtainType(TypeMirror type, AnnotatedMirror symbol, Scope scope, VarianceLocation variance) { String typeName = getAnnotationStringValue(symbol, CEYLON_TYPE_INFO_ANNOTATION); if (typeName != null) { ProducedType ret = decodeType(typeName, scope); // even decoded types need to fit with the reality of the underlying type ret.setUnderlyingType(getUnderlyingType(type, TypeLocation.TOPLEVEL)); return ret; } else { return obtainType(type, scope, TypeLocation.TOPLEVEL, variance); } } private enum TypeLocation { TOPLEVEL, TYPE_PARAM; } private enum VarianceLocation { /** * Used in parameter */ CONTRAVARIANT, /** * Used in method return value */ COVARIANT, /** * For field */ INVARIANT; } private String getUnderlyingType(TypeMirror type, TypeLocation location){ // don't erase to c.l.String if in a type param location if ((sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) || sameType(type, PRIM_BYTE_TYPE) || sameType(type, PRIM_SHORT_TYPE) || sameType(type, PRIM_INT_TYPE) || sameType(type, PRIM_FLOAT_TYPE) || sameType(type, PRIM_CHAR_TYPE)) { return type.getQualifiedName(); } return null; } private ProducedType obtainType(TypeMirror type, Scope scope, TypeLocation location, VarianceLocation variance) { TypeMirror originalType = type; // ERASURE // don't erase to c.l.String if in a type param location if (sameType(type, STRING_TYPE) && location != TypeLocation.TYPE_PARAM) { type = CEYLON_STRING_TYPE; } else if (sameType(type, PRIM_BOOLEAN_TYPE)) { type = CEYLON_BOOLEAN_TYPE; } else if (sameType(type, PRIM_BYTE_TYPE)) { type = CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_SHORT_TYPE)) { type = CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_INT_TYPE)) { type = CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_LONG_TYPE)) { type = CEYLON_INTEGER_TYPE; } else if (sameType(type, PRIM_FLOAT_TYPE)) { type = CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_DOUBLE_TYPE)) { type = CEYLON_FLOAT_TYPE; } else if (sameType(type, PRIM_CHAR_TYPE)) { type = CEYLON_CHARACTER_TYPE; } else if (sameType(type, OBJECT_TYPE)) { type = CEYLON_OBJECT_TYPE; } else if (type.getKind() == TypeKind.ARRAY) { TypeMirror ct = type.getComponentType(); if (sameType(ct, PRIM_BOOLEAN_TYPE)) { type = JAVA_BOOLEAN_ARRAY_TYPE; } else if (sameType(ct, PRIM_BYTE_TYPE)) { type = JAVA_BYTE_ARRAY_TYPE; } else if (sameType(ct, PRIM_SHORT_TYPE)) { type = JAVA_SHORT_ARRAY_TYPE; } else if (sameType(ct, PRIM_INT_TYPE)) { type = JAVA_INT_ARRAY_TYPE; } else if (sameType(ct, PRIM_LONG_TYPE)) { type = JAVA_LONG_ARRAY_TYPE; } else if (sameType(ct, PRIM_FLOAT_TYPE)) { type = JAVA_FLOAT_ARRAY_TYPE; } else if (sameType(ct, PRIM_DOUBLE_TYPE)) { type = JAVA_DOUBLE_ARRAY_TYPE; } else if (sameType(ct, PRIM_CHAR_TYPE)) { type = JAVA_CHAR_ARRAY_TYPE; } else { // object array type = new SimpleReflType(JAVA_LANG_OBJECT_ARRAY, TypeKind.DECLARED, ct); } } ProducedType ret = getType(type, scope, variance); if (ret.getUnderlyingType() == null) { ret.setUnderlyingType(getUnderlyingType(originalType, location)); } return ret; } private boolean sameType(TypeMirror t1, TypeMirror t2) { // make sure we deal with arrays which can't have a qualified name if(t1.getKind() == TypeKind.ARRAY){ if(t2.getKind() != TypeKind.ARRAY) return false; return sameType(t1.getComponentType(), t2.getComponentType()); } if(t2.getKind() == TypeKind.ARRAY) return false; // the rest should be OK return t1.getQualifiedName().equals(t2.getQualifiedName()); } @Override public Declaration getDeclaration(String typeName, DeclarationType declarationType) { return convertToDeclaration(typeName, declarationType); } private ProducedType getType(TypeMirror type, Scope scope, VarianceLocation variance) { Declaration decl = convertToDeclaration(type, scope, DeclarationType.TYPE); TypeDeclaration declaration = (TypeDeclaration) decl; List<TypeMirror> javacTypeArguments = type.getTypeArguments(); if(!javacTypeArguments.isEmpty()){ List<ProducedType> typeArguments = new ArrayList<ProducedType>(javacTypeArguments.size()); for(TypeMirror typeArgument : javacTypeArguments){ // if a single type argument is a wildcard, we erase to Object if(typeArgument.getKind() == TypeKind.WILDCARD){ if(variance == VarianceLocation.CONTRAVARIANT || Decl.isCeylon(declaration)){ TypeMirror bound = typeArgument.getUpperBound(); if(bound == null) bound = typeArgument.getLowerBound(); // if it has no bound let's take Object if(bound == null){ // add the type arg and move to the next one typeArguments.add(typeFactory.getObjectDeclaration().getType()); continue; } typeArgument = bound; }else return typeFactory.getObjectDeclaration().getType(); } typeArguments.add((ProducedType) obtainType(typeArgument, scope, TypeLocation.TYPE_PARAM, variance)); } return declaration.getProducedType(getQualifyingType(declaration), typeArguments); } return declaration.getType(); } private ProducedType getQualifyingType(TypeDeclaration declaration) { // As taken from ProducedType.getType(): if (declaration.isMember()) { return((ClassOrInterface) declaration.getContainer()).getType(); } return null; } @Override public synchronized ProducedType getType(String pkgName, String name, Scope scope) { if(scope != null){ TypeParameter typeParameter = lookupTypeParameter(scope, name); if(typeParameter != null) return typeParameter.getType(); } if(!isBootstrap || !name.startsWith(CEYLON_LANGUAGE)) { if(scope != null && pkgName != null){ Package containingPackage = Decl.getPackageContainer(scope); Package pkg = containingPackage.getModule().getPackage(pkgName); String relativeName = null; String unquotedName = name.replace("$", ""); if(!pkgName.isEmpty()){ if(unquotedName.startsWith(pkgName+".")) relativeName = unquotedName.substring(pkgName.length()+1); // else we don't try it's not in this package }else relativeName = unquotedName; if(relativeName != null && pkg != null){ Declaration declaration = pkg.getDirectMember(relativeName, null, false); // if we get a value, we want its type if(Decl.isValue(declaration) && ((Value)declaration).getTypeDeclaration().getName().equals(relativeName)) declaration = ((Value)declaration).getTypeDeclaration(); if(declaration instanceof TypeDeclaration) return ((TypeDeclaration)declaration).getType(); // if we have something but it's not a type decl, it's a: // - value that's not an object (why would we get its type here?) // - method (doesn't have a type of the same name) if(declaration != null) return null; } } Declaration declaration = convertToDeclaration(name, DeclarationType.TYPE); if(declaration instanceof TypeDeclaration) return ((TypeDeclaration)declaration).getType(); // we're looking for type declarations, so anything else doesn't work for us return null; } // make sure we don't return anything for ceylon.language if(name.equals(CEYLON_LANGUAGE)) return null; // we're bootstrapping ceylon.language so we need to return the ProducedTypes straight from the model we're compiling Module languageModule = modules.getLanguageModule(); String simpleName = name.substring(name.lastIndexOf(".")+1); // Nothing is a special case with no real decl if(name.equals("ceylon.language.Nothing")) return typeFactory.getNothingDeclaration().getType(); for(Package pkg : languageModule.getPackages()){ Declaration member = pkg.getDirectMember(simpleName, null, false); // if we get a value, we want its type if(Decl.isValue(member) && ((Value)member).getTypeDeclaration().getName().equals(simpleName)){ member = ((Value)member).getTypeDeclaration(); } if(member instanceof TypeDeclaration) return ((TypeDeclaration)member).getType(); } throw new ModelResolutionException("Failed to look up given type in language module while bootstrapping: "+name); } public synchronized void removeDeclarations(List<Declaration> declarations) { List<String> keysToRemove = new ArrayList<String>(); for (String name : declarationsByName.keySet()) { String nameWithoutPrefix = name.substring(1); for (Declaration decl : declarations) { if (nameWithoutPrefix.equals(decl.getQualifiedNameString())) { keysToRemove.add(name); } } } for (String keyToRemove : keysToRemove) { declarationsByName.remove(keyToRemove); } for (Declaration decl : declarations) { if (decl instanceof LazyClass || decl instanceof LazyInterface) { classMirrorCache.remove(decl.getQualifiedNameString()); } } } public synchronized void printStats(){ int loaded = 0; class Stats { int loaded, total; } Map<Package, Stats> loadedByPackage = new HashMap<Package, Stats>(); for(Declaration decl : declarationsByName.values()){ if(decl instanceof LazyElement){ Package pkg = getPackage(decl); Stats stats = loadedByPackage.get(pkg); if(stats == null){ stats = new Stats(); loadedByPackage.put(pkg, stats); } stats.total++; if(((LazyElement)decl).isLoaded()){ loaded++; stats.loaded++; } } } logVerbose("[Model loader: "+loaded+"(loaded)/"+declarationsByName.size()+"(total) declarations]"); for(Entry<Package, Stats> packageEntry : loadedByPackage.entrySet()){ logVerbose("[ Package "+packageEntry.getKey().getNameAsString()+": " +packageEntry.getValue().loaded+"(loaded)/"+packageEntry.getValue().total+"(total) declarations]"); } } private static Package getPackage(Object decl) { if(decl == null) return null; if(decl instanceof Package) return (Package) decl; return getPackage(((Declaration)decl).getContainer()); } protected void logMissingOracleType(String type) { logVerbose("Hopefully harmless completion failure in model loader: "+type +". This is most likely when the JDK depends on Oracle private classes that we can't find." +" As a result some model information will be incomplete."); } public void setupSourceFileObjects(List<?> treeHolders) { } public static boolean isJDKModule(String name) { return JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name); } @Override public Module getLoadedModule(String moduleName) { for(Module mod : modules.getListOfModules()){ if(mod.getNameAsString().equals(moduleName)) return mod; } return null; } }
true
true
private void complete(ClassOrInterface klass, ClassMirror classMirror) { Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>(); boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } // Add the methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = methodMirrors.size() > 1; List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null; for (MethodMirror methodMirror : methodMirrors) { String methodName = methodMirror.getName(); if(methodMirror.isConstructor()) { if (methodMirror == constructor) { if(!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType()) setParameters((Class)klass, methodMirror, isCeylon, klass); } } else if(isGetter(methodMirror)) { // simple attribute addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon); } else if(isSetter(methodMirror)) { // We skip setters for now and handle them later variables.put(methodMirror, methodMirrors); } else if(isHashAttribute(methodMirror)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method addValue(klass, methodMirror, "hash", isCeylon); } else if(isStringAttribute(methodMirror)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method addValue(klass, methodMirror, "string", isCeylon); } else { // normal method Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded); if (isOverloaded) { overloads.add(m); } } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(new UnknownType(typeFactory).getType()); } } for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" if(klass.getDirectMember(name, null, false) != null) continue; addValue(klass, fieldMirror, isCeylon); } // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (Decl.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p instanceof ValueParameter) { ((ValueParameter)p).setHidden(true); } } } } // Now mark all Values for which Setters exist as variable for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){ MethodMirror setter = setterEntry.getKey(); String name = getJavaAttributeName(setter.getName()); Declaration decl = klass.getMember(name, null, false); boolean foundGetter = false; if (decl != null && Decl.isValue(decl)) { Value value = (Value)decl; VariableMirror setterParam = setter.getParameters().get(0); try{ ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, VarianceLocation.INVARIANT); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ foundGetter = true; value.setVariable(true); if(decl instanceof JavaBeanValue) ((JavaBeanValue)decl).setSetterName(setter.getName()); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); }catch(TypeParserException x){ logError("Invalid type signature for setter of "+klass.getQualifiedNameString()+"."+setter.getName()+": "+x.getMessage()); throw x; } } if(!foundGetter){ // it was not a setter, it was a method, let's add it as such addMethod(klass, setter, isCeylon, false); } } // In some cases, where all constructors are ignored, we can end up with no constructor, so // pretend we have one which takes no parameters (eg. ceylon.language.String). if(klass instanceof Class && !((Class) klass).isAbstraction() && !klass.isAnonymous() && ((Class) klass).getParameterList() == null){ ((Class) klass).setParameterList(new ParameterList()); } klass.setStaticallyImportable(!isCeylon && classMirror.isStatic()); setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); fillRefinedDeclarations(klass); setAnnotations(klass, classMirror); }
private void complete(ClassOrInterface klass, ClassMirror classMirror) { Map<MethodMirror, List<MethodMirror>> variables = new HashMap<MethodMirror, List<MethodMirror>>(); boolean isFromJDK = isFromJDK(classMirror); boolean isCeylon = (classMirror.getAnnotation(CEYLON_CEYLON_ANNOTATION) != null); // now that everything has containers, do the inner classes if(klass instanceof Class == false || !((Class)klass).isOverloaded()){ // this will not load inner classes of overloads, but that's fine since we want them in the // abstracted super class (the real one) addInnerClasses(klass, classMirror); } // Java classes with multiple constructors get turned into multiple Ceylon classes // Here we get the specific constructor that was assigned to us (if any) MethodMirror constructor = null; if (klass instanceof LazyClass) { constructor = ((LazyClass)klass).getConstructor(); } // Turn a list of possibly overloaded methods into a map // of lists that contain methods with the same name Map<String, List<MethodMirror>> methods = new LinkedHashMap<String, List<MethodMirror>>(); for(MethodMirror methodMirror : classMirror.getDirectMethods()){ // We skip members marked with @Ignore if(methodMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(methodMirror.isStaticInit()) continue; if(isCeylon && methodMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !methodMirror.isPublic()) continue; String methodName = methodMirror.getName(); List<MethodMirror> homonyms = methods.get(methodName); if (homonyms == null) { homonyms = new LinkedList<MethodMirror>(); methods.put(methodName, homonyms); } homonyms.add(methodMirror); } // Add the methods for(List<MethodMirror> methodMirrors : methods.values()){ boolean isOverloaded = methodMirrors.size() > 1; List<Declaration> overloads = (isOverloaded) ? new ArrayList<Declaration>(methodMirrors.size()) : null; for (MethodMirror methodMirror : methodMirrors) { String methodName = methodMirror.getName(); if(methodMirror.isConstructor()) { if (methodMirror == constructor) { if(!(klass instanceof LazyClass) || !((LazyClass)klass).isTopLevelObjectType()) setParameters((Class)klass, methodMirror, isCeylon, klass); } } else if(isGetter(methodMirror)) { // simple attribute addValue(klass, methodMirror, getJavaAttributeName(methodName), isCeylon); } else if(isSetter(methodMirror)) { // We skip setters for now and handle them later variables.put(methodMirror, methodMirrors); } else if(isHashAttribute(methodMirror)) { // ERASURE // Un-erasing 'hash' attribute from 'hashCode' method addValue(klass, methodMirror, "hash", isCeylon); } else if(isStringAttribute(methodMirror)) { // ERASURE // Un-erasing 'string' attribute from 'toString' method addValue(klass, methodMirror, "string", isCeylon); } else { // normal method Method m = addMethod(klass, methodMirror, isCeylon, isOverloaded); if (isOverloaded) { overloads.add(m); } } } if (overloads != null && !overloads.isEmpty()) { // We create an extra "abstraction" method for overloaded methods Method abstractionMethod = addMethod(klass, methodMirrors.get(0), false, false); abstractionMethod.setAbstraction(true); abstractionMethod.setOverloads(overloads); abstractionMethod.setType(new UnknownType(typeFactory).getType()); } } for(FieldMirror fieldMirror : classMirror.getDirectFields()){ // We skip members marked with @Ignore if(fieldMirror.getAnnotation(CEYLON_IGNORE_ANNOTATION) != null) continue; if(isCeylon && fieldMirror.isStatic()) continue; // FIXME: temporary, because some private classes from the jdk are // referenced in private methods but not available if(isFromJDK && !fieldMirror.isPublic()) continue; String name = fieldMirror.getName(); // skip the field if "we've already got one" if(klass.getDirectMember(name, null, false) != null) continue; addValue(klass, fieldMirror, isCeylon); } // Now marry-up attributes and parameters) if (klass instanceof Class) { for (Declaration m : klass.getMembers()) { if (Decl.isValue(m)) { Value v = (Value)m; Parameter p = ((Class)klass).getParameter(v.getName()); if (p instanceof ValueParameter) { ((ValueParameter)p).setHidden(true); } } } } // Now mark all Values for which Setters exist as variable for(Entry<MethodMirror, List<MethodMirror>> setterEntry : variables.entrySet()){ MethodMirror setter = setterEntry.getKey(); String name = getJavaAttributeName(setter.getName()); Declaration decl = klass.getMember(name, null, false); boolean foundGetter = false; // skip Java fields, which we only get if there is no getter method, in that case just add the setter method if (decl != null && Decl.isValue(decl) && decl instanceof FieldValue == false) { Value value = (Value)decl; VariableMirror setterParam = setter.getParameters().get(0); try{ ProducedType paramType = obtainType(setterParam.getType(), setterParam, klass, VarianceLocation.INVARIANT); // only add the setter if it has exactly the same type as the getter if(paramType.isExactly(value.getType())){ foundGetter = true; value.setVariable(true); if(decl instanceof JavaBeanValue) ((JavaBeanValue)decl).setSetterName(setter.getName()); }else logVerbose("Setter parameter type for "+name+" does not match corresponding getter type, adding setter as a method"); }catch(TypeParserException x){ logError("Invalid type signature for setter of "+klass.getQualifiedNameString()+"."+setter.getName()+": "+x.getMessage()); throw x; } } if(!foundGetter){ // it was not a setter, it was a method, let's add it as such addMethod(klass, setter, isCeylon, false); } } // In some cases, where all constructors are ignored, we can end up with no constructor, so // pretend we have one which takes no parameters (eg. ceylon.language.String). if(klass instanceof Class && !((Class) klass).isAbstraction() && !klass.isAnonymous() && ((Class) klass).getParameterList() == null){ ((Class) klass).setParameterList(new ParameterList()); } klass.setStaticallyImportable(!isCeylon && classMirror.isStatic()); setExtendedType(klass, classMirror); setSatisfiedTypes(klass, classMirror); setCaseTypes(klass, classMirror); fillRefinedDeclarations(klass); setAnnotations(klass, classMirror); }
diff --git a/opensajux/src/com/opensajux/view/NewsBean.java b/opensajux/src/com/opensajux/view/NewsBean.java index 30a4d13..cdfedb1 100644 --- a/opensajux/src/com/opensajux/view/NewsBean.java +++ b/opensajux/src/com/opensajux/view/NewsBean.java @@ -1,182 +1,182 @@ package com.opensajux.view; import java.io.Serializable; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.model.LazyDataModel; import org.primefaces.model.SortOrder; import com.google.appengine.api.datastore.Text; import com.opensajux.common.PaginationParameters; import com.opensajux.entity.News; import com.opensajux.jsf.context.ViewScoped; import com.opensajux.service.NewsService; @ViewScoped @Named public class NewsBean implements Serializable { private static final long serialVersionUID = -6774765469039891357L; @Inject private NewsService newsService; private LazyDataModel<News> newsModel; private News[] selectedNews; private News[] filteredNews; private String newsTitle = ""; private String newsContent = ""; private News selected = new News(); public LazyDataModel<News> getNews() { if (newsModel == null) { newsModel = new LazyDataModel<News>() { private static final long serialVersionUID = 71468727114834068L; @Override public int getRowCount() { return newsService.getCount().intValue(); } @Override public List<News> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) { PaginationParameters param = new PaginationParameters(); param.setFirst(first); param.setPageSize(pageSize); - param.setSortField(sortField); - param.setSortOrder(sortOrder == null ? "" : sortOrder == SortOrder.ASCENDING ? "asc" : "desc"); + param.setSortField(sortField == null ? "publishDate" : sortField); + param.setSortOrder(sortOrder == null ? "desc" : sortOrder == SortOrder.ASCENDING ? "asc" : "desc"); return newsService.getNews(param); } @Override public Object getRowKey(News news) { return news.getKey().getId() + ""; } @Override public News getRowData(String rowKey) { return newsService.getById(rowKey); } }; newsModel.setPageSize(5); } return newsModel; } /** * @return the selectedNews */ public News[] getSelectedNews() { return selectedNews; } /** * @param selectedNews * the selectedNews to set */ public void setSelectedNews(News[] selectedNews) { this.selectedNews = selectedNews; } /** * @return the filteredNews */ public News[] getFilteredNews() { return filteredNews; } /** * @param filteredNews * the filteredNews to set */ public void setFilteredNews(News[] filteredNews) { this.filteredNews = filteredNews; } /** * @return the newsTitle */ public String getNewsTitle() { return newsTitle; } /** * @param newsTitle * the newsTitle to set */ public void setNewsTitle(String newsTitle) { this.newsTitle = newsTitle; } /** * @return the newsContent */ public String getNewsContent() { return newsContent; } /** * @param newsContent * the newsContent to set */ public void setNewsContent(String newsContent) { this.newsContent = newsContent; } public void saveNews() { News news; if (selected != null) { news = selected; news.setUpdatedDate(new Date()); } else { news = new News(); news.setPublishDate(new Date()); news.setUpdatedDate(news.getPublishDate()); } news.setTitle(newsTitle); news.setContent(new Text(newsContent)); newsService.saveNews(news); } public void removeNews() { newsService.removeNews(selectedNews); clearFields(); } public void add() { clearFields(); } /** * */ private void clearFields() { newsTitle = ""; newsContent = ""; selected = null; selectedNews = null; } /** * @return the selected */ public News getSelected() { return selected; } /** * @param selected * the selected to set */ public void setSelected(News selected) { this.selected = selected; newsTitle = selected.getTitle(); newsContent = selected.getContent().getValue(); } }
true
true
public LazyDataModel<News> getNews() { if (newsModel == null) { newsModel = new LazyDataModel<News>() { private static final long serialVersionUID = 71468727114834068L; @Override public int getRowCount() { return newsService.getCount().intValue(); } @Override public List<News> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) { PaginationParameters param = new PaginationParameters(); param.setFirst(first); param.setPageSize(pageSize); param.setSortField(sortField); param.setSortOrder(sortOrder == null ? "" : sortOrder == SortOrder.ASCENDING ? "asc" : "desc"); return newsService.getNews(param); } @Override public Object getRowKey(News news) { return news.getKey().getId() + ""; } @Override public News getRowData(String rowKey) { return newsService.getById(rowKey); } }; newsModel.setPageSize(5); } return newsModel; }
public LazyDataModel<News> getNews() { if (newsModel == null) { newsModel = new LazyDataModel<News>() { private static final long serialVersionUID = 71468727114834068L; @Override public int getRowCount() { return newsService.getCount().intValue(); } @Override public List<News> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) { PaginationParameters param = new PaginationParameters(); param.setFirst(first); param.setPageSize(pageSize); param.setSortField(sortField == null ? "publishDate" : sortField); param.setSortOrder(sortOrder == null ? "desc" : sortOrder == SortOrder.ASCENDING ? "asc" : "desc"); return newsService.getNews(param); } @Override public Object getRowKey(News news) { return news.getKey().getId() + ""; } @Override public News getRowData(String rowKey) { return newsService.getById(rowKey); } }; newsModel.setPageSize(5); } return newsModel; }
diff --git a/src/com/vaadin/data/util/AbstractBeanContainer.java b/src/com/vaadin/data/util/AbstractBeanContainer.java index faeda2ad4..d0b8259ff 100644 --- a/src/com/vaadin/data/util/AbstractBeanContainer.java +++ b/src/com/vaadin/data/util/AbstractBeanContainer.java @@ -1,926 +1,926 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.data.util; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.vaadin.data.Container.Filterable; import com.vaadin.data.Container.Sortable; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.Property.ValueChangeNotifier; /** * An abstract base class for in-memory containers for JavaBeans. * * <p> * The properties of the container are determined automatically by introspecting * the used JavaBean class. Only beans of the same type can be added to the * container. * </p> * * <p> * Subclasses should implement adding items to the container, typically calling * the protected methods {@link #addItem(Object, Object)}, * {@link #addItemAfter(Object, Object, Object)} and * {@link #addItemAt(int, Object, Object)}, and if necessary, * {@link #internalAddAt(int, Object, Object)} and * {@link #internalIndexOf(Object)}. * </p> * * <p> * It is not possible to add additional properties to the container and nested * bean properties are not supported. * </p> * * @param <IDTYPE> * The type of the item identifier * @param <BEANTYPE> * The type of the Bean * * @since 6.5 */ public abstract class AbstractBeanContainer<IDTYPE, BEANTYPE> extends AbstractInMemoryContainer<IDTYPE, String, BeanItem<BEANTYPE>> implements Filterable, Sortable, ValueChangeListener { /** * Resolver that maps beans to their (item) identifiers, removing the need * to explicitly specify item identifiers when there is no need to customize * this. * * Note that beans can also be added with an explicit id even if a resolver * has been set. * * @param <IDTYPE> * @param <BEANTYPE> * * @since 6.5 */ public static interface BeanIdResolver<IDTYPE, BEANTYPE> extends Serializable { /** * Return the item identifier for a bean. * * @param bean * @return */ public IDTYPE getIdForBean(BEANTYPE bean); } /** * A item identifier resolver that returns the value of a bean property. * * The bean must have a getter for the property, and the getter must return * an object of type IDTYPE. */ protected class PropertyBasedBeanIdResolver implements BeanIdResolver<IDTYPE, BEANTYPE> { private final Object propertyId; private transient Method getMethod; public PropertyBasedBeanIdResolver(Object propertyId) { if (propertyId == null) { throw new IllegalArgumentException( "Property identifier must not be null"); } this.propertyId = propertyId; } private Method getGetter() throws IllegalStateException { if (getMethod == null) { if (!model.containsKey(propertyId)) { throw new IllegalStateException("Property " + propertyId + " not found"); } getMethod = model.get(propertyId).getReadMethod(); } return getMethod; } @SuppressWarnings("unchecked") public IDTYPE getIdForBean(BEANTYPE bean) throws IllegalArgumentException { try { return (IDTYPE) getGetter().invoke(bean); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e); } } } /** * The resolver that finds the item ID for a bean, or null not to use * automatic resolving. * * Methods that add a bean without specifying an ID must not be called if no * resolver has been set. */ private BeanIdResolver<IDTYPE, BEANTYPE> beanIdResolver = null; /** * The item sorter which is used for sorting the container. */ private ItemSorter itemSorter = new DefaultItemSorter(); /** * Filters currently applied to the container. */ private Set<Filter> filters = new HashSet<Filter>(); /** * Maps all item ids in the container (including filtered) to their * corresponding BeanItem. */ private final Map<IDTYPE, BeanItem<BEANTYPE>> itemIdToItem = new HashMap<IDTYPE, BeanItem<BEANTYPE>>(); /** * The type of the beans in the container. */ private final Class<? super BEANTYPE> type; /** * A description of the properties found in beans of type {@link #type}. * Determines the property ids that are present in the container. */ private transient LinkedHashMap<String, PropertyDescriptor> model; /** * Constructs a {@code AbstractBeanContainer} for beans of the given type. * * @param type * the type of the beans that will be added to the container. * @throws IllegalArgumentException * If {@code type} is null */ protected AbstractBeanContainer(Class<? super BEANTYPE> type) { super(new ListSet<IDTYPE>()); setFilteredItemIds(new ListSet<IDTYPE>()); if (type == null) { throw new IllegalArgumentException( "The bean type passed to AbstractBeanContainer must not be null"); } this.type = type; model = BeanItem.getPropertyDescriptors(type); } /** * A special deserialization method that resolves {@link #model} is needed * as PropertyDescriptor is not {@link Serializable}. */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); model = BeanItem.getPropertyDescriptors(type); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getType(java.lang.Object) */ public Class<?> getType(Object propertyId) { return model.get(propertyId).getPropertyType(); } /** * Create a BeanItem for a bean using pre-parsed bean metadata (based on * {@link #getBeanType()}). * * @param bean * @return */ protected BeanItem<BEANTYPE> createBeanItem(BEANTYPE bean) { return new BeanItem<BEANTYPE>(bean, model); } /** * Returns the type of beans this Container can contain. * * This comes from the bean type constructor parameter, and bean metadata * (including container properties) is based on this. * * @return */ public Class<? super BEANTYPE> getBeanType() { return type; } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getContainerPropertyIds() */ public Collection<String> getContainerPropertyIds() { return model.keySet(); } /** * Unsupported operation. Properties are determined by the introspecting the * bean class. */ public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Unsupported operation. Properties are determined by the introspecting the * bean class. */ public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeAllItems() */ public boolean removeAllItems() { internalRemoveAllItems(); // detach listeners from all Items for (Item item : itemIdToItem.values()) { removeAllValueChangeListeners(item); } itemIdToItem.clear(); fireItemSetChange(); return true; } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getItem(java.lang.Object) */ @Override public BeanItem<BEANTYPE> getItem(Object itemId) { return itemIdToItem.get(itemId); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getItemIds() */ @Override @SuppressWarnings("unchecked") public Collection<IDTYPE> getItemIds() { return (Collection<IDTYPE>) super.getItemIds(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#getContainerProperty(java.lang.Object, * java.lang.Object) */ public Property getContainerProperty(Object itemId, Object propertyId) { Item item = getItem(itemId); if (item == null) { return null; } return item.getItemProperty(propertyId); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeItem(java.lang.Object) */ public boolean removeItem(Object itemId) { Item item = getItem(itemId); if (internalRemoveItem(itemId)) { // detach listeners from Item removeAllValueChangeListeners(item); // remove item itemIdToItem.remove(itemId); fireItemSetChange(); return true; } else { return false; } } /** * Re-filter the container when one of the monitored properties changes. */ public void valueChange(ValueChangeEvent event) { // if a property that is used in a filter is changed, refresh filtering filterAll(); } /** * Filter the view to recreate the visible item list from the unfiltered * items, and send a notification if the set of visible items changed in any * way. */ @SuppressWarnings("unchecked") protected void filterAll() { // avoid notification if the filtering had no effect List<IDTYPE> originalItems = getFilteredItemIds(); // it is somewhat inefficient to do a (shallow) clone() every time setFilteredItemIds((List<IDTYPE>) ((ListSet<IDTYPE>) allItemIds) .clone()); for (Filter f : filters) { filter(f); } // check if exactly the same items are there after filtering to avoid // unnecessary notifications // this may be slow in some cases as it uses BEANTYPE.equals() if (!originalItems.equals(getFilteredItemIds())) { fireItemSetChange(); } } /** * Returns an unmodifiable collection of filters in use by the container. * * @return */ protected Set<Filter> getFilters() { return Collections.unmodifiableSet(filters); } /** * Remove (from the filtered list) any items that do not match the given * filter. * * @param f * The filter used to determine if items should be removed */ protected void filter(Filter f) { Iterator<IDTYPE> iterator = getFilteredItemIds().iterator(); while (iterator.hasNext()) { IDTYPE itemId = iterator.next(); if (!f.passesFilter(getItem(itemId))) { iterator.remove(); } } } /* * (non-Javadoc) * * @see * com.vaadin.data.Container.Filterable#addContainerFilter(java.lang.Object, * java.lang.String, boolean, boolean) */ @SuppressWarnings("unchecked") public void addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix) { if (filters.isEmpty()) { setFilteredItemIds((List<IDTYPE>) ((ListSet<IDTYPE>) allItemIds) .clone()); } // listen to change events to be able to update filtering for (Item item : itemIdToItem.values()) { addValueChangeListener(item, propertyId); } Filter f = new Filter(propertyId, filterString, ignoreCase, onlyMatchPrefix); filter(f); filters.add(f); fireItemSetChange(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Filterable#removeAllContainerFilters() */ public void removeAllContainerFilters() { if (!filters.isEmpty()) { filters = new HashSet<Filter>(); // stop listening to change events for any property for (Item item : itemIdToItem.values()) { removeAllValueChangeListeners(item); } filterAll(); } } /* * (non-Javadoc) * * @see * com.vaadin.data.Container.Filterable#removeContainerFilters(java.lang * .Object) */ public void removeContainerFilters(Object propertyId) { if (!filters.isEmpty()) { boolean filteringChanged = false; for (Iterator<Filter> iterator = filters.iterator(); iterator .hasNext();) { Filter f = iterator.next(); if (f.propertyId.equals(propertyId)) { iterator.remove(); filteringChanged = true; } } if (filteringChanged) { // stop listening to change events for the property for (Item item : itemIdToItem.values()) { removeValueChangeListener(item, propertyId); } filterAll(); } } } /** * Make this container listen to the given property provided it notifies * when its value changes. * * @param item * The {@link Item} that contains the property * @param propertyId * The id of the property */ private void addValueChangeListener(Item item, Object propertyId) { Property property = item.getItemProperty(propertyId); if (property instanceof ValueChangeNotifier) { // avoid multiple notifications for the same property if // multiple filters are in use ValueChangeNotifier notifier = (ValueChangeNotifier) property; notifier.removeListener(this); notifier.addListener(this); } } /** * Remove this container as a listener for the given property. * * @param item * The {@link Item} that contains the property * @param propertyId * The id of the property */ private void removeValueChangeListener(Item item, Object propertyId) { Property property = item.getItemProperty(propertyId); if (property instanceof ValueChangeNotifier) { ((ValueChangeNotifier) property).removeListener(this); } } /** * Remove this contains as a listener for all the properties in the given * {@link Item}. * * @param item * The {@link Item} that contains the properties */ private void removeAllValueChangeListeners(Item item) { for (Object propertyId : item.getItemPropertyIds()) { removeValueChangeListener(item, propertyId); } } /** * Unsupported operation. Use other methods to add items. */ public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Unsupported operation. Beans should be added through * {@code addItemAt(int, ...)}. */ public Object addItemAt(int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Sortable#getSortableContainerPropertyIds() */ public Collection<Object> getSortableContainerPropertyIds() { LinkedList<Object> sortables = new LinkedList<Object>(); for (Object propertyId : getContainerPropertyIds()) { Class<?> propertyType = getType(propertyId); if (Comparable.class.isAssignableFrom(propertyType) || propertyType.isPrimitive()) { sortables.add(propertyId); } } return sortables; } /* * (non-Javadoc) * * @see com.vaadin.data.Container.Sortable#sort(java.lang.Object[], * boolean[]) */ public void sort(Object[] propertyId, boolean[] ascending) { itemSorter.setSortProperties(this, propertyId, ascending); doSort(); // notifies if anything changes in the filtered list, including order filterAll(); } /** * Perform the sorting of the data structures in the container. This is * invoked when the <code>itemSorter</code> has been prepared for the sort * operation. Typically this method calls * <code>Collections.sort(aCollection, getItemSorter())</code> on all arrays * (containing item ids) that need to be sorted. * */ protected void doSort() { Collections.sort(allItemIds, getItemSorter()); } /** * Returns the ItemSorter that is used for sorting the container. * * @see #setItemSorter(ItemSorter) * * @return The ItemSorter that is used for sorting the container */ public ItemSorter getItemSorter() { return itemSorter; } /** * Sets the ItemSorter that is used for sorting the container. The * {@link ItemSorter#compare(Object, Object)} method is called to compare * two beans (item ids). * * @param itemSorter * The ItemSorter to use when sorting the container */ public void setItemSorter(ItemSorter itemSorter) { this.itemSorter = itemSorter; } /** * Unsupported operation. See subclasses of {@link AbstractBeanContainer} * for the correct way to add items. */ public Object addItem() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Adds the bean to all internal data structures at the given position. * Fails if the bean is already in the container or is not assignable to the * correct type. Returns a new BeanItem if the bean was added successfully. * * <p> * Caller should call {@link #filterAll()} after calling this method to * ensure the filtered list is updated. * </p> * * For internal use by subclasses only. This API is experimental and subject * to change. * * @param position * The position at which the bean should be inserted in the * unfiltered collection of items * @param itemId * The item identifier for the bean to insert * @param bean * The bean to insert * * @return BeanItem<BEANTYPE> if the bean was added successfully, null * otherwise */ protected BeanItem<BEANTYPE> internalAddAt(int position, IDTYPE itemId, BEANTYPE bean) { if (bean == null) { return null; } // Make sure that the item has not been added previously - if (allItemIds.contains(bean)) { + if (allItemIds.contains(itemId)) { return null; } if (!getBeanType().isAssignableFrom(bean.getClass())) { return null; } // "filteredList" will be updated in filterAll() which should be invoked // by the caller after calling this method. allItemIds.add(position, itemId); BeanItem<BEANTYPE> beanItem = createBeanItem(bean); itemIdToItem.put(itemId, beanItem); // add listeners to be able to update filtering on property // changes for (Filter filter : getFilters()) { // addValueChangeListener avoids adding duplicates addValueChangeListener(beanItem, filter.propertyId); } return beanItem; } /** * Returns the index of an item within the unfiltered collection of items. * * For internal use by subclasses only. This API is experimental and subject * to change. * * @param itemId * @return */ protected int internalIndexOf(IDTYPE itemId) { return allItemIds.indexOf(itemId); } /** * Adds a bean at the given index of the internal (unfiltered) list. * <p> * The item is also added in the visible part of the list if it passes the * filters. * </p> * * @param index * Internal index to add the new item. * @param newItemId * Id of the new item to be added. * @param bean * bean to be added * @return Returns new item or null if the operation fails. */ private BeanItem<BEANTYPE> addItemAtInternalIndex(int index, IDTYPE newItemId, BEANTYPE bean) { BeanItem<BEANTYPE> beanItem = internalAddAt(index, newItemId, bean); if (beanItem != null) { filterAll(); } return beanItem; } /** * Adds the bean to the Container. * * @see com.vaadin.data.Container#addItem(Object) */ protected BeanItem<BEANTYPE> addItem(IDTYPE itemId, BEANTYPE bean) { if (size() > 0) { // add immediately after last visible item int lastIndex = internalIndexOf(lastItemId()); return addItemAtInternalIndex(lastIndex + 1, itemId, bean); } else { return addItemAtInternalIndex(0, itemId, bean); } } /** * Adds the bean after the given bean. * * @see com.vaadin.data.Container.Ordered#addItemAfter(Object, Object) */ protected BeanItem<BEANTYPE> addItemAfter(IDTYPE previousItemId, IDTYPE newItemId, BEANTYPE bean) { // only add if the previous item is visible if (previousItemId == null) { return addItemAtInternalIndex(0, newItemId, bean); } else if (containsId(previousItemId)) { return addItemAtInternalIndex(internalIndexOf(previousItemId) + 1, newItemId, bean); } else { return null; } } /** * Adds a new bean at the given index. * * The bean is used both as the item contents and as the item identifier. * * @param index * Index at which the bean should be added. * @param newItemId * The item id for the bean to add to the container. * @param bean * The bean to add to the container. * * @return Returns the new BeanItem or null if the operation fails. */ protected BeanItem<BEANTYPE> addItemAt(int index, IDTYPE newItemId, BEANTYPE bean) { if (index < 0 || index > size()) { return null; } else if (index == 0) { // add before any item, visible or not return addItemAtInternalIndex(0, newItemId, bean); } else { // if index==size(), adds immediately after last visible item return addItemAfter(getIdByIndex(index - 1), newItemId, bean); } } /** * Adds a bean to the container using the bean item id resolver to find its * identifier. * * A bean id resolver must be set before calling this method. * * @see #addItem(Object, Object) * * @param bean * the bean to add * @return BeanItem<BEANTYPE> item added or null * @throws IllegalStateException * if no bean identifier resolver has been set * @throws IllegalArgumentException * if an identifier cannot be resolved for the bean */ protected BeanItem<BEANTYPE> addBean(BEANTYPE bean) throws IllegalStateException, IllegalArgumentException { if (beanIdResolver == null) { throw new IllegalStateException( "Bean item identifier resolver is required."); } if (bean == null) { return null; } IDTYPE itemId = beanIdResolver.getIdForBean(bean); if (itemId == null) { throw new IllegalArgumentException( "Resolved identifier for a bean must not be null"); } return addItem(itemId, bean); } /** * Adds a bean to the container after a specified item identifier, using the * bean item id resolver to find its identifier. * * A bean id resolver must be set before calling this method. * * @see #addItemAfter(Object, Object, Object) * * @param previousItemId * the identifier of the bean after which this bean should be * added, null to add to the beginning * @param bean * the bean to add * @return BeanItem<BEANTYPE> item added or null * @throws IllegalStateException * if no bean identifier resolver has been set * @throws IllegalArgumentException * if an identifier cannot be resolved for the bean */ protected BeanItem<BEANTYPE> addBeanAfter(IDTYPE previousItemId, BEANTYPE bean) throws IllegalStateException, IllegalArgumentException { if (beanIdResolver == null) { throw new IllegalStateException( "Bean item identifier resolver is required."); } if (bean == null) { return null; } IDTYPE itemId = beanIdResolver.getIdForBean(bean); if (itemId == null) { throw new IllegalArgumentException( "Resolved identifier for a bean must not be null"); } return addItemAfter(previousItemId, itemId, bean); } /** * Adds a bean at a specified (filtered view) position in the container * using the bean item id resolver to find its identifier. * * A bean id resolver must be set before calling this method. * * @see #addItemAfter(Object, Object, Object) * * @param index * the index (in the filtered view) at which to add the item * @param bean * the bean to add * @return BeanItem<BEANTYPE> item added or null * @throws IllegalStateException * if no bean identifier resolver has been set * @throws IllegalArgumentException * if an identifier cannot be resolved for the bean */ protected BeanItem<BEANTYPE> addBeanAt(int index, BEANTYPE bean) throws IllegalStateException, IllegalArgumentException { if (beanIdResolver == null) { throw new IllegalStateException( "Bean item identifier resolver is required."); } if (bean == null) { return null; } IDTYPE itemId = beanIdResolver.getIdForBean(bean); if (itemId == null) { throw new IllegalArgumentException( "Resolved identifier for a bean must not be null"); } return addItemAt(index, itemId, bean); } /** * Adds all the beans from a {@link Collection} in one operation using the * bean item identifier resolver. More efficient than adding them one by * one. * * A bean id resolver must be set before calling this method. * * @param collection * The collection of beans to add. Must not be null. * @throws IllegalStateException * if no bean identifier resolver has been set */ protected void addAll(Collection<? extends BEANTYPE> collection) throws IllegalStateException { if (beanIdResolver == null) { throw new IllegalStateException( "Bean item identifier resolver is required."); } int idx = internalIndexOf(lastItemId()) + 1; for (BEANTYPE bean : collection) { IDTYPE itemId = beanIdResolver.getIdForBean(bean); if (internalAddAt(idx, itemId, bean) != null) { idx++; } } // Filter the contents when all items have been added filterAll(); } /** * Sets the resolver that finds the item id for a bean, or null not to use * automatic resolving. * * Methods that add a bean without specifying an id must not be called if no * resolver has been set. * * Note that methods taking an explicit id can be used whether a resolver * has been defined or not. * * @param beanIdResolver * to use or null to disable automatic id resolution */ protected void setBeanIdResolver( BeanIdResolver<IDTYPE, BEANTYPE> beanIdResolver) { this.beanIdResolver = beanIdResolver; } /** * Returns the resolver that finds the item ID for a bean. * * @return resolver used or null if automatic item id resolving is disabled */ public BeanIdResolver<IDTYPE, BEANTYPE> getBeanIdResolver() { return beanIdResolver; } /** * Create an item identifier resolver using a named bean property. * * @param propertyId * property identifier, which must map to a getter in BEANTYPE * @return created resolver */ protected BeanIdResolver<IDTYPE, BEANTYPE> createBeanPropertyResolver( Object propertyId) { return new PropertyBasedBeanIdResolver(propertyId); } }
true
true
protected BeanItem<BEANTYPE> internalAddAt(int position, IDTYPE itemId, BEANTYPE bean) { if (bean == null) { return null; } // Make sure that the item has not been added previously if (allItemIds.contains(bean)) { return null; } if (!getBeanType().isAssignableFrom(bean.getClass())) { return null; } // "filteredList" will be updated in filterAll() which should be invoked // by the caller after calling this method. allItemIds.add(position, itemId); BeanItem<BEANTYPE> beanItem = createBeanItem(bean); itemIdToItem.put(itemId, beanItem); // add listeners to be able to update filtering on property // changes for (Filter filter : getFilters()) { // addValueChangeListener avoids adding duplicates addValueChangeListener(beanItem, filter.propertyId); } return beanItem; }
protected BeanItem<BEANTYPE> internalAddAt(int position, IDTYPE itemId, BEANTYPE bean) { if (bean == null) { return null; } // Make sure that the item has not been added previously if (allItemIds.contains(itemId)) { return null; } if (!getBeanType().isAssignableFrom(bean.getClass())) { return null; } // "filteredList" will be updated in filterAll() which should be invoked // by the caller after calling this method. allItemIds.add(position, itemId); BeanItem<BEANTYPE> beanItem = createBeanItem(bean); itemIdToItem.put(itemId, beanItem); // add listeners to be able to update filtering on property // changes for (Filter filter : getFilters()) { // addValueChangeListener avoids adding duplicates addValueChangeListener(beanItem, filter.propertyId); } return beanItem; }
diff --git a/src/org/openslide/dzi/DeepZoomGenerator.java b/src/org/openslide/dzi/DeepZoomGenerator.java index 245090c..de50f64 100644 --- a/src/org/openslide/dzi/DeepZoomGenerator.java +++ b/src/org/openslide/dzi/DeepZoomGenerator.java @@ -1,205 +1,205 @@ package org.openslide.dzi; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.File; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.imageio.ImageIO; import edu.cmu.cs.openslide.OpenSlide; public class DeepZoomGenerator { static final int TILE_SIZE = 256; static final int OVERLAP = 1; static final int numThreads = Runtime.getRuntime().availableProcessors(); static final ExecutorService executor = new ThreadPoolExecutor(numThreads, numThreads, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>( numThreads * 2), new ThreadPoolExecutor.CallerRunsPolicy()); public static void main(String[] args) throws IOException { File f = new File(args[0]); final OpenSlide os = new OpenSlide(f); long w = os.getLayer0Width(); long h = os.getLayer0Height(); String dirname; if (args.length > 1) { dirname = args[1]; } else { dirname = os.getProperties() .get(OpenSlide.PROPERTY_NAME_QUICKHASH1); } if (dirname == null) { System.out.println("Please give directory name on command line"); return; } File dir = new File(dirname); String bgcolorStr = os.getProperties().get( OpenSlide.PROPERTY_NAME_BACKGROUND_COLOR); if (bgcolorStr == null) { bgcolorStr = "FFFFFF"; } final Color bgcolor = Color.decode("#" + bgcolorStr); final AtomicInteger tileCount = new AtomicInteger(); long lastTime = System.currentTimeMillis(); long lastTiles = 0; double tilesPerSec = 0.0; // determine dzi level int level = (int) Math.ceil(Math.log(Math.max(w, h)) / Math.log(2)); final int topLevel = level; final long totalTiles = computeTotalTiles(w, h, level, TILE_SIZE); while (level >= 0) { System.out.println("generating level " + level + ": (" + (w / TILE_SIZE) + "," + (h / TILE_SIZE) + ")"); final File curDir = new File(dir, Integer.toString(level)); curDir.mkdirs(); int j = 0; for (int y = -OVERLAP; y < h; y += TILE_SIZE) { int th = TILE_SIZE + 2 * OVERLAP; if (y < 0) { - th -= y; + th += y; y = 0; } if (y + th > h) { th = (int) (h - y); } final int fth = th; final int fy = y; int i = 0; for (int x = -OVERLAP; x < w; x += TILE_SIZE) { int tw = TILE_SIZE + 2 * OVERLAP; if (x < 0) { - tw -= x; + tw += x; x = 0; } if (x + tw > w) { th = (int) (w - x); } final int ftw = tw; final int fx = x; final String filename = i + "_" + j; final File prevDir; if (level == topLevel) { prevDir = null; } else { prevDir = new File(dir, Integer.toString(level + 1)); } executor.execute(new Runnable() { @Override public void run() { tileCount.incrementAndGet(); File jpegFile = new File(curDir, filename + ".jpeg"); if (jpegFile.exists()) { return; } try { BufferedImage img = new BufferedImage(ftw, fth, BufferedImage.TYPE_INT_ARGB_PRE); if (prevDir == null) { // get from OpenSlide level 0 int dest[] = ((DataBufferInt) img .getRaster().getDataBuffer()) .getData(); os.paintRegionARGB(dest, fx, fy, 0, ftw, fth); // png File pngFile = new File(curDir, filename + ".png"); ImageIO.write(img, "png", pngFile); } else { // TODO generate from previous dir return; } // jpeg BufferedImage img2 = new BufferedImage(ftw, fth, BufferedImage.TYPE_INT_RGB); Graphics2D g = img2.createGraphics(); g.setColor(bgcolor); g.fillRect(0, 0, ftw, fth); g.drawImage(img, 0, 0, null); g.dispose(); ImageIO.write(img2, "jpeg", jpegFile); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } }); long time = System.currentTimeMillis(); long tilesComputed = tileCount.longValue(); long deltaTime = time - lastTime; if (deltaTime > 500) { long deltaTiles = tilesComputed - lastTiles; lastTime = time; lastTiles = tilesComputed; tilesPerSec = (0.9 * tilesPerSec) + (0.1 * (deltaTiles / (deltaTime / 1000.0))); int percent = (int) (100 * tilesComputed / totalTiles); System.out .print(" " + tilesComputed + "/" + totalTiles + " " + percent + "%, tiles per second: " + (int) tilesPerSec + " \r"); System.out.flush(); } i++; } j++; } System.out.println(); level--; } executor.shutdown(); } private static long computeTotalTiles(long w, long h, int level, int tileSize) { long t = 0; while (level >= 0) { long ww = (w / TILE_SIZE) + ((w % TILE_SIZE) == 0 ? 0 : 1); long hh = (h / TILE_SIZE) + ((h % TILE_SIZE) == 0 ? 0 : 1); t += ww * hh; w /= 2; h /= 2; level--; } return t; } }
false
true
public static void main(String[] args) throws IOException { File f = new File(args[0]); final OpenSlide os = new OpenSlide(f); long w = os.getLayer0Width(); long h = os.getLayer0Height(); String dirname; if (args.length > 1) { dirname = args[1]; } else { dirname = os.getProperties() .get(OpenSlide.PROPERTY_NAME_QUICKHASH1); } if (dirname == null) { System.out.println("Please give directory name on command line"); return; } File dir = new File(dirname); String bgcolorStr = os.getProperties().get( OpenSlide.PROPERTY_NAME_BACKGROUND_COLOR); if (bgcolorStr == null) { bgcolorStr = "FFFFFF"; } final Color bgcolor = Color.decode("#" + bgcolorStr); final AtomicInteger tileCount = new AtomicInteger(); long lastTime = System.currentTimeMillis(); long lastTiles = 0; double tilesPerSec = 0.0; // determine dzi level int level = (int) Math.ceil(Math.log(Math.max(w, h)) / Math.log(2)); final int topLevel = level; final long totalTiles = computeTotalTiles(w, h, level, TILE_SIZE); while (level >= 0) { System.out.println("generating level " + level + ": (" + (w / TILE_SIZE) + "," + (h / TILE_SIZE) + ")"); final File curDir = new File(dir, Integer.toString(level)); curDir.mkdirs(); int j = 0; for (int y = -OVERLAP; y < h; y += TILE_SIZE) { int th = TILE_SIZE + 2 * OVERLAP; if (y < 0) { th -= y; y = 0; } if (y + th > h) { th = (int) (h - y); } final int fth = th; final int fy = y; int i = 0; for (int x = -OVERLAP; x < w; x += TILE_SIZE) { int tw = TILE_SIZE + 2 * OVERLAP; if (x < 0) { tw -= x; x = 0; } if (x + tw > w) { th = (int) (w - x); } final int ftw = tw; final int fx = x; final String filename = i + "_" + j; final File prevDir; if (level == topLevel) { prevDir = null; } else { prevDir = new File(dir, Integer.toString(level + 1)); } executor.execute(new Runnable() { @Override public void run() { tileCount.incrementAndGet(); File jpegFile = new File(curDir, filename + ".jpeg"); if (jpegFile.exists()) { return; } try { BufferedImage img = new BufferedImage(ftw, fth, BufferedImage.TYPE_INT_ARGB_PRE); if (prevDir == null) { // get from OpenSlide level 0 int dest[] = ((DataBufferInt) img .getRaster().getDataBuffer()) .getData(); os.paintRegionARGB(dest, fx, fy, 0, ftw, fth); // png File pngFile = new File(curDir, filename + ".png"); ImageIO.write(img, "png", pngFile); } else { // TODO generate from previous dir return; } // jpeg BufferedImage img2 = new BufferedImage(ftw, fth, BufferedImage.TYPE_INT_RGB); Graphics2D g = img2.createGraphics(); g.setColor(bgcolor); g.fillRect(0, 0, ftw, fth); g.drawImage(img, 0, 0, null); g.dispose(); ImageIO.write(img2, "jpeg", jpegFile); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } }); long time = System.currentTimeMillis(); long tilesComputed = tileCount.longValue(); long deltaTime = time - lastTime; if (deltaTime > 500) { long deltaTiles = tilesComputed - lastTiles; lastTime = time; lastTiles = tilesComputed; tilesPerSec = (0.9 * tilesPerSec) + (0.1 * (deltaTiles / (deltaTime / 1000.0))); int percent = (int) (100 * tilesComputed / totalTiles); System.out .print(" " + tilesComputed + "/" + totalTiles + " " + percent + "%, tiles per second: " + (int) tilesPerSec + " \r"); System.out.flush(); } i++; } j++; } System.out.println(); level--; } executor.shutdown(); }
public static void main(String[] args) throws IOException { File f = new File(args[0]); final OpenSlide os = new OpenSlide(f); long w = os.getLayer0Width(); long h = os.getLayer0Height(); String dirname; if (args.length > 1) { dirname = args[1]; } else { dirname = os.getProperties() .get(OpenSlide.PROPERTY_NAME_QUICKHASH1); } if (dirname == null) { System.out.println("Please give directory name on command line"); return; } File dir = new File(dirname); String bgcolorStr = os.getProperties().get( OpenSlide.PROPERTY_NAME_BACKGROUND_COLOR); if (bgcolorStr == null) { bgcolorStr = "FFFFFF"; } final Color bgcolor = Color.decode("#" + bgcolorStr); final AtomicInteger tileCount = new AtomicInteger(); long lastTime = System.currentTimeMillis(); long lastTiles = 0; double tilesPerSec = 0.0; // determine dzi level int level = (int) Math.ceil(Math.log(Math.max(w, h)) / Math.log(2)); final int topLevel = level; final long totalTiles = computeTotalTiles(w, h, level, TILE_SIZE); while (level >= 0) { System.out.println("generating level " + level + ": (" + (w / TILE_SIZE) + "," + (h / TILE_SIZE) + ")"); final File curDir = new File(dir, Integer.toString(level)); curDir.mkdirs(); int j = 0; for (int y = -OVERLAP; y < h; y += TILE_SIZE) { int th = TILE_SIZE + 2 * OVERLAP; if (y < 0) { th += y; y = 0; } if (y + th > h) { th = (int) (h - y); } final int fth = th; final int fy = y; int i = 0; for (int x = -OVERLAP; x < w; x += TILE_SIZE) { int tw = TILE_SIZE + 2 * OVERLAP; if (x < 0) { tw += x; x = 0; } if (x + tw > w) { th = (int) (w - x); } final int ftw = tw; final int fx = x; final String filename = i + "_" + j; final File prevDir; if (level == topLevel) { prevDir = null; } else { prevDir = new File(dir, Integer.toString(level + 1)); } executor.execute(new Runnable() { @Override public void run() { tileCount.incrementAndGet(); File jpegFile = new File(curDir, filename + ".jpeg"); if (jpegFile.exists()) { return; } try { BufferedImage img = new BufferedImage(ftw, fth, BufferedImage.TYPE_INT_ARGB_PRE); if (prevDir == null) { // get from OpenSlide level 0 int dest[] = ((DataBufferInt) img .getRaster().getDataBuffer()) .getData(); os.paintRegionARGB(dest, fx, fy, 0, ftw, fth); // png File pngFile = new File(curDir, filename + ".png"); ImageIO.write(img, "png", pngFile); } else { // TODO generate from previous dir return; } // jpeg BufferedImage img2 = new BufferedImage(ftw, fth, BufferedImage.TYPE_INT_RGB); Graphics2D g = img2.createGraphics(); g.setColor(bgcolor); g.fillRect(0, 0, ftw, fth); g.drawImage(img, 0, 0, null); g.dispose(); ImageIO.write(img2, "jpeg", jpegFile); } catch (IOException e) { e.printStackTrace(); System.exit(0); } } }); long time = System.currentTimeMillis(); long tilesComputed = tileCount.longValue(); long deltaTime = time - lastTime; if (deltaTime > 500) { long deltaTiles = tilesComputed - lastTiles; lastTime = time; lastTiles = tilesComputed; tilesPerSec = (0.9 * tilesPerSec) + (0.1 * (deltaTiles / (deltaTime / 1000.0))); int percent = (int) (100 * tilesComputed / totalTiles); System.out .print(" " + tilesComputed + "/" + totalTiles + " " + percent + "%, tiles per second: " + (int) tilesPerSec + " \r"); System.out.flush(); } i++; } j++; } System.out.println(); level--; } executor.shutdown(); }
diff --git a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/filter/SabEntitlementsFilter.java b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/filter/SabEntitlementsFilter.java index 3521470d..f2e0e79e 100644 --- a/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/filter/SabEntitlementsFilter.java +++ b/coin-selfservice-war/src/main/java/nl/surfnet/coin/selfservice/filter/SabEntitlementsFilter.java @@ -1,152 +1,152 @@ /* * Copyright 2013 SURFnet bv, The Netherlands * * 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 nl.surfnet.coin.selfservice.filter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import nl.surfnet.coin.selfservice.domain.CoinAuthority; import nl.surfnet.coin.selfservice.domain.CoinUser; import nl.surfnet.coin.selfservice.util.SpringSecurity; import nl.surfnet.sab.Sab; import nl.surfnet.sab.SabRoleHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.GrantedAuthority; import org.springframework.web.filter.GenericFilterBean; import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_DISTRIBUTION_CHANNEL_ADMIN; import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_IDP_LICENSE_ADMIN; import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_IDP_SURFCONEXT_ADMIN; import static nl.surfnet.coin.selfservice.domain.CoinAuthority.Authority.ROLE_USER; public class SabEntitlementsFilter extends GenericFilterBean { private static final Logger LOG = LoggerFactory.getLogger(SabEntitlementsFilter.class); protected static final String PROCESSED = "nl.surfnet.coin.selfservice.filter.SabEntitlementsFilter.PROCESSED"; private boolean lmngActive; @Resource private Sab sab; private String adminDistributionRole; private String adminLicentieIdPRole; private String adminSurfConextIdPRole; private String viewerSurfConextIdPRole; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpSession session = httpRequest.getSession(true); if (SpringSecurity.isFullyAuthenticated() && session.getAttribute(PROCESSED) == null) { CoinUser user = SpringSecurity.getCurrentUser(); try { SabRoleHolder roleHolder = sab.getRoles(user.getUid()); if (roleHolder == null) { LOG.debug("SAB returned no information about user '{}'. Will skip SAB entitlement.", user.getUid()); session.setAttribute(PROCESSED, "true"); } else { LOG.debug("Roles of user '{}' in organisation {}: {}", user.getUid(), roleHolder.getOrganisation(), roleHolder.getRoles()); elevateUserIfApplicable(user, roleHolder); session.setAttribute(PROCESSED, "true"); LOG.debug("Authorities of user '{}' after processing SAB entitlements: {}", user.getUid(), user.getAuthorityEnums()); } } catch (IOException e) { LOG.info("Skipping SAB entitlement, SAB request got IOException: {}", e.getMessage()); } } chain.doFilter(request, response); } private void elevateUserIfApplicable(CoinUser user, SabRoleHolder roleHolder) { - if (roleHolder.getOrganisation().equals(user.getSchacHomeOrganization())) { + if (roleHolder.getOrganisation() != null && roleHolder.getOrganisation().equals(user.getSchacHomeOrganization())) { if (!adminDistributionRole.isEmpty() && roleHolder.getRoles().contains(adminDistributionRole)) { user.setAuthorities(new ArrayList<CoinAuthority>()); user.addAuthority(new CoinAuthority(ROLE_DISTRIBUTION_CHANNEL_ADMIN)); } else { List<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>(); if (!adminLicentieIdPRole.isEmpty() && roleHolder.getRoles().contains(adminLicentieIdPRole) && this.lmngActive) { newAuthorities.add(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN)); } if (!adminSurfConextIdPRole.isEmpty() && roleHolder.getRoles().contains(adminSurfConextIdPRole)) { newAuthorities.add(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN)); } if (!viewerSurfConextIdPRole.isEmpty() && roleHolder.getRoles().contains(viewerSurfConextIdPRole)) { // BACKLOG-940: for now, only users having this role will be allowed access. // No regular end users yet. // In the future, this 'viewer' (SURFconextbeheerder) user probably deserves a role of its own, instead of the USER role. newAuthorities.add(new CoinAuthority(CoinAuthority.Authority.ROLE_USER)); } // Now merge with earlier assigned authorities if (user.getAuthorityEnums().contains(ROLE_DISTRIBUTION_CHANNEL_ADMIN)) { // nothing, highest role possible } else if (user.getAuthorityEnums().contains(ROLE_IDP_LICENSE_ADMIN) && newAuthorities.contains(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN))) { user.addAuthority(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN)); } else if (user.getAuthorityEnums().contains(ROLE_IDP_SURFCONEXT_ADMIN) && newAuthorities.contains(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN))) { user.addAuthority(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN)); } else if (newAuthorities.contains(new CoinAuthority(ROLE_USER))) { user.addAuthority(new CoinAuthority(ROLE_USER)); } } } else { LOG.debug("User ({})'s SchacHomeOrg ({}) does not match organisation in SAB ({}). Will not apply roles.", user.getUid(), user.getSchacHomeOrganization(), roleHolder.getOrganisation()); return; } } @Override public void destroy() { } public void setAdminDistributionRole(String adminDistributionRole) { this.adminDistributionRole = adminDistributionRole; } public void setAdminLicentieIdPRole(String adminLicentieIdPRole) { this.adminLicentieIdPRole = adminLicentieIdPRole; } public void setAdminSurfConextIdPRole(String adminSurfConextIdPRole) { this.adminSurfConextIdPRole = adminSurfConextIdPRole; } public void setViewerSurfConextIdPRole(String viewerSurfConextIdPRole) { this.viewerSurfConextIdPRole = viewerSurfConextIdPRole; } public void setLmngActive(boolean lmngActive) { this.lmngActive = lmngActive; } }
true
true
private void elevateUserIfApplicable(CoinUser user, SabRoleHolder roleHolder) { if (roleHolder.getOrganisation().equals(user.getSchacHomeOrganization())) { if (!adminDistributionRole.isEmpty() && roleHolder.getRoles().contains(adminDistributionRole)) { user.setAuthorities(new ArrayList<CoinAuthority>()); user.addAuthority(new CoinAuthority(ROLE_DISTRIBUTION_CHANNEL_ADMIN)); } else { List<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>(); if (!adminLicentieIdPRole.isEmpty() && roleHolder.getRoles().contains(adminLicentieIdPRole) && this.lmngActive) { newAuthorities.add(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN)); } if (!adminSurfConextIdPRole.isEmpty() && roleHolder.getRoles().contains(adminSurfConextIdPRole)) { newAuthorities.add(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN)); } if (!viewerSurfConextIdPRole.isEmpty() && roleHolder.getRoles().contains(viewerSurfConextIdPRole)) { // BACKLOG-940: for now, only users having this role will be allowed access. // No regular end users yet. // In the future, this 'viewer' (SURFconextbeheerder) user probably deserves a role of its own, instead of the USER role. newAuthorities.add(new CoinAuthority(CoinAuthority.Authority.ROLE_USER)); } // Now merge with earlier assigned authorities if (user.getAuthorityEnums().contains(ROLE_DISTRIBUTION_CHANNEL_ADMIN)) { // nothing, highest role possible } else if (user.getAuthorityEnums().contains(ROLE_IDP_LICENSE_ADMIN) && newAuthorities.contains(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN))) { user.addAuthority(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN)); } else if (user.getAuthorityEnums().contains(ROLE_IDP_SURFCONEXT_ADMIN) && newAuthorities.contains(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN))) { user.addAuthority(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN)); } else if (newAuthorities.contains(new CoinAuthority(ROLE_USER))) { user.addAuthority(new CoinAuthority(ROLE_USER)); } } } else { LOG.debug("User ({})'s SchacHomeOrg ({}) does not match organisation in SAB ({}). Will not apply roles.", user.getUid(), user.getSchacHomeOrganization(), roleHolder.getOrganisation()); return; } }
private void elevateUserIfApplicable(CoinUser user, SabRoleHolder roleHolder) { if (roleHolder.getOrganisation() != null && roleHolder.getOrganisation().equals(user.getSchacHomeOrganization())) { if (!adminDistributionRole.isEmpty() && roleHolder.getRoles().contains(adminDistributionRole)) { user.setAuthorities(new ArrayList<CoinAuthority>()); user.addAuthority(new CoinAuthority(ROLE_DISTRIBUTION_CHANNEL_ADMIN)); } else { List<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>(); if (!adminLicentieIdPRole.isEmpty() && roleHolder.getRoles().contains(adminLicentieIdPRole) && this.lmngActive) { newAuthorities.add(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN)); } if (!adminSurfConextIdPRole.isEmpty() && roleHolder.getRoles().contains(adminSurfConextIdPRole)) { newAuthorities.add(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN)); } if (!viewerSurfConextIdPRole.isEmpty() && roleHolder.getRoles().contains(viewerSurfConextIdPRole)) { // BACKLOG-940: for now, only users having this role will be allowed access. // No regular end users yet. // In the future, this 'viewer' (SURFconextbeheerder) user probably deserves a role of its own, instead of the USER role. newAuthorities.add(new CoinAuthority(CoinAuthority.Authority.ROLE_USER)); } // Now merge with earlier assigned authorities if (user.getAuthorityEnums().contains(ROLE_DISTRIBUTION_CHANNEL_ADMIN)) { // nothing, highest role possible } else if (user.getAuthorityEnums().contains(ROLE_IDP_LICENSE_ADMIN) && newAuthorities.contains(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN))) { user.addAuthority(new CoinAuthority(ROLE_IDP_SURFCONEXT_ADMIN)); } else if (user.getAuthorityEnums().contains(ROLE_IDP_SURFCONEXT_ADMIN) && newAuthorities.contains(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN))) { user.addAuthority(new CoinAuthority(ROLE_IDP_LICENSE_ADMIN)); } else if (newAuthorities.contains(new CoinAuthority(ROLE_USER))) { user.addAuthority(new CoinAuthority(ROLE_USER)); } } } else { LOG.debug("User ({})'s SchacHomeOrg ({}) does not match organisation in SAB ({}). Will not apply roles.", user.getUid(), user.getSchacHomeOrganization(), roleHolder.getOrganisation()); return; } }
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java index 3cc171bf8..ee6ddd946 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java @@ -1,308 +1,308 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text.source; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControlCreator; /** * A hover for line oriented diffs. It determines the text to show as hover for a certain line in the * document. * * @since 3.0 */ public class LineChangeHover implements IAnnotationHover, IAnnotationHoverExtension { /* * @see org.eclipse.jface.text.source.IAnnotationHover#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, int) */ public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { return null; } /** * Formats the source w/ syntax coloring etc. This implementation replaces tabs with spaces. * May be overridden by subclasses. * * @param content the hover content * @return <code>content</code> reformatted */ protected String formatSource(String content) { if (content != null) { StringBuffer sb= new StringBuffer(content); final String tabReplacement= getTabReplacement(); for (int pos= 0; pos < sb.length(); pos++) { if (sb.charAt(pos) == '\t') sb.replace(pos, pos + 1, tabReplacement); } return sb.toString(); } return content; } /** * Returns a replacement for the tab character. The default implementation * returns a tabulator character, but subclasses may override to specify a * number of spaces. * * @return a whitespace String that will be substituted for the tabulator * character */ protected String getTabReplacement() { return "\t"; //$NON-NLS-1$ } /** * Computes the content of the hover for the document contained in <code>viewer</code> on * line <code>line</code>. * * @param viewer the connected viewer * @param first the first line in <code>viewer</code>'s document to consider * @param last the last line in <code>viewer</code>'s document to consider * @param maxLines the max number of lines * @return The hover content corresponding to the parameters * @see #getHoverInfo(ISourceViewer, int) * @see #getHoverInfo(ISourceViewer, ILineRange, int) */ private String computeContent(ISourceViewer viewer, int first, int last, int maxLines) { ILineDiffer differ= getDiffer(viewer); if (differ == null) return null; final List lines= new LinkedList(); for (int l= first; l <= last; l++) { ILineDiffInfo info= differ.getLineInfo(l); if (info != null) lines.add(info); } return decorateText(lines, maxLines); } /** * Takes a list of <code>ILineDiffInfo</code>s and computes a hover of at most <code>maxLines</code>. * Added lines are prefixed with a <code>'+'</code>, changed lines with <code>'>'</code> and * deleted lines with <code>'-'</code>. * <p>Deleted and added lines can even each other out, so that a number of deleted lines get * displayed where - in the current document - the added lines are. * * @param diffInfos a <code>List</code> of <code>ILineDiffInfo</code> * @param maxLines the maximum number of lines. Note that adding up all annotations might give * more than that due to deleted lines. * @return a <code>String</code> suitable for hover display */ protected String decorateText(List diffInfos, int maxLines) { /* maxLines controls the size of the hover (not more than what fits into the display are of * the viewer). * added controls how many lines are added - added lines are */ String text= new String(); int added= 0; for (Iterator it= diffInfos.iterator(); it.hasNext();) { ILineDiffInfo info= (ILineDiffInfo)it.next(); String[] original= info.getOriginalText(); int type= info.getChangeType(); int i= 0; if (type == ILineDiffInfo.ADDED) added++; else if (type == ILineDiffInfo.CHANGED) { text += "> " + (original.length > 0 ? original[i++] : ""); //$NON-NLS-1$ //$NON-NLS-2$ maxLines--; } else if (type == ILineDiffInfo.UNCHANGED) { maxLines++; } if (maxLines == 0) return trimTrailing(text); for (; i < original.length; i++) { text += "- " + original[i]; //$NON-NLS-1$ added--; if (--maxLines == 0) return trimTrailing(text); } } text= text.trim(); if (text.length() == 0 && added-- > 0 && maxLines-- > 0) text += "+ "; //$NON-NLS-1$ while (added-- > 0 && maxLines-- > 0) text += "\n+ "; //$NON-NLS-1$ return text; } /** * Trims trailing spaces * * @param text a <code>String</code> * @return a copy of <code>text</code> with trailing spaces removed */ private String trimTrailing(String text) { int pos= text.length() - 1; while (pos >= 0 && Character.isWhitespace(text.charAt(pos))) { pos--; } return text.substring(0, pos + 1); } /** * Extracts the line differ - if any - from the viewer's document's annotation model. * @param viewer the viewer * @return a line differ for the document displayed in viewer, or <code>null</code>. */ private ILineDiffer getDiffer(ISourceViewer viewer) { IAnnotationModel model= viewer.getAnnotationModel(); if (model == null) return null; if (model instanceof IAnnotationModelExtension) { IAnnotationModel diffModel= ((IAnnotationModelExtension)model).getAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID); if (diffModel != null) model= diffModel; } if (model instanceof ILineDiffer) return (ILineDiffer)model; else return null; } /** * Computes the block of lines which form a contiguous block of changes covering <code>line</code>. * * @param viewer the source viewer showing * @param line the line which a hover is displayed for * @param min the first line in <code>viewer</code>'s document to consider * @param max the last line in <code>viewer</code>'s document to consider * @return the selection in the document displayed in <code>viewer</code> containing <code>line</code> * that is covered by the hover information returned by the receiver. */ protected Point computeLineRange(ISourceViewer viewer, int line, int min, int max) { /* Algorithm: * All lines that have changes to themselves (added, changed) are taken that form a * contiguous block of lines that includes <code>line</code>. * * If <code>line</code> is itself unchanged, if there is a deleted line either above or * below, or both, the lines +/- 1 from <code>line</code> are included in the search as well, * without applying this last rule to them, though. (I.e., if <code>line</code> is unchanged, * but has a deleted line above, this one is taken in. If the line above has changes, the block * is extended from there. If the line has no changes itself, the search stops). * * The block never extends the visible line range of the viewer. */ ILineDiffer differ= getDiffer(viewer); if (differ == null) - return null; + return new Point(-1, -1); // backward search int l= line; ILineDiffInfo info= differ.getLineInfo(l); // search backwards until a line has no changes to itself while (l >= min && info != null && (info.getChangeType() == ILineDiffInfo.CHANGED || info.getChangeType() == ILineDiffInfo.ADDED)) { info= differ.getLineInfo(--l); } int first= Math.min(l + 1, line); // forward search l= line; info= differ.getLineInfo(l); // search forward until a line has no changes to itself while (l <= max && info != null && (info.getChangeType() == ILineDiffInfo.CHANGED || info.getChangeType() == ILineDiffInfo.ADDED)) { info= differ.getLineInfo(++l); } int last= Math.max(l - 1, line); return new Point(first, last); } /* * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverControlCreator() */ public IInformationControlCreator getHoverControlCreator() { return null; } /* * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverInfo(org.eclipse.jface.text.source.ISourceViewer, org.eclipse.jface.text.source.ILineRange, int) */ public Object getHoverInfo(ISourceViewer sourceViewer, ILineRange lineRange, int visibleLines) { int first= adaptFirstLine(sourceViewer, lineRange.getStartLine()); int last= adaptLastLine(sourceViewer, lineRange.getStartLine() + lineRange.getNumberOfLines() - 1); String content= computeContent(sourceViewer, first, last, visibleLines); return formatSource(content); } /** * Adapts the start line to the implementation of <code>ILineDiffInfo</code>. * * @param startLine the line to adapt * @return <code>startLine - 1</code> if that line exists and is an * unchanged line followed by deletions, <code>startLine</code> * otherwise */ private int adaptFirstLine(ISourceViewer viewer, int startLine) { ILineDiffer differ= getDiffer(viewer); if (differ != null && startLine > 0) { int l= startLine - 1; ILineDiffInfo info= differ.getLineInfo(l); if (info != null && info.getChangeType() == ILineDiffInfo.UNCHANGED && info.getRemovedLinesBelow() > 0) return l; } return startLine; } /** * Adapts the last line to the implementation of <code>ILineDiffInfo</code>. * * @param lastLine the line to adapt * @return <code>lastLine - 1</code> if that line exists and is an * unchanged line followed by deletions, <code>startLine</code> * otherwise */ private int adaptLastLine(ISourceViewer viewer, int lastLine) { ILineDiffer differ= getDiffer(viewer); if (differ != null && lastLine > 0) { ILineDiffInfo info= differ.getLineInfo(lastLine); if (info != null && info.getChangeType() == ILineDiffInfo.UNCHANGED) return lastLine - 1; } return lastLine; } /* * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverLineRange(org.eclipse.jface.text.source.ISourceViewer, int) */ public ILineRange getHoverLineRange(ISourceViewer viewer, int lineNumber) { IDocument document= viewer.getDocument(); if (document != null) { Point range= computeLineRange(viewer, lineNumber, 0, Math.max(0, document.getNumberOfLines() - 1)); if (range.x != -1 && range.y != -1) return new LineRange(range.x, range.y - range.x + 1); } return null; } /* * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#canHandleMouseCursor() */ public boolean canHandleMouseCursor() { return false; } }
true
true
protected Point computeLineRange(ISourceViewer viewer, int line, int min, int max) { /* Algorithm: * All lines that have changes to themselves (added, changed) are taken that form a * contiguous block of lines that includes <code>line</code>. * * If <code>line</code> is itself unchanged, if there is a deleted line either above or * below, or both, the lines +/- 1 from <code>line</code> are included in the search as well, * without applying this last rule to them, though. (I.e., if <code>line</code> is unchanged, * but has a deleted line above, this one is taken in. If the line above has changes, the block * is extended from there. If the line has no changes itself, the search stops). * * The block never extends the visible line range of the viewer. */ ILineDiffer differ= getDiffer(viewer); if (differ == null) return null; // backward search int l= line; ILineDiffInfo info= differ.getLineInfo(l); // search backwards until a line has no changes to itself while (l >= min && info != null && (info.getChangeType() == ILineDiffInfo.CHANGED || info.getChangeType() == ILineDiffInfo.ADDED)) { info= differ.getLineInfo(--l); } int first= Math.min(l + 1, line); // forward search l= line; info= differ.getLineInfo(l); // search forward until a line has no changes to itself while (l <= max && info != null && (info.getChangeType() == ILineDiffInfo.CHANGED || info.getChangeType() == ILineDiffInfo.ADDED)) { info= differ.getLineInfo(++l); } int last= Math.max(l - 1, line); return new Point(first, last); }
protected Point computeLineRange(ISourceViewer viewer, int line, int min, int max) { /* Algorithm: * All lines that have changes to themselves (added, changed) are taken that form a * contiguous block of lines that includes <code>line</code>. * * If <code>line</code> is itself unchanged, if there is a deleted line either above or * below, or both, the lines +/- 1 from <code>line</code> are included in the search as well, * without applying this last rule to them, though. (I.e., if <code>line</code> is unchanged, * but has a deleted line above, this one is taken in. If the line above has changes, the block * is extended from there. If the line has no changes itself, the search stops). * * The block never extends the visible line range of the viewer. */ ILineDiffer differ= getDiffer(viewer); if (differ == null) return new Point(-1, -1); // backward search int l= line; ILineDiffInfo info= differ.getLineInfo(l); // search backwards until a line has no changes to itself while (l >= min && info != null && (info.getChangeType() == ILineDiffInfo.CHANGED || info.getChangeType() == ILineDiffInfo.ADDED)) { info= differ.getLineInfo(--l); } int first= Math.min(l + 1, line); // forward search l= line; info= differ.getLineInfo(l); // search forward until a line has no changes to itself while (l <= max && info != null && (info.getChangeType() == ILineDiffInfo.CHANGED || info.getChangeType() == ILineDiffInfo.ADDED)) { info= differ.getLineInfo(++l); } int last= Math.max(l - 1, line); return new Point(first, last); }
diff --git a/core/src/main/java/io/undertow/server/handlers/DateHandler.java b/core/src/main/java/io/undertow/server/handlers/DateHandler.java index 4277d7aa0..6afbc0cd6 100644 --- a/core/src/main/java/io/undertow/server/handlers/DateHandler.java +++ b/core/src/main/java/io/undertow/server/handlers/DateHandler.java @@ -1,44 +1,45 @@ package io.undertow.server.handlers; import java.util.Date; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.DateUtils; import io.undertow.util.Headers; /** * Class that adds the Date: header to a HTTP response. * * The current date string is cached, and is updated every second in a racey * manner (i.e. it is possible for two thread to update it at once). * * @author Stuart Douglas */ public class DateHandler implements HttpHandler { private final HttpHandler next; private volatile String cachedDateString; private volatile long nextUpdateTime = -1; public DateHandler(final HttpHandler next) { this.next = next; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { - long time = System.currentTimeMillis(); + long time = System.nanoTime(); if(time < nextUpdateTime) { exchange.getResponseHeaders().put(Headers.DATE, cachedDateString); } else { - String dateString = DateUtils.toDateString(new Date(time)); + long realTime = System.currentTimeMillis(); + String dateString = DateUtils.toDateString(new Date(realTime)); cachedDateString = dateString; - nextUpdateTime = time + 1000; + nextUpdateTime = time + 1000000000; exchange.getResponseHeaders().put(Headers.DATE, dateString); } next.handleRequest(exchange); } }
false
true
public void handleRequest(final HttpServerExchange exchange) throws Exception { long time = System.currentTimeMillis(); if(time < nextUpdateTime) { exchange.getResponseHeaders().put(Headers.DATE, cachedDateString); } else { String dateString = DateUtils.toDateString(new Date(time)); cachedDateString = dateString; nextUpdateTime = time + 1000; exchange.getResponseHeaders().put(Headers.DATE, dateString); } next.handleRequest(exchange); }
public void handleRequest(final HttpServerExchange exchange) throws Exception { long time = System.nanoTime(); if(time < nextUpdateTime) { exchange.getResponseHeaders().put(Headers.DATE, cachedDateString); } else { long realTime = System.currentTimeMillis(); String dateString = DateUtils.toDateString(new Date(realTime)); cachedDateString = dateString; nextUpdateTime = time + 1000000000; exchange.getResponseHeaders().put(Headers.DATE, dateString); } next.handleRequest(exchange); }
diff --git a/connectors/common/src/de/ub0r/android/websms/connector/common/Log.java b/connectors/common/src/de/ub0r/android/websms/connector/common/Log.java index bf638b9e..a98371d9 100644 --- a/connectors/common/src/de/ub0r/android/websms/connector/common/Log.java +++ b/connectors/common/src/de/ub0r/android/websms/connector/common/Log.java @@ -1,271 +1,276 @@ /* * Copyright (C) 2010 Felix Bechstein * * This file is part of WebSMS. * * 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.ub0r.android.websms.connector.common; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; /** * @author flx */ public final class Log { /** Tag for output. */ public static final String TAG = "WebSMS"; /** Packagename of SendLog. */ private static final String SENDLOG_PACKAGE_NAME = "org.l6n.sendlog"; /** Classname of SendLog. */ // private static final String SENDLOG_CLASS_NAME = ".SendLog"; /** Priority constant for the println method. */ public static final int ASSERT = android.util.Log.ASSERT; /** Priority constant for the println method; use Log.d. */ public static final int DEBUG = android.util.Log.DEBUG; /** Priority constant for the println method; use Log.e. */ public static final int ERROR = android.util.Log.ERROR; /** Priority constant for the println method; use Log.i. */ public static final int INFO = android.util.Log.INFO; /** Priority constant for the println method; use Log.v. */ public static final int VERBOSE = android.util.Log.VERBOSE; /** Priority constant for the println method; use Log.w. */ public static final int WARN = android.util.Log.WARN; /** * Fire a given {@link Intent}. * * @author flx */ private static class FireIntent implements DialogInterface.OnClickListener { /** {@link Activity}. */ private final Activity a; /** {@link Intent}. */ private final Intent i; /** * Default Constructor. * * @param activity * {@link Activity} * @param intent * {@link Intent} */ public FireIntent(final Activity activity, final Intent intent) { this.a = activity; this.i = intent; } /** * {@inheritDoc} */ public void onClick(final DialogInterface dialog, // . final int whichButton) { this.a.startActivity(this.i); } } /** * Default Constructor. */ private Log() { } /** * Send a DEBUG log message. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. */ public static void d(final String tag, final String msg) { android.util.Log.d(TAG, tag + ": " + msg); } /** * Send a DEBUG log message and log the exception. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. * @param tr * An exception to log. */ public static void d(final String tag, final String msg, // . final Throwable tr) { android.util.Log.d(TAG, tag + ": " + msg, tr); } /** * Send a ERROR log message. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. */ public static void e(final String tag, final String msg) { android.util.Log.e(TAG, tag + ": " + msg); } /** * Send a ERROR log message and log the exception. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. * @param tr * An exception to log. */ public static void e(final String tag, final String msg, // . final Throwable tr) { android.util.Log.e(TAG, tag + ": " + msg, tr); } /** * Send a INFO log message. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. */ public static void i(final String tag, final String msg) { android.util.Log.i(TAG, tag + ": " + msg); } /** * Send a INFO log message and log the exception. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. * @param tr * An exception to log. */ public static void i(final String tag, final String msg, // . final Throwable tr) { android.util.Log.i(TAG, tag + ": " + msg, tr); } /** * Send a VERBOSE log message. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. */ public static void v(final String tag, final String msg) { android.util.Log.v(TAG, tag + ": " + msg); } /** * Send a VERBOSE log message and log the exception. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. * @param tr * An exception to log. */ public static void v(final String tag, final String msg, // . final Throwable tr) { android.util.Log.v(TAG, tag + ": " + msg, tr); } /** * Send a WARN log message. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. */ public static void w(final String tag, final String msg) { android.util.Log.w(TAG, tag + ": " + msg); } /** * Send a WARN log message and log the exception. * * @param tag * Used to identify the source of a log message. It usually * identifies the class or activity where the log call occurs. * @param msg * The message you would like logged. * @param tr * An exception to log. */ public static void w(final String tag, final String msg, // . final Throwable tr) { android.util.Log.w(TAG, tag + ": " + msg, tr); } /** * Collect and send Log. * * @param activity * {@link Activity}. */ public static void collectAndSendLog(final Activity activity) { final PackageManager packageManager = activity.getPackageManager(); Intent intent = packageManager .getLaunchIntentForPackage(SENDLOG_PACKAGE_NAME); + final String pkg = activity.getPackageName(); int title, message; if (intent == null) { intent = new Intent(Intent.ACTION_VIEW, Uri .parse("market://search?q=pname:" + SENDLOG_PACKAGE_NAME)); - title = R.string.sendlog_install_; - message = R.string.sendlog_install; + title = activity.getResources().getIdentifier("sendlog_install_", + "string", pkg); + message = activity.getResources().getIdentifier("sendlog_install", + "string", pkg); } else { intent.putExtra("filter", TAG + ":D *:W"); intent.setType("0||[email protected]"); - title = R.string.sendlog_run_; - message = R.string.sendlog_run; + title = activity.getResources().getIdentifier("sendlog_run_", + "string", pkg); + message = activity.getResources().getIdentifier("sendlog_run", + "string", pkg); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final AlertDialog.Builder b = new AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_info); b.setTitle(title); b.setMessage(message); b.setPositiveButton(android.R.string.ok, new FireIntent(activity, intent)); b.setNegativeButton(android.R.string.cancel, null); b.show(); } }
false
true
public static void collectAndSendLog(final Activity activity) { final PackageManager packageManager = activity.getPackageManager(); Intent intent = packageManager .getLaunchIntentForPackage(SENDLOG_PACKAGE_NAME); int title, message; if (intent == null) { intent = new Intent(Intent.ACTION_VIEW, Uri .parse("market://search?q=pname:" + SENDLOG_PACKAGE_NAME)); title = R.string.sendlog_install_; message = R.string.sendlog_install; } else { intent.putExtra("filter", TAG + ":D *:W"); intent.setType("0||[email protected]"); title = R.string.sendlog_run_; message = R.string.sendlog_run; } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final AlertDialog.Builder b = new AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_info); b.setTitle(title); b.setMessage(message); b.setPositiveButton(android.R.string.ok, new FireIntent(activity, intent)); b.setNegativeButton(android.R.string.cancel, null); b.show(); }
public static void collectAndSendLog(final Activity activity) { final PackageManager packageManager = activity.getPackageManager(); Intent intent = packageManager .getLaunchIntentForPackage(SENDLOG_PACKAGE_NAME); final String pkg = activity.getPackageName(); int title, message; if (intent == null) { intent = new Intent(Intent.ACTION_VIEW, Uri .parse("market://search?q=pname:" + SENDLOG_PACKAGE_NAME)); title = activity.getResources().getIdentifier("sendlog_install_", "string", pkg); message = activity.getResources().getIdentifier("sendlog_install", "string", pkg); } else { intent.putExtra("filter", TAG + ":D *:W"); intent.setType("0||[email protected]"); title = activity.getResources().getIdentifier("sendlog_run_", "string", pkg); message = activity.getResources().getIdentifier("sendlog_run", "string", pkg); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final AlertDialog.Builder b = new AlertDialog.Builder(activity); b.setIcon(android.R.drawable.ic_dialog_info); b.setTitle(title); b.setMessage(message); b.setPositiveButton(android.R.string.ok, new FireIntent(activity, intent)); b.setNegativeButton(android.R.string.cancel, null); b.show(); }
diff --git a/source/net/sourceforge/texlipse/actions/TexHardLineWrapAction.java b/source/net/sourceforge/texlipse/actions/TexHardLineWrapAction.java index 58ac931..644aaca 100644 --- a/source/net/sourceforge/texlipse/actions/TexHardLineWrapAction.java +++ b/source/net/sourceforge/texlipse/actions/TexHardLineWrapAction.java @@ -1,199 +1,203 @@ /* * $Id$ * * Copyright (c) 2004-2005 by the TeXlapse Team. * 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 net.sourceforge.texlipse.actions; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.editor.TexEditor; import net.sourceforge.texlipse.editor.TexEditorTools; import net.sourceforge.texlipse.properties.TexlipseProperties; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.ITextEditor; /** * This class handles the action based text wrapping. * @author Antti Pirinen */ public class TexHardLineWrapAction implements IEditorActionDelegate { private IEditorPart targetEditor; private int tabWidth = 2; private int lineLength = 80; private TexEditorTools tools; private static TexSelections selection; /** * From what editot the event will come. * @param action not used in this method, can also be </code>null</code> * @param targetEditor the editor that calls this class * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart) */ public void setActiveEditor(IAction action, IEditorPart targetEditor) { this.targetEditor = targetEditor; } /** * When the user presses <code>Esc, q</code> or selects from menu bar * <code>Wrap Lines</code> this method is invoked. * @param action an action that invokes * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { this.lineLength = TexlipsePlugin.getDefault().getPreferenceStore().getInt(TexlipseProperties.WORDWRAP_LENGTH); this.tabWidth = TexlipsePlugin.getDefault().getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); selection = new TexSelections(getTexEditor()); this.tools = new TexEditorTools(); try { doWrap(); } catch(BadLocationException e) { TexlipsePlugin.log("TexCorrectIndentationAction.run", e); } } /* (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IAction action, ISelection selection) { if (selection instanceof TextSelection) { action.setEnabled(true); return; } action.setEnabled( targetEditor instanceof ITextEditor); } /** * Returns the TexEditor. */ private TexEditor getTexEditor() { if (targetEditor instanceof TexEditor) { return (TexEditor) targetEditor; } else { throw new RuntimeException("Expecting text editor. Found:"+targetEditor.getClass().getName()); } } /** * This method does actual wrapping... * @throws BadLocationException */ private void doWrap() throws BadLocationException{ boolean itemFound = false; IDocument document = selection.getDocument(); //selection.selectCompleteLines(); selection.selectParagraph(); String delimiter = document.getLineDelimiter(selection.getStartLineIndex()); String[] lines = document.get(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength()).split(delimiter); if (lines.length == 0) return; int index = 0; StringBuffer buff = new StringBuffer(); boolean fix = true; String selectedLine = ""; String correctIndentation = ""; while (index < lines.length){ if (tools.isLineCommandLine(lines[index]) || tools.isLineCommentLine(lines[index]) || lines[index].trim().length() == 0) { buff.append(lines[index]); if (lines[index].trim().length() == 0 || isList(lines[index])) fix = true; index++; if (index < lines.length ) buff.append(delimiter); continue; } // a current line is NOT a comment, a command or an empty line -> continue if (fix){ correctIndentation = tools.getIndentation(lines[index],tabWidth); fix = false; } StringBuffer temp = new StringBuffer(); boolean end = false; while (index < lines.length && !end ){ if (!tools.isLineCommandLine(lines[index]) && !tools.isLineCommentLine(lines[index]) && lines[index].trim().length() > 0 ){ if (lines[index].trim().startsWith("\\item") && !itemFound) { end = true; itemFound = true; - }else { + } else { temp.append(lines[index].trim()+" "); itemFound = false; - index++; + //Respect \\ with a subsequent line break + if (lines[index].trim().endsWith("\\\\")) { + end = true; + } + index++; } } else { /* a current line is a command, a comment or en empty -> do not handle the line at this iteration. */ end = true; } } int wsLast = 0; selectedLine = temp.toString().trim(); while(selectedLine.length() > 0) { /* find the last white space before MAX */ wsLast = tools.getWhiteSpacePosition(selectedLine, (lineLength - correctIndentation.length()))+1; if (wsLast == 0 ){ /* there was no white space before MAX, try if there is one after */ wsLast = tools.getWhiteSpacePositionA(selectedLine, (lineLength - correctIndentation.length()))+1; } if (wsLast == 0 || wsLast > selectedLine.length() || selectedLine.length() < (lineLength - correctIndentation.length())){ //there was no white space character at the line wsLast = selectedLine.length(); } buff.append(correctIndentation); buff.append(selectedLine.substring(0,wsLast)); selectedLine = selectedLine.substring(wsLast); selectedLine = tools.trimBegin(selectedLine); if( index < lines.length || selectedLine.length() > 0 ) buff.append(delimiter); } } document.replace(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength(), buff.toString()); } /** * Checks if the command word is \begin{itemize} or \begin{enumerate} * @param txt string to test * @return <code>true</code> if txt contains \begin{itemize} or * \begin{enumerate}, <code>false</code> otherwise */ private boolean isList(String txt){ boolean rv = false; int bi = -1; if ((bi = txt.indexOf("\\begin")) != -1) { String end = tools.getEndLine(txt.substring(bi), "\\begin"); String env = tools.getEnvironment(end); if ( env.equals("itemize") || env.equals("enumerate")|| env.equals("description")) rv = true; } return rv; } }
false
true
private void doWrap() throws BadLocationException{ boolean itemFound = false; IDocument document = selection.getDocument(); //selection.selectCompleteLines(); selection.selectParagraph(); String delimiter = document.getLineDelimiter(selection.getStartLineIndex()); String[] lines = document.get(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength()).split(delimiter); if (lines.length == 0) return; int index = 0; StringBuffer buff = new StringBuffer(); boolean fix = true; String selectedLine = ""; String correctIndentation = ""; while (index < lines.length){ if (tools.isLineCommandLine(lines[index]) || tools.isLineCommentLine(lines[index]) || lines[index].trim().length() == 0) { buff.append(lines[index]); if (lines[index].trim().length() == 0 || isList(lines[index])) fix = true; index++; if (index < lines.length ) buff.append(delimiter); continue; } // a current line is NOT a comment, a command or an empty line -> continue if (fix){ correctIndentation = tools.getIndentation(lines[index],tabWidth); fix = false; } StringBuffer temp = new StringBuffer(); boolean end = false; while (index < lines.length && !end ){ if (!tools.isLineCommandLine(lines[index]) && !tools.isLineCommentLine(lines[index]) && lines[index].trim().length() > 0 ){ if (lines[index].trim().startsWith("\\item") && !itemFound) { end = true; itemFound = true; }else { temp.append(lines[index].trim()+" "); itemFound = false; index++; } } else { /* a current line is a command, a comment or en empty -> do not handle the line at this iteration. */ end = true; } } int wsLast = 0; selectedLine = temp.toString().trim(); while(selectedLine.length() > 0) { /* find the last white space before MAX */ wsLast = tools.getWhiteSpacePosition(selectedLine, (lineLength - correctIndentation.length()))+1; if (wsLast == 0 ){ /* there was no white space before MAX, try if there is one after */ wsLast = tools.getWhiteSpacePositionA(selectedLine, (lineLength - correctIndentation.length()))+1; } if (wsLast == 0 || wsLast > selectedLine.length() || selectedLine.length() < (lineLength - correctIndentation.length())){ //there was no white space character at the line wsLast = selectedLine.length(); } buff.append(correctIndentation); buff.append(selectedLine.substring(0,wsLast)); selectedLine = selectedLine.substring(wsLast); selectedLine = tools.trimBegin(selectedLine); if( index < lines.length || selectedLine.length() > 0 ) buff.append(delimiter); } } document.replace(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength(), buff.toString()); }
private void doWrap() throws BadLocationException{ boolean itemFound = false; IDocument document = selection.getDocument(); //selection.selectCompleteLines(); selection.selectParagraph(); String delimiter = document.getLineDelimiter(selection.getStartLineIndex()); String[] lines = document.get(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength()).split(delimiter); if (lines.length == 0) return; int index = 0; StringBuffer buff = new StringBuffer(); boolean fix = true; String selectedLine = ""; String correctIndentation = ""; while (index < lines.length){ if (tools.isLineCommandLine(lines[index]) || tools.isLineCommentLine(lines[index]) || lines[index].trim().length() == 0) { buff.append(lines[index]); if (lines[index].trim().length() == 0 || isList(lines[index])) fix = true; index++; if (index < lines.length ) buff.append(delimiter); continue; } // a current line is NOT a comment, a command or an empty line -> continue if (fix){ correctIndentation = tools.getIndentation(lines[index],tabWidth); fix = false; } StringBuffer temp = new StringBuffer(); boolean end = false; while (index < lines.length && !end ){ if (!tools.isLineCommandLine(lines[index]) && !tools.isLineCommentLine(lines[index]) && lines[index].trim().length() > 0 ){ if (lines[index].trim().startsWith("\\item") && !itemFound) { end = true; itemFound = true; } else { temp.append(lines[index].trim()+" "); itemFound = false; //Respect \\ with a subsequent line break if (lines[index].trim().endsWith("\\\\")) { end = true; } index++; } } else { /* a current line is a command, a comment or en empty -> do not handle the line at this iteration. */ end = true; } } int wsLast = 0; selectedLine = temp.toString().trim(); while(selectedLine.length() > 0) { /* find the last white space before MAX */ wsLast = tools.getWhiteSpacePosition(selectedLine, (lineLength - correctIndentation.length()))+1; if (wsLast == 0 ){ /* there was no white space before MAX, try if there is one after */ wsLast = tools.getWhiteSpacePositionA(selectedLine, (lineLength - correctIndentation.length()))+1; } if (wsLast == 0 || wsLast > selectedLine.length() || selectedLine.length() < (lineLength - correctIndentation.length())){ //there was no white space character at the line wsLast = selectedLine.length(); } buff.append(correctIndentation); buff.append(selectedLine.substring(0,wsLast)); selectedLine = selectedLine.substring(wsLast); selectedLine = tools.trimBegin(selectedLine); if( index < lines.length || selectedLine.length() > 0 ) buff.append(delimiter); } } document.replace(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength(), buff.toString()); }
diff --git a/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/gt2deegree/GtToDgConvertor.java b/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/gt2deegree/GtToDgConvertor.java index 1369a4e11..49623f6c6 100644 --- a/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/gt2deegree/GtToDgConvertor.java +++ b/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/gt2deegree/GtToDgConvertor.java @@ -1,521 +1,517 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2010. */ package eu.esdihumboldt.gmlhandler.gt2deegree; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.xml.namespace.QName; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.primitive.PrimitiveType; import org.deegree.cs.CRS; import org.deegree.feature.GenericFeatureCollection; import org.deegree.feature.property.GenericProperty; import org.deegree.feature.types.GenericFeatureType; import org.deegree.feature.types.property.SimplePropertyType; import org.deegree.feature.types.property.ValueRepresentation; import org.deegree.feature.types.property.GeometryPropertyType.CoordinateDimension; import org.deegree.feature.types.property.GeometryPropertyType.GeometryType; import org.deegree.geometry.Geometry; import org.deegree.geometry.points.Points; import org.deegree.geometry.primitive.Ring; import org.deegree.geometry.standard.multi.DefaultMultiPolygon; import org.deegree.geometry.standard.primitive.DefaultPolygon; import org.deegree.gml.GMLVersion; import org.geotools.feature.FeatureIterator; import org.geotools.geometry.jts.Geometries; import org.opengis.feature.Feature; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.type.FeatureType; import org.opengis.feature.type.GeometryDescriptor; import org.opengis.feature.type.Name; import org.opengis.feature.type.PropertyDescriptor; import org.opengis.feature.type.PropertyType; import org.opengis.referencing.crs.CoordinateReferenceSystem; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * * * This class contains methods to create Deegree3 Structures like Feature, * FeatureCollection and so using GeoSpatial data retrieved from the according * geotools Objects. * * @author Jan Jezek, Anna Pitaev * @version $Id$ * * * * */ public class GtToDgConvertor { /** * * @param geotools * -based Feature Collection fc * @return deegree-based Feature Collection */ public static org.deegree.feature.FeatureCollection convertGtToDg( org.geotools.feature.FeatureCollection fc) { Collection<org.deegree.feature.Feature> dgFeatures = new ArrayList(); org.deegree.feature.Feature dgFeature = null; List<org.deegree.feature.property.Property> dgProperties = null; List<org.deegree.feature.types.property.PropertyType> dgPropertyTypes = null; for (FeatureIterator i = fc.features(); i.hasNext();) { dgPropertyTypes = new ArrayList<org.deegree.feature.types.property.PropertyType>(); Feature gtFeature = i.next(); dgFeature = createDgFeature(gtFeature); dgFeatures.add(dgFeature); } org.deegree.feature.FeatureCollection dfFC = new GenericFeatureCollection( fc.getID(), dgFeatures); return dfFC; } /** * * @param geotools * -based Feature * @return deegree-based Feature * */ private static org.deegree.feature.Feature createDgFeature(Feature gtFeature) { System.out.println(gtFeature.getDefaultGeometryProperty().getType()); FeatureType gtFT = gtFeature.getType(); // convert gtFT to gtFT // 1. GenericFeatureType GenericFeatureType dgFT = createDgFt(gtFT); // 2. Feature id String fid = gtFeature.getIdentifier().getID(); // 3. List<Property> List<org.deegree.feature.property.Property> dgProps = new ArrayList<org.deegree.feature.property.Property>(); Iterator<Property> gtPropsIter = gtFeature.getProperties().iterator(); while (gtPropsIter.hasNext()) { Property gtProp = gtPropsIter.next(); org.deegree.feature.property.Property dgProp = createDgProp(gtProp); dgProps.add(dgProp); } // 4. GMLVersion org.deegree.feature.Feature dgFeature = dgFT.newFeature(fid, dgProps, GMLVersion.GML_32); return dgFeature; } /** * * @param geotools * -based Property * @return deegree-based Property * */ private static org.deegree.feature.property.Property createDgProp( Property gtProp) { // 1. declare a Property instance: make decision about implementing // class after analyze of the PropertyType org.deegree.feature.property.Property dgProp = null; // 2. define isNilled isNilled boolean isNilled = gtProp.isNillable(); // 3. define property name QName dgPropName = new QName(gtProp.getName().getNamespaceURI(), gtProp .getName().getLocalPart()); // create deegree based PropertyType from the geotools Objecy // if prop has xml atttribures map it to the CustomPropertyType boolean hasXMLAttrs = gtProp.getUserData().get("XmlAttributes") != null; org.deegree.feature.types.property.PropertyType dgPT = createDgPt( gtProp.getDescriptor(), hasXMLAttrs); if (dgPT instanceof org.deegree.feature.types.property.SimplePropertyType) { // A PropertyType that defines a property with a primitive value, // i.e. a value that can be represented as a single String. if (isNilled) { TypedObjectNode node = null; dgProp = new org.deegree.feature.property.GenericProperty(dgPT, dgPropName, null); } else { dgProp = new org.deegree.feature.property.SimpleProperty( (SimplePropertyType) dgPT, (String) gtProp.getValue(), ((SimplePropertyType) dgPT).getPrimitiveType()); } } else if (dgPT instanceof org.deegree.feature.types.property.GeometryPropertyType) { // TODO handle case with GeometryReference<Geometry> // convert gt Geometry attribute to deegree Geometry org.deegree.geometry.Geometry dgGeometry = createDgGeometry(gtProp); dgProp = new GenericProperty(dgPT, dgPropName, dgGeometry); } else if (dgPT instanceof org.deegree.feature.types.property.FeaturePropertyType) { // we support inline Features mapping only // if (gtProp instanceof SimpleFeature ){ // create deegree generic feature based on gtProp GenericFeatureType ft = createDgFt(((SimpleFeature) gtProp) .getFeatureType()); org.deegree.feature.Feature featureProp = createDgFeature((Feature) gtProp); /* * //TODO find a nicer way to create fid String fid = * java.util.UUID.randomUUID().toString(); GMLVersion version = * GMLVersion.GML_32; List<org.deegree.feature.property.Property> * properties = new * ArrayList<org.deegree.feature.property.Property>(); * org.deegree.feature.property.Property property; //create Property * from the gt Attributes List<Object> attrs = * ((SimpleFeature)gtProp).getAttributes(); for (Object attr : * attrs){ property = createProperty(attr); //TODOuse geotools * Feature Attribute Type //properties.add(property, * ((SimpleFeature)gtProp).getAttribute(attr.)); } GenericFeature * dgSubProperty = new GenericFeature(ft, fid, properties, version); */ dgProp = new GenericProperty(dgPT, dgPropName, featureProp); // } } else if (dgPT instanceof org.deegree.feature.types.property.CustomPropertyType) { // TODO implement if needed } else if (dgPT instanceof org.deegree.feature.types.property.CodePropertyType) { // TODO implement it if needed } else if (dgPT instanceof org.deegree.feature.types.property.EnvelopePropertyType) { // TODO clear how to retrieve envelope data } return dgProp; } /** * * <p> * This method provides mapping for the following geometries: * <ul> * <li>POINT</li> * <li>MULTIPOINT</li> * <li>POLIGON</li> * <li>MULTIPOLIGON</li> * <li>LINESTRING</li> * <li>MULTILINESTRING</li> * </ul> * * @param gtProp * GeometryAttribute * @return Geometry */ private static Geometry createDgGeometry(Property gtProp) { // TODO provide junit testcasefor this method --> high priority Geometry dgGeometry = null; String geometryName = gtProp.getDescriptor().getType().getBinding() .getSimpleName(); // we provide mapping for Geometries geomType = Geometries .getForBinding((Class<? extends com.vividsolutions.jts.geom.Geometry>) gtProp .getDescriptor().getType().getBinding()); // map common attributtes // 1. id // TODO test it String id = UUID.randomUUID().toString(); // 2.TODO figure out CRS // org.deegree.cs.CRS dgCRS = // createCRS(gtProp.getType().getCoordinateReferenceSystem()); org.deegree.cs.CRS dgCRS = null; // 3. precision model // TODO find a nicer way to define it org.deegree.geometry.precision.PrecisionModel pm = org.deegree.geometry.precision.PrecisionModel.DEFAULT_PRECISION_MODEL; switch (geomType) { case POLYGON: - Polygon gtPoligon = (Polygon) gtProp.getDescriptor().getType(); + Polygon gtPoligon = (Polygon) gtProp.getValue(); Ring exteriorRing = createRing(gtPoligon.getExteriorRing()); int numOfInterRings = gtPoligon.getNumInteriorRing(); List<Ring> interiorRings = new ArrayList<Ring>(numOfInterRings); Ring interiorRing = null; for (int i = 0; i < numOfInterRings; i++) { interiorRing = createRing(gtPoligon.getInteriorRingN(i)); interiorRings.add(interiorRing); } dgGeometry = new DefaultPolygon(id, dgCRS, pm, exteriorRing, interiorRings); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtPoligon); break; case MULTIPOLYGON: - MultiPolygon gtMultiPolygon = (MultiPolygon) gtProp.getDescriptor() - .getType(); + MultiPolygon gtMultiPolygon = (MultiPolygon) gtProp.getValue(); int numOfPolygs = gtMultiPolygon.getNumGeometries(); List<org.deegree.geometry.primitive.Polygon> dgPolygons = new ArrayList<org.deegree.geometry.primitive.Polygon>( numOfPolygs); org.deegree.geometry.primitive.Polygon dgPolygon; for (int i = 0; i < numOfPolygs; i++) { dgPolygon = createDefaultPolygon((Polygon) gtMultiPolygon .getGeometryN(i)); dgPolygons.add(dgPolygon); } dgGeometry = new DefaultMultiPolygon(id, dgCRS, pm, dgPolygons); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiPolygon); break; case LINESTRING: - LineString gtLineString = (LineString) gtProp.getDescriptor() - .getType(); + LineString gtLineString = (LineString) gtProp.getValue(); Points dgLineStringPoints = createDGPoints(gtLineString .getCoordinates()); dgGeometry = new org.deegree.geometry.standard.primitive.DefaultLineString( id, dgCRS, pm, dgLineStringPoints); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtLineString); break; case MULTILINESTRING: - MultiLineString gtMultiLineString = (MultiLineString) gtProp - .getDescriptor().getType(); + MultiLineString gtMultiLineString = (MultiLineString) gtProp.getValue(); int numOfLineStrings = gtMultiLineString.getNumGeometries(); List<org.deegree.geometry.primitive.LineString> dgLineStrings = new ArrayList<org.deegree.geometry.primitive.LineString>( numOfLineStrings); org.deegree.geometry.primitive.LineString dgLineString; for (int i = 0; i < numOfLineStrings; i++) { dgLineString = createLineString(gtMultiLineString .getGeometryN(i)); dgLineStrings.add(dgLineString); } dgGeometry = new org.deegree.geometry.standard.multi.DefaultMultiLineString( id, dgCRS, pm, dgLineStrings); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiLineString); break; case POINT: Point gtPoint = (Point) (gtProp.getValue()); double[] dgCoordinates = createCoordinates(gtPoint.getCoordinates()); dgGeometry = new org.deegree.geometry.standard.primitive.DefaultPoint( id, dgCRS, pm, dgCoordinates); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtPoint); break; case MULTIPOINT: - MultiPoint gtMultiPoint = (MultiPoint) gtProp.getDescriptor() - .getType(); + MultiPoint gtMultiPoint = (MultiPoint) gtProp.getValue(); int numOfPoints = gtMultiPoint.getNumGeometries(); List<org.deegree.geometry.primitive.Point> dgPoints = new ArrayList<org.deegree.geometry.primitive.Point>( numOfPoints); org.deegree.geometry.primitive.Point dgPoint; for (int i = 0; i < numOfPoints; i++) { dgPoint = createPoint(gtMultiPoint.getGeometryN(i)); dgPoints.add(dgPoint); } dgGeometry = new org.deegree.geometry.standard.multi.DefaultMultiPoint( id, dgCRS, pm, dgPoints); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiPoint); break; default: break; } return dgGeometry; } private static org.deegree.geometry.primitive.Point createPoint( com.vividsolutions.jts.geom.Geometry geometryN) { // TODO Auto-generated method stub return null; } private static double[] createCoordinates(Coordinate[] coordinates) { // TODO Auto-generated method stub return null; } private static org.deegree.geometry.primitive.LineString createLineString( com.vividsolutions.jts.geom.Geometry geometryN) { // TODO Auto-generated method stub return null; } private static Points createDGPoints(Coordinate[] coordinates) { // TODO Auto-generated method stub return null; } private static org.deegree.geometry.primitive.Polygon createDefaultPolygon( Polygon geometryN) { // TODO Auto-generated method stub return null; } private static Ring createRing(LineString exteriorRing) { // TODO Auto-generated method stub return null; } private static CRS createCRS( CoordinateReferenceSystem coordinateReferenceSystem) { // TODO Auto-generated method stub return null; } /** * * @param hasXMLAttrs * @param geotools * -based propertyType * @return deegree-based PropertyType */ private static org.deegree.feature.types.property.PropertyType createDgPt( PropertyDescriptor gtPD, boolean hasXMLAttrs) { org.deegree.feature.types.property.PropertyType dgPT = null; // TODO define a better way for the value representation List<org.deegree.feature.types.property.PropertyType> substitutions = new ArrayList<org.deegree.feature.types.property.PropertyType>(); PropertyType gtPT = gtPD.getType(); Property prop = null; String namespace = gtPD.getName().getNamespaceURI(); // define commons attributes QName dgName = new QName(gtPD.getName().getNamespaceURI(), gtPT .getName().getLocalPart()); QName dgFTName = new QName(gtPT.getName().getNamespaceURI(), gtPT .getName().getLocalPart()); int minOccurs = gtPD.getMinOccurs(); int maxOccurs = gtPD.getMaxOccurs(); boolean isAbstract = gtPT.isAbstract(); if (gtPT instanceof org.opengis.feature.type.GeometryType) { org.deegree.feature.types.property.GeometryPropertyType.GeometryType dgGeomType = createGeometryType((GeometryDescriptor) gtPD); org.deegree.feature.types.property.GeometryPropertyType.CoordinateDimension dgCoordDim = createCoordDim((GeometryDescriptor) gtPD); dgPT = new org.deegree.feature.types.property.GeometryPropertyType( dgName, minOccurs, maxOccurs, dgGeomType, dgCoordDim, isAbstract, substitutions, ValueRepresentation.BOTH); } else if (gtPT instanceof org.opengis.feature.type.AttributeType && !(gtPT instanceof org.opengis.feature.type.ComplexType)) { // TODO find a nicer way to define this binding PrimitiveType propPrimType = PrimitiveType .determinePrimitiveType(gtPT.getBinding().getName()); dgPT = new org.deegree.feature.types.property.SimplePropertyType( dgName, minOccurs, maxOccurs, propPrimType, isAbstract, substitutions); } else { if (hasXMLAttrs) { // create CustomPropertyType to handle xml attrs // TODO XSTypeDefinition we need // org.apache.xerces.xs.XSElementDeclaration xs = null; // this.appSchema.getXSModel().getAbstractCurveSegmentElementDeclaration().getEnclosingCTDefinition(). // List<org.apache.xerces.xs.XSElementDeclaration> xsDecl = // this.appSchema.getXSModel(). // 2. Qname // 3. namespace - only element declarations in this namespace // are returned, set to null for all namespaces // 4. transitive - if true, also substitutions for substitutions // (and so one) are included // 5. onlyConcrete - if true, only concrete (non-abstract) // declarations are returned // dgPT = new // org.deegree.feature.types.property.CustomPropertyType(dgFTName, // maxOccurs, maxOccurs, null, isAbstract, substitutions); } else { // create Feature Property Type dgPT = new org.deegree.feature.types.property.FeaturePropertyType( dgName, minOccurs, maxOccurs, dgFTName, isAbstract, substitutions, ValueRepresentation.BOTH); } } return dgPT; } /** * * @param geotools * Geometry Descriptor * @return CoordinateDimension */ private static CoordinateDimension createCoordDim( GeometryDescriptor descriptor) { if (descriptor.getCoordinateReferenceSystem() != null && descriptor.getCoordinateReferenceSystem() .getCoordinateSystem() != null) { if (descriptor.getCoordinateReferenceSystem().getCoordinateSystem() .getDimension() == 2) return CoordinateDimension.DIM_2; if (descriptor.getCoordinateReferenceSystem().getCoordinateSystem() .getDimension() == 3) return CoordinateDimension.DIM_3; } return CoordinateDimension.DIM_2_OR_3; } /** * * @param geotools * Geometry Descriptor * @return Geometry Type */ private static GeometryType createGeometryType(GeometryDescriptor descriptor) { // 1. retrieve the Geometry type name String geometry = descriptor.getType().getBinding().getSimpleName(); // 2. assign a string value to the GeometryType return GeometryType.fromString(geometry); } /** * * @param geotools * -based FeatureType * @return deegree-based FeatureType * */ private static org.deegree.feature.types.GenericFeatureType createDgFt( FeatureType gtFT) { // 1.0 QName Name gtFTName = gtFT.getName(); QName ftName = new QName(gtFTName.getNamespaceURI(), gtFTName.getLocalPart()); List<org.deegree.feature.types.property.PropertyType> propDecls = new ArrayList<org.deegree.feature.types.property.PropertyType>(); // 1.1 List<PropertyType> for (PropertyDescriptor gtPD : gtFT.getDescriptors()) { // create deegree PropertyType org.deegree.feature.types.property.PropertyType dgPT = createDgPt( gtPD, false); propDecls.add(dgPT); } // 1.2 boolean isAbstract boolean isAbstract = gtFT.isAbstract(); org.deegree.feature.types.GenericFeatureType dgFT = new org.deegree.feature.types.GenericFeatureType( ftName, propDecls, isAbstract); return dgFT; } }
false
true
private static Geometry createDgGeometry(Property gtProp) { // TODO provide junit testcasefor this method --> high priority Geometry dgGeometry = null; String geometryName = gtProp.getDescriptor().getType().getBinding() .getSimpleName(); // we provide mapping for Geometries geomType = Geometries .getForBinding((Class<? extends com.vividsolutions.jts.geom.Geometry>) gtProp .getDescriptor().getType().getBinding()); // map common attributtes // 1. id // TODO test it String id = UUID.randomUUID().toString(); // 2.TODO figure out CRS // org.deegree.cs.CRS dgCRS = // createCRS(gtProp.getType().getCoordinateReferenceSystem()); org.deegree.cs.CRS dgCRS = null; // 3. precision model // TODO find a nicer way to define it org.deegree.geometry.precision.PrecisionModel pm = org.deegree.geometry.precision.PrecisionModel.DEFAULT_PRECISION_MODEL; switch (geomType) { case POLYGON: Polygon gtPoligon = (Polygon) gtProp.getDescriptor().getType(); Ring exteriorRing = createRing(gtPoligon.getExteriorRing()); int numOfInterRings = gtPoligon.getNumInteriorRing(); List<Ring> interiorRings = new ArrayList<Ring>(numOfInterRings); Ring interiorRing = null; for (int i = 0; i < numOfInterRings; i++) { interiorRing = createRing(gtPoligon.getInteriorRingN(i)); interiorRings.add(interiorRing); } dgGeometry = new DefaultPolygon(id, dgCRS, pm, exteriorRing, interiorRings); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtPoligon); break; case MULTIPOLYGON: MultiPolygon gtMultiPolygon = (MultiPolygon) gtProp.getDescriptor() .getType(); int numOfPolygs = gtMultiPolygon.getNumGeometries(); List<org.deegree.geometry.primitive.Polygon> dgPolygons = new ArrayList<org.deegree.geometry.primitive.Polygon>( numOfPolygs); org.deegree.geometry.primitive.Polygon dgPolygon; for (int i = 0; i < numOfPolygs; i++) { dgPolygon = createDefaultPolygon((Polygon) gtMultiPolygon .getGeometryN(i)); dgPolygons.add(dgPolygon); } dgGeometry = new DefaultMultiPolygon(id, dgCRS, pm, dgPolygons); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiPolygon); break; case LINESTRING: LineString gtLineString = (LineString) gtProp.getDescriptor() .getType(); Points dgLineStringPoints = createDGPoints(gtLineString .getCoordinates()); dgGeometry = new org.deegree.geometry.standard.primitive.DefaultLineString( id, dgCRS, pm, dgLineStringPoints); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtLineString); break; case MULTILINESTRING: MultiLineString gtMultiLineString = (MultiLineString) gtProp .getDescriptor().getType(); int numOfLineStrings = gtMultiLineString.getNumGeometries(); List<org.deegree.geometry.primitive.LineString> dgLineStrings = new ArrayList<org.deegree.geometry.primitive.LineString>( numOfLineStrings); org.deegree.geometry.primitive.LineString dgLineString; for (int i = 0; i < numOfLineStrings; i++) { dgLineString = createLineString(gtMultiLineString .getGeometryN(i)); dgLineStrings.add(dgLineString); } dgGeometry = new org.deegree.geometry.standard.multi.DefaultMultiLineString( id, dgCRS, pm, dgLineStrings); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiLineString); break; case POINT: Point gtPoint = (Point) (gtProp.getValue()); double[] dgCoordinates = createCoordinates(gtPoint.getCoordinates()); dgGeometry = new org.deegree.geometry.standard.primitive.DefaultPoint( id, dgCRS, pm, dgCoordinates); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtPoint); break; case MULTIPOINT: MultiPoint gtMultiPoint = (MultiPoint) gtProp.getDescriptor() .getType(); int numOfPoints = gtMultiPoint.getNumGeometries(); List<org.deegree.geometry.primitive.Point> dgPoints = new ArrayList<org.deegree.geometry.primitive.Point>( numOfPoints); org.deegree.geometry.primitive.Point dgPoint; for (int i = 0; i < numOfPoints; i++) { dgPoint = createPoint(gtMultiPoint.getGeometryN(i)); dgPoints.add(dgPoint); } dgGeometry = new org.deegree.geometry.standard.multi.DefaultMultiPoint( id, dgCRS, pm, dgPoints); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiPoint); break; default: break; } return dgGeometry; }
private static Geometry createDgGeometry(Property gtProp) { // TODO provide junit testcasefor this method --> high priority Geometry dgGeometry = null; String geometryName = gtProp.getDescriptor().getType().getBinding() .getSimpleName(); // we provide mapping for Geometries geomType = Geometries .getForBinding((Class<? extends com.vividsolutions.jts.geom.Geometry>) gtProp .getDescriptor().getType().getBinding()); // map common attributtes // 1. id // TODO test it String id = UUID.randomUUID().toString(); // 2.TODO figure out CRS // org.deegree.cs.CRS dgCRS = // createCRS(gtProp.getType().getCoordinateReferenceSystem()); org.deegree.cs.CRS dgCRS = null; // 3. precision model // TODO find a nicer way to define it org.deegree.geometry.precision.PrecisionModel pm = org.deegree.geometry.precision.PrecisionModel.DEFAULT_PRECISION_MODEL; switch (geomType) { case POLYGON: Polygon gtPoligon = (Polygon) gtProp.getValue(); Ring exteriorRing = createRing(gtPoligon.getExteriorRing()); int numOfInterRings = gtPoligon.getNumInteriorRing(); List<Ring> interiorRings = new ArrayList<Ring>(numOfInterRings); Ring interiorRing = null; for (int i = 0; i < numOfInterRings; i++) { interiorRing = createRing(gtPoligon.getInteriorRingN(i)); interiorRings.add(interiorRing); } dgGeometry = new DefaultPolygon(id, dgCRS, pm, exteriorRing, interiorRings); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtPoligon); break; case MULTIPOLYGON: MultiPolygon gtMultiPolygon = (MultiPolygon) gtProp.getValue(); int numOfPolygs = gtMultiPolygon.getNumGeometries(); List<org.deegree.geometry.primitive.Polygon> dgPolygons = new ArrayList<org.deegree.geometry.primitive.Polygon>( numOfPolygs); org.deegree.geometry.primitive.Polygon dgPolygon; for (int i = 0; i < numOfPolygs; i++) { dgPolygon = createDefaultPolygon((Polygon) gtMultiPolygon .getGeometryN(i)); dgPolygons.add(dgPolygon); } dgGeometry = new DefaultMultiPolygon(id, dgCRS, pm, dgPolygons); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiPolygon); break; case LINESTRING: LineString gtLineString = (LineString) gtProp.getValue(); Points dgLineStringPoints = createDGPoints(gtLineString .getCoordinates()); dgGeometry = new org.deegree.geometry.standard.primitive.DefaultLineString( id, dgCRS, pm, dgLineStringPoints); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtLineString); break; case MULTILINESTRING: MultiLineString gtMultiLineString = (MultiLineString) gtProp.getValue(); int numOfLineStrings = gtMultiLineString.getNumGeometries(); List<org.deegree.geometry.primitive.LineString> dgLineStrings = new ArrayList<org.deegree.geometry.primitive.LineString>( numOfLineStrings); org.deegree.geometry.primitive.LineString dgLineString; for (int i = 0; i < numOfLineStrings; i++) { dgLineString = createLineString(gtMultiLineString .getGeometryN(i)); dgLineStrings.add(dgLineString); } dgGeometry = new org.deegree.geometry.standard.multi.DefaultMultiLineString( id, dgCRS, pm, dgLineStrings); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiLineString); break; case POINT: Point gtPoint = (Point) (gtProp.getValue()); double[] dgCoordinates = createCoordinates(gtPoint.getCoordinates()); dgGeometry = new org.deegree.geometry.standard.primitive.DefaultPoint( id, dgCRS, pm, dgCoordinates); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtPoint); break; case MULTIPOINT: MultiPoint gtMultiPoint = (MultiPoint) gtProp.getValue(); int numOfPoints = gtMultiPoint.getNumGeometries(); List<org.deegree.geometry.primitive.Point> dgPoints = new ArrayList<org.deegree.geometry.primitive.Point>( numOfPoints); org.deegree.geometry.primitive.Point dgPoint; for (int i = 0; i < numOfPoints; i++) { dgPoint = createPoint(gtMultiPoint.getGeometryN(i)); dgPoints.add(dgPoint); } dgGeometry = new org.deegree.geometry.standard.multi.DefaultMultiPoint( id, dgCRS, pm, dgPoints); dgGeometry = ((org.deegree.geometry.standard.AbstractDefaultGeometry) dgGeometry) .createFromJTS(gtMultiPoint); break; default: break; } return dgGeometry; }
diff --git a/src/edu/ucla/cens/andwellness/mobile/plugin/LocationTriggerPlugin.java b/src/edu/ucla/cens/andwellness/mobile/plugin/LocationTriggerPlugin.java index 6e07885..23db2d4 100644 --- a/src/edu/ucla/cens/andwellness/mobile/plugin/LocationTriggerPlugin.java +++ b/src/edu/ucla/cens/andwellness/mobile/plugin/LocationTriggerPlugin.java @@ -1,96 +1,96 @@ /** * */ package edu.ucla.cens.andwellness.mobile.plugin; import java.io.FileOutputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; import com.phonegap.api.PluginResult.Status; import edu.ucla.cens.andwellness.triggers.types.location.LocTrigDesc; /** * @author mistralay * */ public class LocationTriggerPlugin extends Plugin { /* (non-Javadoc) * @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String) */ @Override public PluginResult execute(String action, JSONArray data, String callbackId) { PluginResult result = null; if (action.equals("set")) { JSONObject dataObject; try { dataObject = data.getJSONObject(0); // String category = dataObject.getString("category"); // String label = dataObject.getString("label"); // String surveyId = dataObject.getString("survey_id"); // long latitude = dataObject.getLong("latitude"); // long longitude = dataObject.getLong("longitude"); // JSONArray repeatArray = dataObject.getJSONArray("repeat"); - FileOutputStream out = new FileOutputStream("/sdcard/location_temp.jpg"); +// FileOutputStream out = new FileOutputStream("/sdcard/location_temp.jpg"); // LocTrigDesc trigDesc = new LocTrigDesc(); // trigDesc.setRangeEnabled(false); // trigDesc.setTriggerAlways(false); // trigDesc.setLocation(label); // trigDesc.setMinReentryInterval(120); JSONObject apiResult = new JSONObject(); apiResult.put("result", "success"); result = new PluginResult(Status.OK, apiResult); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (action.equals("getAll")) { JSONObject apiResult = new JSONObject(); try { apiResult.put("result", "success"); JSONArray repeatArray = new JSONArray(); repeatArray.put("M"); repeatArray.put("T"); repeatArray.put("W"); JSONObject object1 = new JSONObject(); object1.put("category", "home"); object1.put("label", "palash1"); object1.put("latitude", 123.123); object1.put("longitude", 123.123); object1.put("survey_id", "exerciseAndActivity"); object1.put("repeat", repeatArray); JSONArray triggerArray = new JSONArray(); triggerArray.put(object1); apiResult.put("triggers", triggerArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } result = new PluginResult(Status.OK, apiResult); } return result; } }
true
true
public PluginResult execute(String action, JSONArray data, String callbackId) { PluginResult result = null; if (action.equals("set")) { JSONObject dataObject; try { dataObject = data.getJSONObject(0); // String category = dataObject.getString("category"); // String label = dataObject.getString("label"); // String surveyId = dataObject.getString("survey_id"); // long latitude = dataObject.getLong("latitude"); // long longitude = dataObject.getLong("longitude"); // JSONArray repeatArray = dataObject.getJSONArray("repeat"); FileOutputStream out = new FileOutputStream("/sdcard/location_temp.jpg"); // LocTrigDesc trigDesc = new LocTrigDesc(); // trigDesc.setRangeEnabled(false); // trigDesc.setTriggerAlways(false); // trigDesc.setLocation(label); // trigDesc.setMinReentryInterval(120); JSONObject apiResult = new JSONObject(); apiResult.put("result", "success"); result = new PluginResult(Status.OK, apiResult); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (action.equals("getAll")) { JSONObject apiResult = new JSONObject(); try { apiResult.put("result", "success"); JSONArray repeatArray = new JSONArray(); repeatArray.put("M"); repeatArray.put("T"); repeatArray.put("W"); JSONObject object1 = new JSONObject(); object1.put("category", "home"); object1.put("label", "palash1"); object1.put("latitude", 123.123); object1.put("longitude", 123.123); object1.put("survey_id", "exerciseAndActivity"); object1.put("repeat", repeatArray); JSONArray triggerArray = new JSONArray(); triggerArray.put(object1); apiResult.put("triggers", triggerArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } result = new PluginResult(Status.OK, apiResult); } return result; }
public PluginResult execute(String action, JSONArray data, String callbackId) { PluginResult result = null; if (action.equals("set")) { JSONObject dataObject; try { dataObject = data.getJSONObject(0); // String category = dataObject.getString("category"); // String label = dataObject.getString("label"); // String surveyId = dataObject.getString("survey_id"); // long latitude = dataObject.getLong("latitude"); // long longitude = dataObject.getLong("longitude"); // JSONArray repeatArray = dataObject.getJSONArray("repeat"); // FileOutputStream out = new FileOutputStream("/sdcard/location_temp.jpg"); // LocTrigDesc trigDesc = new LocTrigDesc(); // trigDesc.setRangeEnabled(false); // trigDesc.setTriggerAlways(false); // trigDesc.setLocation(label); // trigDesc.setMinReentryInterval(120); JSONObject apiResult = new JSONObject(); apiResult.put("result", "success"); result = new PluginResult(Status.OK, apiResult); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (action.equals("getAll")) { JSONObject apiResult = new JSONObject(); try { apiResult.put("result", "success"); JSONArray repeatArray = new JSONArray(); repeatArray.put("M"); repeatArray.put("T"); repeatArray.put("W"); JSONObject object1 = new JSONObject(); object1.put("category", "home"); object1.put("label", "palash1"); object1.put("latitude", 123.123); object1.put("longitude", 123.123); object1.put("survey_id", "exerciseAndActivity"); object1.put("repeat", repeatArray); JSONArray triggerArray = new JSONArray(); triggerArray.put(object1); apiResult.put("triggers", triggerArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } result = new PluginResult(Status.OK, apiResult); } return result; }
diff --git a/src/main/java/hex/Summary.java b/src/main/java/hex/Summary.java index c2e51a88e..04b609bbc 100644 --- a/src/main/java/hex/Summary.java +++ b/src/main/java/hex/Summary.java @@ -1,315 +1,315 @@ package hex; import java.util.Arrays; import water.*; import water.ValueArray.Column; import water.util.Utils; import com.google.common.base.Objects; import com.google.gson.*; public class Summary extends Iced { public static final int MAX_HIST_SZ = water.parser.Enum.MAX_ENUM_SIZE; public final static class ColSummary extends Iced { public transient Summary _summary; public final int _colId; final int NMAX = 5; public static final double [] DEFAULT_PERCENTILES = {0.01,0.05,0.10,0.25,0.33,0.50,0.66,0.75,0.90,0.95,0.99}; final long [] _bins; // bins for histogram long _n; long _nzero; long _n_na; final double _start, _end, _binsz, _binszInv; double [] _min; // min N elements double [] _max; // max N elements private double [] _percentileValues; final double [] _percentiles; final boolean _enum; ColSummary(Summary s, int colId) { this(s,colId,null); } ColSummary(Summary s, int colId, double [] percentiles) { _summary = s; _colId = colId; Column c = s.ary()._cols[colId]; _enum = c.isEnum(); if(c._min == c._max){ // constant columns pecial case, not really any meaningfull data here, just don't blow up _start = c._min; _binsz = _binszInv = 1; _end = _start+1; _percentiles = null; _bins = new long[1]; _min = new double[]{c._min}; _max = new double[]{c._max}; } else { if(_enum){ _percentiles = null; _binsz = _binszInv = 1; _bins = MemoryManager.malloc8((int)c.numDomainSize()); _start = 0; _end = _bins.length; _min = _max = null; } else { final long n = Math.max(c._n,1); _min = MemoryManager.malloc8d(NMAX); _max = MemoryManager.malloc8d(NMAX); Arrays.fill(_min, Double.POSITIVE_INFINITY); Arrays.fill(_max, Double.NEGATIVE_INFINITY); if(c.isFloat() || c.numDomainSize() > MAX_HIST_SZ){ double start, binsz; int nbin; double a = (c._max - c._min) / n; double b = Math.pow(10, Math.floor(Math.log10(a))); // selects among d, 5*d, and 10*d so that the number of // partitions go in [start, end] is closest to n if (a > 20*b/3) b *= 10; else if (a > 5*b/3) b *= 5; start = b * Math.floor(c._min / b); if(Double.isNaN(start)) System.out.println("haha"); // guard against improper parse (date type) or zero c._sigma binsz = Math.max(1e-4, 3.5 * c._sigma/ Math.cbrt(c._n)); // Pick smaller of two for number of bins to avoid blowup of longs nbin = Math.max(Math.min(MAX_HIST_SZ,(int)((c._max - c._min) / binsz)),1); _bins = new long[nbin]; _start = start; _binsz = binsz; _binszInv = 1.0/binsz; _end = start + nbin * binsz; _percentiles = Objects.firstNonNull(percentiles, DEFAULT_PERCENTILES); } else { _start = c._min; _end = c._max; int sz = (int)c.numDomainSize(); _bins = new long[sz]; _binszInv = _binsz = 1.0; _percentiles = Objects.firstNonNull(percentiles, DEFAULT_PERCENTILES); } } } assert !Double.isNaN(_start):"_start is NaN!"; } public final double [] percentiles(){return _percentiles;} public long getEnumCardinality(){ if (_enum) return _bins.length; else throw new IllegalArgumentException("summary: non enums don't have enum cardinality"); } private void computePercentiles(){ _percentileValues = new double [_percentiles.length]; if( _bins.length == 0 ) return; int k = 0; long s = 0; for(int j = 0; j < _percentiles.length; ++j){ final double s1 = _percentiles[j]*_n; long bc = 0; while(s1 > s+(bc = binCount(k))){ s += bc; k++; } _percentileValues[j] = _min[0] + k*_binsz + ((_binsz > 1)?0.5*_binsz:0); } } public double percentileValue(double threshold){ if(_percentiles == null) throw new Error("Percentiles not available for enums!"); int idx = Arrays.binarySearch(_percentiles, threshold); if(idx < 0) throw new Error("don't have requested percentile"); if(_percentileValues == null)computePercentiles(); return _percentileValues[idx]; } void add(ColSummary other) { assert _bins.length == other._bins.length; assert Math.abs(_start - other._start) < 0.000001:"start - other._start = " + (_start - other._start); assert Math.abs(_binszInv - other._binszInv) < 0.000000001; _n += other._n; _nzero += other._nzero; _n_na += other._n_na; for (int i = 0; i < _bins.length; i++) _bins[i] += other._bins[i]; if(_min != null){ int j = 0, k = 0; double [] min = _min.clone(); double [] max = _max.clone(); for(int i = 0; i < _min.length; ++i){ if(other._min[k] < _min[j]){ min[i] = other._min[k++]; } else if(_min[j] < other._min[k]){ ++j; } else { ++j; ++k; } } j = k = 0; for(int i = 0; i < _max.length; ++i){ if(other._max[k] > _max[j]){ max[i] = other._max[k++]; } else if (_max[j] > other._max[k]){ ++j; } else { ++j;++k; } } _min = min; _max = max; } } void add(double val) { if(!_enum){ if (val == 0.) _nzero++; // first update min/max if(val < _min[_min.length-1]){ int j = _min.length-1; while(j > 0 && _min[j-1] > val)--j; if(j == 0 || _min[j-1] < val){ // skip dups for(int k = _min.length-1; k > j; --k) _min[k] = _min[k-1]; _min[j] = val; } } if(val > _max[_min.length-1]){ int j = _max.length-1; while(j > 0 && _max[j-1] < val)--j; if(j == 0 || _max[j-1] > val){ // skip dups for(int k = _max.length-1; k > j; --k) _max[k] = _max[k-1]; _max[j] = val; } } } // update the histogram int binIdx = (_binsz == 1) ?Math.min((int)(val-_start),_bins.length-1) :Math.min(_bins.length-1,(int)((val - _start) * _binszInv)); ++_bins[binIdx]; ++_n; } public double binValue(int b){ if(_binsz != 1) return _start + Math.max(0,(b-1))*_binsz + _binsz*0.5; else return _start + b; } public long binCount(int b){return _bins[b];} public double binPercent(int b){return 100*(double)_bins[b]/_n;} public String toString(){ StringBuilder res = new StringBuilder("ColumnSummary[" + _start + ":" + _end +", binsz=" + _binsz+"]"); if(_percentiles != null) { for(double d:_percentiles) res.append(", p("+(int)(100*d)+"%)=" + percentileValue(d)); } return res.toString(); } public JsonObject toJson(){ JsonObject res = new JsonObject(); res.addProperty("type", _enum?"enum":"number"); res.addProperty("name", _summary._ary._cols[_colId]._name); if (_enum) res.addProperty("enumCardinality", getEnumCardinality()); if(!_enum){ JsonArray min = new JsonArray(); for(double d:_min){ if(Double.isInfinite(d))break; min.add(new JsonPrimitive(d)); } res.add("min", min); JsonArray max = new JsonArray(); for(double d:_max){ if(Double.isInfinite(d))break; max.add(new JsonPrimitive(d)); } res.add("max", max); res.addProperty("mean", _summary._ary._cols[_colId]._mean); res.addProperty("sigma", _summary._ary._cols[_colId]._sigma); - res.addProperty("zeros", _summary._sums[ _colId ]._nzero); + res.addProperty("zeros", _nzero); } res.addProperty("N", _n); res.addProperty("na", _n_na); JsonObject histo = new JsonObject(); histo.addProperty("bin_size", _binsz); histo.addProperty("nbins", _bins.length); JsonArray ary = new JsonArray(); JsonArray binNames = new JsonArray(); if(_summary._ary._cols[_colId].isEnum()){ for(int i = 0; i < _summary._ary._cols[_colId]._domain.length; ++i){ if(_bins[i] != 0){ ary.add(new JsonPrimitive(_bins[i])); binNames.add(new JsonPrimitive(_summary._ary._cols[_colId]._domain[i])); } } } else { double x = _min[0]; if(_binsz != 1)x += _binsz*0.5; for(int i = 0; i < _bins.length; ++i){ if(_bins[i] != 0){ ary.add(new JsonPrimitive(_bins[i])); binNames.add(new JsonPrimitive(Utils.p2d(x + i*_binsz))); } } } histo.add("bin_names", binNames); histo.add("bins", ary); res.add("histogram", histo); if(!_enum && _percentiles != null){ if(_percentileValues == null)computePercentiles(); JsonObject percentiles = new JsonObject(); JsonArray thresholds = new JsonArray(); JsonArray values = new JsonArray(); for(int i = 0; i < _percentiles.length; ++i){ thresholds.add(new JsonPrimitive(_percentiles[i])); values.add(new JsonPrimitive(_percentileValues[i])); } percentiles.add("thresholds", thresholds); percentiles.add("values", values); res.add("percentiles", percentiles); } return res; } } private final ValueArray _ary; public ValueArray ary(){ return _ary; } ColSummary [] _sums; int [] _cols; public Summary(ValueArray ary, int [] cols){ assert ary != null; _ary = ary; _sums = new ColSummary [cols.length]; _cols = cols; for(int i = 0; i < cols.length; ++i) _sums[i] = new ColSummary(this, cols[i]); } public Summary add(Summary other){ for(int i = 0; i < _sums.length; ++i) _sums[i].add(other._sums[i]); return this; } public JsonObject toJson(){ JsonObject res = new JsonObject(); JsonArray sums = new JsonArray(); for(int i = 0; i < _sums.length; ++i){ _sums[i]._summary = this; sums.add(_sums[i].toJson()); } res.add("columns",sums); return res; } }
true
true
public JsonObject toJson(){ JsonObject res = new JsonObject(); res.addProperty("type", _enum?"enum":"number"); res.addProperty("name", _summary._ary._cols[_colId]._name); if (_enum) res.addProperty("enumCardinality", getEnumCardinality()); if(!_enum){ JsonArray min = new JsonArray(); for(double d:_min){ if(Double.isInfinite(d))break; min.add(new JsonPrimitive(d)); } res.add("min", min); JsonArray max = new JsonArray(); for(double d:_max){ if(Double.isInfinite(d))break; max.add(new JsonPrimitive(d)); } res.add("max", max); res.addProperty("mean", _summary._ary._cols[_colId]._mean); res.addProperty("sigma", _summary._ary._cols[_colId]._sigma); res.addProperty("zeros", _summary._sums[ _colId ]._nzero); } res.addProperty("N", _n); res.addProperty("na", _n_na); JsonObject histo = new JsonObject(); histo.addProperty("bin_size", _binsz); histo.addProperty("nbins", _bins.length); JsonArray ary = new JsonArray(); JsonArray binNames = new JsonArray(); if(_summary._ary._cols[_colId].isEnum()){ for(int i = 0; i < _summary._ary._cols[_colId]._domain.length; ++i){ if(_bins[i] != 0){ ary.add(new JsonPrimitive(_bins[i])); binNames.add(new JsonPrimitive(_summary._ary._cols[_colId]._domain[i])); } } } else { double x = _min[0]; if(_binsz != 1)x += _binsz*0.5; for(int i = 0; i < _bins.length; ++i){ if(_bins[i] != 0){ ary.add(new JsonPrimitive(_bins[i])); binNames.add(new JsonPrimitive(Utils.p2d(x + i*_binsz))); } } } histo.add("bin_names", binNames); histo.add("bins", ary); res.add("histogram", histo); if(!_enum && _percentiles != null){ if(_percentileValues == null)computePercentiles(); JsonObject percentiles = new JsonObject(); JsonArray thresholds = new JsonArray(); JsonArray values = new JsonArray(); for(int i = 0; i < _percentiles.length; ++i){ thresholds.add(new JsonPrimitive(_percentiles[i])); values.add(new JsonPrimitive(_percentileValues[i])); } percentiles.add("thresholds", thresholds); percentiles.add("values", values); res.add("percentiles", percentiles); } return res; }
public JsonObject toJson(){ JsonObject res = new JsonObject(); res.addProperty("type", _enum?"enum":"number"); res.addProperty("name", _summary._ary._cols[_colId]._name); if (_enum) res.addProperty("enumCardinality", getEnumCardinality()); if(!_enum){ JsonArray min = new JsonArray(); for(double d:_min){ if(Double.isInfinite(d))break; min.add(new JsonPrimitive(d)); } res.add("min", min); JsonArray max = new JsonArray(); for(double d:_max){ if(Double.isInfinite(d))break; max.add(new JsonPrimitive(d)); } res.add("max", max); res.addProperty("mean", _summary._ary._cols[_colId]._mean); res.addProperty("sigma", _summary._ary._cols[_colId]._sigma); res.addProperty("zeros", _nzero); } res.addProperty("N", _n); res.addProperty("na", _n_na); JsonObject histo = new JsonObject(); histo.addProperty("bin_size", _binsz); histo.addProperty("nbins", _bins.length); JsonArray ary = new JsonArray(); JsonArray binNames = new JsonArray(); if(_summary._ary._cols[_colId].isEnum()){ for(int i = 0; i < _summary._ary._cols[_colId]._domain.length; ++i){ if(_bins[i] != 0){ ary.add(new JsonPrimitive(_bins[i])); binNames.add(new JsonPrimitive(_summary._ary._cols[_colId]._domain[i])); } } } else { double x = _min[0]; if(_binsz != 1)x += _binsz*0.5; for(int i = 0; i < _bins.length; ++i){ if(_bins[i] != 0){ ary.add(new JsonPrimitive(_bins[i])); binNames.add(new JsonPrimitive(Utils.p2d(x + i*_binsz))); } } } histo.add("bin_names", binNames); histo.add("bins", ary); res.add("histogram", histo); if(!_enum && _percentiles != null){ if(_percentileValues == null)computePercentiles(); JsonObject percentiles = new JsonObject(); JsonArray thresholds = new JsonArray(); JsonArray values = new JsonArray(); for(int i = 0; i < _percentiles.length; ++i){ thresholds.add(new JsonPrimitive(_percentiles[i])); values.add(new JsonPrimitive(_percentileValues[i])); } percentiles.add("thresholds", thresholds); percentiles.add("values", values); res.add("percentiles", percentiles); } return res; }
diff --git a/test/sun/tools/jhat/HatRun.java b/test/sun/tools/jhat/HatRun.java index cb1e41b24..41f691129 100644 --- a/test/sun/tools/jhat/HatRun.java +++ b/test/sun/tools/jhat/HatRun.java @@ -1,232 +1,234 @@ /* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* * * Support classes for running jhat tests * */ import java.io.InputStream; import java.io.IOException; import java.io.File; import java.io.BufferedInputStream; import java.io.PrintStream; /* * Helper class to direct process output to a StringBuffer */ class MyInputStream implements Runnable { private String name; private BufferedInputStream in; private StringBuffer buffer; /* Create MyInputStream that saves all output to a StringBuffer */ MyInputStream(String name, InputStream in) { this.name = name; this.in = new BufferedInputStream(in); buffer = new StringBuffer(4096); Thread thr = new Thread(this); thr.setDaemon(true); thr.start(); } /* Dump the buffer */ void dump(PrintStream x) { String str = buffer.toString(); x.println("<beginning of " + name + " buffer>"); x.println(str); x.println("<end of buffer>"); } /* Check to see if a pattern is inside the output. */ boolean contains(String pattern) { String str = buffer.toString(); return str.contains(pattern); } /* Runs as a separate thread capturing all output in a StringBuffer */ public void run() { try { byte b[] = new byte[100]; for (;;) { int n = in.read(b); String str; if (n < 0) { break; } str = new String(b, 0, n); buffer.append(str); System.out.print(str); } } catch (IOException ioe) { /* skip */ } } } /* * Main jhat run */ public class HatRun { private String all_hprof_options; private String all_hat_options; private String dumpfile; private MyInputStream output; private MyInputStream error; /* Create a Hat run process */ public HatRun(String hprof_options, String hat_options) { all_hprof_options = hprof_options; all_hat_options = hat_options; } /* * Execute a process with an -agentpath or -agentlib command option */ public void runit(String class_name) { runit(class_name, null); } /* * Execute a command. */ private void execute(String cmd[]) { /* Begin process */ Process p; String cmdLine = ""; int i; for ( i = 0 ; i < cmd.length; i++ ) { cmdLine += cmd[i]; cmdLine += " "; } System.out.println("Starting: " + cmdLine); try { p = Runtime.getRuntime().exec(cmd); } catch ( IOException e ) { throw new RuntimeException("Test failed - exec got IO exception"); } /* Save process output in StringBuffers */ output = new MyInputStream("Input Stream", p.getInputStream()); error = new MyInputStream("Error Stream", p.getErrorStream()); /* Wait for process to complete, and if exit code is non-zero we fail */ try { int exitStatus; exitStatus = p.waitFor(); if ( exitStatus != 0) { System.out.println("Exit code is " + exitStatus); error.dump(System.out); output.dump(System.out); throw new RuntimeException("Test failed - " + "exit return code non-zero " + "(exitStatus==" + exitStatus + ")"); } } catch ( InterruptedException e ) { throw new RuntimeException("Test failed - process interrupted"); } System.out.println("Completed: " + cmdLine); } /* * Execute a process with an -agentpath or -agentlib command option * plus any set of other java options. */ public void runit(String class_name, String vm_options[]) { String jre_home = System.getProperty("java.home"); String sdk_home = (jre_home.endsWith("jre") ? (jre_home + File.separator + "..") : jre_home ); String cdir = System.getProperty("test.classes", "."); String os_arch = System.getProperty("os.arch"); boolean d64 = os_arch.equals("sparcv9") || os_arch.equals("amd64"); String isa_dir = d64?(File.separator+os_arch):""; String java = jre_home + File.separator + "bin" + isa_dir + File.separator + "java"; String jhat = sdk_home + File.separator + "bin" + File.separator + "jhat"; /* Array of strings to be passed in for exec: * 1. java - * 2. -Dtest.classes=. - * 3. -d64 (optional) - * 4. -Xcheck:jni (Just because it finds bugs) - * 5. -Xverify:all (Make sure verification is on full blast) - * 6. -agent + * 2. -cp + * 3. cdir + * 4. -Dtest.classes=. + * 5. -d64 (optional) + * 6. -Xcheck:jni (Just because it finds bugs) + * 7. -Xverify:all (Make sure verification is on full blast) + * 8. -agent * vm_options - * 7+i. classname + * 9+i. classname */ int nvm_options = 0; if ( vm_options != null ) nvm_options = vm_options.length; String cmd[] = new String[1 + (d64?1:0) + 7 + nvm_options]; int i,j; i = 0; cmd[i++] = java; cmd[i++] = "-cp"; cmd[i++] = cdir; cmd[i++] = "-Dtest.classes=" + cdir; if ( d64 ) { cmd[i++] = "-d64"; } cmd[i++] = "-Xcheck:jni"; cmd[i++] = "-Xverify:all"; dumpfile= cdir + File.separator + class_name + ".hdump"; cmd[i++] = "-agentlib:hprof=" + all_hprof_options + ",format=b,file=" + dumpfile; /* Add any special VM options */ for ( j = 0; j < nvm_options; j++ ) { cmd[i++] = vm_options[j]; } /* Add classname */ cmd[i++] = class_name; /* Execute process */ execute(cmd); /* Run jhat */ String jhat_cmd[] = new String[4]; jhat_cmd[0] = jhat; jhat_cmd[1] = "-debug"; jhat_cmd[2] = "2"; jhat_cmd[3] = dumpfile; /* Execute process */ execute(jhat_cmd); } /* Does the pattern appear in the output of this process */ public boolean output_contains(String pattern) { return output.contains(pattern) || error.contains(pattern); } }
false
true
public void runit(String class_name, String vm_options[]) { String jre_home = System.getProperty("java.home"); String sdk_home = (jre_home.endsWith("jre") ? (jre_home + File.separator + "..") : jre_home ); String cdir = System.getProperty("test.classes", "."); String os_arch = System.getProperty("os.arch"); boolean d64 = os_arch.equals("sparcv9") || os_arch.equals("amd64"); String isa_dir = d64?(File.separator+os_arch):""; String java = jre_home + File.separator + "bin" + isa_dir + File.separator + "java"; String jhat = sdk_home + File.separator + "bin" + File.separator + "jhat"; /* Array of strings to be passed in for exec: * 1. java * 2. -Dtest.classes=. * 3. -d64 (optional) * 4. -Xcheck:jni (Just because it finds bugs) * 5. -Xverify:all (Make sure verification is on full blast) * 6. -agent * vm_options * 7+i. classname */ int nvm_options = 0; if ( vm_options != null ) nvm_options = vm_options.length; String cmd[] = new String[1 + (d64?1:0) + 7 + nvm_options]; int i,j; i = 0; cmd[i++] = java; cmd[i++] = "-cp"; cmd[i++] = cdir; cmd[i++] = "-Dtest.classes=" + cdir; if ( d64 ) { cmd[i++] = "-d64"; } cmd[i++] = "-Xcheck:jni"; cmd[i++] = "-Xverify:all"; dumpfile= cdir + File.separator + class_name + ".hdump"; cmd[i++] = "-agentlib:hprof=" + all_hprof_options + ",format=b,file=" + dumpfile; /* Add any special VM options */ for ( j = 0; j < nvm_options; j++ ) { cmd[i++] = vm_options[j]; } /* Add classname */ cmd[i++] = class_name; /* Execute process */ execute(cmd); /* Run jhat */ String jhat_cmd[] = new String[4]; jhat_cmd[0] = jhat; jhat_cmd[1] = "-debug"; jhat_cmd[2] = "2"; jhat_cmd[3] = dumpfile; /* Execute process */ execute(jhat_cmd); }
public void runit(String class_name, String vm_options[]) { String jre_home = System.getProperty("java.home"); String sdk_home = (jre_home.endsWith("jre") ? (jre_home + File.separator + "..") : jre_home ); String cdir = System.getProperty("test.classes", "."); String os_arch = System.getProperty("os.arch"); boolean d64 = os_arch.equals("sparcv9") || os_arch.equals("amd64"); String isa_dir = d64?(File.separator+os_arch):""; String java = jre_home + File.separator + "bin" + isa_dir + File.separator + "java"; String jhat = sdk_home + File.separator + "bin" + File.separator + "jhat"; /* Array of strings to be passed in for exec: * 1. java * 2. -cp * 3. cdir * 4. -Dtest.classes=. * 5. -d64 (optional) * 6. -Xcheck:jni (Just because it finds bugs) * 7. -Xverify:all (Make sure verification is on full blast) * 8. -agent * vm_options * 9+i. classname */ int nvm_options = 0; if ( vm_options != null ) nvm_options = vm_options.length; String cmd[] = new String[1 + (d64?1:0) + 7 + nvm_options]; int i,j; i = 0; cmd[i++] = java; cmd[i++] = "-cp"; cmd[i++] = cdir; cmd[i++] = "-Dtest.classes=" + cdir; if ( d64 ) { cmd[i++] = "-d64"; } cmd[i++] = "-Xcheck:jni"; cmd[i++] = "-Xverify:all"; dumpfile= cdir + File.separator + class_name + ".hdump"; cmd[i++] = "-agentlib:hprof=" + all_hprof_options + ",format=b,file=" + dumpfile; /* Add any special VM options */ for ( j = 0; j < nvm_options; j++ ) { cmd[i++] = vm_options[j]; } /* Add classname */ cmd[i++] = class_name; /* Execute process */ execute(cmd); /* Run jhat */ String jhat_cmd[] = new String[4]; jhat_cmd[0] = jhat; jhat_cmd[1] = "-debug"; jhat_cmd[2] = "2"; jhat_cmd[3] = dumpfile; /* Execute process */ execute(jhat_cmd); }
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java index ef4a6453..213f63a3 100644 --- a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java +++ b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java @@ -1,1272 +1,1272 @@ /***************************************************************************** * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.vmware.bdd.cli.commands; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import jline.ConsoleReader; import org.apache.hadoop.conf.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.hadoop.impala.hive.HiveCommands; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import com.vmware.bdd.apitypes.ClusterType; import com.vmware.bdd.apitypes.ClusterCreate; import com.vmware.bdd.apitypes.ClusterRead; import com.vmware.bdd.apitypes.DistroRead; import com.vmware.bdd.apitypes.NetworkRead; import com.vmware.bdd.apitypes.NodeGroupCreate; import com.vmware.bdd.apitypes.NodeGroupRead; import com.vmware.bdd.apitypes.NodeRead; import com.vmware.bdd.apitypes.TopologyType; import com.vmware.bdd.cli.rest.CliRestException; import com.vmware.bdd.cli.rest.ClusterRestClient; import com.vmware.bdd.cli.rest.DistroRestClient; import com.vmware.bdd.cli.rest.NetworkRestClient; import com.vmware.bdd.utils.AppConfigValidationUtils; import com.vmware.bdd.utils.AppConfigValidationUtils.ValidationType; import com.vmware.bdd.utils.ValidateResult; @Component public class ClusterCommands implements CommandMarker { @Autowired private DistroRestClient distroRestClient; @Autowired private NetworkRestClient networkRestClient; @Autowired private ClusterRestClient restClient; @Autowired private Configuration hadoopConfiguration; @Autowired private HiveCommands hiveCommands; private String hiveInfo; private String targetClusterName; private boolean alwaysAnswerYes; //define role of the node group . private enum NodeGroupRole { MASTER, WORKER, CLIENT, NONE } @CliAvailabilityIndicator({ "cluster help" }) public boolean isCommandAvailable() { return true; } @CliCommand(value = "cluster create", help = "Create a hadoop cluster") public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "Hadoop Distro") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName, @CliOption(key = { "topology" }, mandatory = false, help = "Please specify the topology type: HVE or RACK_HOST or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { this.alwaysAnswerYes = alwaysAnswerYes; //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } //process resume if (resume) { resumeCreateCluster(name); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, - Constants.INVALID_VALUE + " " + "topologyType=" + topology); + Constants.INVALID_VALUE + " " + "type=" + type); return; } clusterCreate.setType(clusterType); } if (topology != null) { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException ex) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } } else { clusterCreate.setTopologyPolicy(null); } if (distro != null) { List<String> distroNames = getDistroNames(); if (validName(distro, distroNames)) { clusterCreate.setDistro(distro); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + distroNames); return; } } if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> warningMsgList = new ArrayList<String>(); List<String> networkNames = null; try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList); if (!validateHAInfo(clusterCreate.getNodeGroups())){ CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } } networkNames = getNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (networkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED); return; } else { if (networkName != null) { if (validName(networkName, networkNames)) { clusterCreate.setNetworkName(networkName); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + networkNames); return; } } else { if (networkNames.size() == 1) { clusterCreate.setNetworkName(networkNames.get(0)); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } } // Validate that the specified file is correct json format and proper value. if (specFilePath != null) { if (!validateClusterCreate(clusterCreate)) { return; } } // process topology option if (topology == null) { clusterCreate.setTopologyPolicy(TopologyType.NONE); } else { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_TOPOLOGY_INVALID_VALUE); System.out.println("Please specify the topology type: HVE or RACK_HOST or HOST_AS_RACK"); return; } } // rest invocation try { if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) { return; } restClient.create(clusterCreate); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster list", help = "Get cluster information") public void getCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { ClusterRead[] clusters = restClient.getAll(); if (clusters != null) { prettyOutputClustersInfo(clusters, detail); } } else { ClusterRead cluster = restClient.get(name); if (cluster != null) { prettyOutputClusterInfo(cluster, detail); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster export --spec", help = "Export cluster specification") public void exportClusterSpec( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) { // rest invocation try { ClusterCreate cluster = restClient.getSpec(name); if (cluster != null) { CommandsUtils.prettyJsonOutput(cluster, fileName); } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster delete", help = "Delete a cluster") public void deleteCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_DELETE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster start", help = "Start a cluster") public void startCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings .put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START); //rest invocation try { if (!validateNodeGroupName(nodeGroupName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node group name"); return; } if (!validateNodeName(clusterName, nodeGroupName, nodeName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node name"); return; } String groupName = nodeGroupName; String fullNodeName = nodeName; if (nodeName != null) { if (nodeGroupName == null) { groupName = extractNodeGroupName(nodeName); if (groupName == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "missing node group name"); return; } } else { fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName); } } String resource = getClusterResourceName(clusterName, groupName, fullNodeName); if (resource != null) { restClient.actionOps(resource, clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_START); } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster stop", help = "Stop a cluster") public void stopCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP); //rest invocation try { if (!validateNodeGroupName(nodeGroupName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node group name"); return; } if (!validateNodeName(clusterName, nodeGroupName, nodeName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node name"); return; } String groupName = nodeGroupName; String fullNodeName = nodeName; if (nodeName != null) { if (nodeGroupName == null) { groupName = extractNodeGroupName(nodeName); if (groupName == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "missing node group name"); return; } } else { fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName); } } String resource = getClusterResourceName(clusterName, groupName, fullNodeName); if (resource != null) { restClient.actionOps(resource, clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_STOP); } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster resize", help = "Resize a cluster") public void resizeCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup, @CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) { if (instanceNum > 1) { try { restClient.resize(name, nodeGroup, instanceNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESIZE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " instanceNum=" + instanceNum); } } @CliCommand(value = "cluster limit", help = "Set number of instances powered on in a node group") public void limitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "activeComputeNodeNum" }, mandatory = true, help = "The number of instances powered on") final int activeComputeNodeNum) { try { // The active compute node number must be a integer and cannot be less than zero. if (activeComputeNodeNum < 0) { System.out.println("Invalid instance number:" + activeComputeNodeNum); return; } ClusterRead cluster = restClient.get(clusterName); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName, activeComputeNodeNum)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster target", help = "Set or query target cluster to run commands") public void targetCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) { ClusterRead cluster = null; try { if (info) { if (name != null) { System.out.println("Warning: can't specify option --name and --info at the same time"); return; } String fsUrl = hadoopConfiguration.get("fs.default.name"); String jtUrl = hadoopConfiguration.get("mapred.job.tracker"); if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) { System.out.println("There is no targeted cluster. Please use \"cluster target --name\" to target first"); return; } if(targetClusterName != null && targetClusterName.length() > 0){ System.out.println("Cluster : " + targetClusterName); } if (fsUrl != null && fsUrl.length() > 0) { System.out.println("HDFS url : " + fsUrl); } if (jtUrl != null && jtUrl.length() > 0) { System.out.println("Job Tracker url : " + jtUrl); } if (hiveInfo != null && hiveInfo.length() > 0) { System.out.println("Hive server info: " + hiveInfo); } } else { if (name == null) { ClusterRead[] clusters = restClient.getAll(); if (clusters != null && clusters.length > 0) { cluster = clusters[0]; } } else { cluster = restClient.get(name); } if (cluster == null) { System.out.println("Failed to target cluster: The cluster " + name + "is not found"); setFsURL(""); setJobTrackerURL(""); this.setHiveServer(""); } else { targetClusterName = cluster.getName(); for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) { for (String role : nodeGroup.getRoles()) { if (role.equals("hadoop_namenode")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String nameNodeIP = nodes.get(0).getIp(); setNameNode(nameNodeIP); } else { throw new CliRestException("no name node available"); } } if (role.equals("hadoop_jobtracker")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String jobTrackerIP = nodes.get(0).getIp(); setJobTracker(jobTrackerIP); } else { throw new CliRestException("no job tracker available"); } } if (role.equals("hive_server")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String hiveServerIP = nodes.get(0).getIp(); setHiveServer(hiveServerIP); } else { throw new CliRestException("no hive server available"); } } } } if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { setFsURL(cluster.getExternalHDFS()); } } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); setFsURL(""); setJobTrackerURL(""); this.setHiveServer(""); } } private void setNameNode(String nameNodeAddress) { String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020"; setFsURL(hdfsUrl); } private void setFsURL(String fsURL) { hadoopConfiguration.set("fs.default.name", fsURL); } private void setJobTracker(String jobTrackerAddress) { String jobTrackerUrl = jobTrackerAddress + ":8021"; setJobTrackerURL(jobTrackerUrl); } private void setJobTrackerURL(String jobTrackerUrl){ hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl); } private void setHiveServer(String hiveServerAddress) { try { hiveInfo = hiveCommands.config(hiveServerAddress, 10000, null); } catch (Exception e) { throw new CliRestException("faild to set hive server address"); } } @CliCommand(value = "cluster config", help = "Config an existing cluster") public void configCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { this.alwaysAnswerYes = alwaysAnswerYes; //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } try { ClusterRead clusterRead = restClient.get(name); // build ClusterCreate object ClusterCreate clusterConfig = new ClusterCreate(); clusterConfig.setName(clusterRead.getName()); ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterConfig.setNodeGroups(clusterSpec.getNodeGroups()); clusterConfig.setConfiguration(clusterSpec.getConfiguration()); clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS()); List<String> warningMsgList = new ArrayList<String>(); validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList); // add a confirm message for running job warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING); if (!showWarningMsg(clusterConfig.getName(), warningMsgList)) { return; } restClient.configCluster(clusterConfig); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } } private String getClusterResourceName(String cluster, String nodeGroup, String node) { assert cluster != null; // Spring shell guarantees this if (node != null && nodeGroup == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, cluster, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, Constants.OUTPUT_OP_NODEGROUP_MISSING); return null; } StringBuilder res = new StringBuilder(); res.append(cluster); if (nodeGroup != null) { res.append("/nodegroup/").append(nodeGroup); if (node != null) { res.append("/node/").append(node); } } return res.toString(); } private boolean validateNodeName(String cluster, String group, String node) { if (node != null) { String[] parts = node.split("-"); if (parts.length == 1) { return true; } if (parts.length == 3) { if (!parts[0].equals(cluster)) { return false; } if (group != null && !parts[1].equals(group)) { return false; } return true; } return false; } return true; } private boolean validateNodeGroupName(String group) { if (group != null) { return group.indexOf("-") == -1; } return true; } private String autoCompleteNodeName(String cluster, String group, String node) { assert cluster != null; assert group != null; assert node != null; if (node.indexOf("-") == -1) { StringBuilder sb = new StringBuilder(); sb.append(cluster).append("-").append(group).append("-").append(node); return sb.toString(); } return node; } private String extractNodeGroupName(String node) { String[] parts = node.split("-"); if (parts.length == 3) { return parts[1]; } return null; } private void resumeCreateCluster(final String name) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_RESUME); try { restClient.actionOps(name, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESUME); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> getNetworkNames() { List<String> networkNames = new ArrayList<String>(0); NetworkRead[] networks = networkRestClient.getAll(false); if (networks != null) { for (NetworkRead network : networks) networkNames.add(network.getName()); } return networkNames; } private List<String> getDistroNames() { List<String> distroNames = new ArrayList<String>(0); DistroRead[] distros = distroRestClient.getAll(); if (distros != null) { for (DistroRead distro : distros) distroNames.add(distro.getName()); } return distroNames; } private boolean validName(String inputName, List<String> validNames) { for (String name : validNames) { if (name.equals(inputName)) { return true; } } return false; } private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) { TopologyType topology = cluster.getTopologyPolicy(); if (topology == null || topology == TopologyType.NONE) { System.out.printf("name: %s, distro: %s, status: %s", cluster.getName(), cluster.getDistro(), cluster.getStatus()); } else { System.out.printf("name: %s, distro: %s, topology: %s, status: %s", cluster.getName(), cluster.getDistro(), topology, cluster.getStatus()); } System.out.println(); if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS()); } LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); List<NodeGroupRead> nodegroups = cluster.getNodeGroups(); if (nodegroups != null) { ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_INSTANCE, Arrays.asList("getInstanceNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU, Arrays.asList("getCpuNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM, Arrays.asList("getMemCapacityMB")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("getStorage", "getType")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_SIZE, Arrays.asList("getStorage", "getSizeGB")); try { if (detail) { LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); if (topology == TopologyType.RACK_AS_RACK || topology == TopologyType.HVE) { nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_RACK, Arrays.asList("getRack")); } nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_HOST, Arrays.asList("getHostName")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_STATUS, Arrays.asList("getStatus")); for (NodeGroupRead nodegroup : nodegroups) { CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, new NodeGroupRead[] { nodegroup }, Constants.OUTPUT_INDENT); List<NodeRead> nodes = nodegroup.getInstances(); if (nodes != null) { System.out.println(); CommandsUtils.printInTableFormat( nColumnNamesWithGetMethodNames, nodes.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } System.out.println(); } } else CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, nodegroups.toArray(), Constants.OUTPUT_INDENT); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, cluster.getName(), Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) { for (ClusterRead cluster : clusters) { prettyOutputClusterInfo(cluster, detail); System.out.println(); } } /** * Validate nodeGroupCreates member formats and values in the ClusterCreate. */ private boolean validateClusterCreate(ClusterCreate clusterCreate) { // validation status boolean validated = true; // show warning message boolean warning = false; //role count int masterCount = 0, workerCount = 0, clientCount = 0; //Find NodeGroupCreate array from current ClusterCreate instance. NodeGroupCreate[] nodeGroupCreates = clusterCreate.getNodeGroups(); if (nodeGroupCreates == null || nodeGroupCreates.length == 0) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.MULTI_INPUTS_CHECK); return !validated; } else { //used for collecting failed message. List<String> failedMsgList = new LinkedList<String>(); List<String> warningMsgList = new LinkedList<String>(); //find distro roles. List<String> distroRoles = findDistroRoles(clusterCreate); if (distroRoles == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NO_DISTRO_AVAILABLE); return !validated; } if (nodeGroupCreates.length < 2 || nodeGroupCreates.length > 5) { warningMsgList.add(Constants.PARAM_CLUSTER_WARNING); warning = true; } // check external HDFS if (clusterCreate.hasHDFSUrlConfigured() && !clusterCreate.validateHDFSUrl()) { failedMsgList.add(new StringBuilder() .append("externalHDFS=") .append(clusterCreate.getExternalHDFS()).toString()); validated = false; } // check placement policies if (!clusterCreate.validateNodeGroupPlacementPolicies(failedMsgList, warningMsgList)) { validated = false; } if (!clusterCreate.validateNodeGroupRoles(failedMsgList)) { validated = false; } for (NodeGroupCreate nodeGroupCreate : nodeGroupCreates) { // check node group's instanceNum if (!checkInstanceNum(nodeGroupCreate, failedMsgList)) { validated = false; } // check node group's roles if (!checkNodeGroupRoles(nodeGroupCreate, distroRoles, failedMsgList)) { validated = false; } // get node group role . NodeGroupRole role = getNodeGroupRole(nodeGroupCreate); switch (role) { case MASTER: masterCount++; if (nodeGroupCreate.getInstanceNum() >= 0 && nodeGroupCreate.getInstanceNum() != 1) { validated = false; collectInstanceNumInvalidateMsg(nodeGroupCreate, failedMsgList); } break; case WORKER: workerCount++; if (nodeGroupCreate.getInstanceNum() == 0) { validated = false; collectInstanceNumInvalidateMsg(nodeGroupCreate, failedMsgList); } else if (isHAFlag(nodeGroupCreate)) { warning = true; } break; case CLIENT: clientCount++; if (isHAFlag(nodeGroupCreate)) { warning = true; } break; case NONE: warning = true; break; default: } } if ((masterCount < 1 || masterCount > 2) || (workerCount < 1 || workerCount > 2) || clientCount > 1) { warning = true; } if (!validated) { showFailedMsg(clusterCreate.getName(), failedMsgList); } else if (warning || warningMsgList != null) { // If warning is true,show waring message. if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) { // When exist warning message,whether to proceed validated = false; } } return validated; } } private boolean isContinue(String clusterName, String operateType, String promptMsg) { if (this.alwaysAnswerYes) { return true; } boolean continueCreate = true; boolean continueLoop = true; String readMsg = ""; try { ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setDefaultPrompt(promptMsg); int k = 0; while (continueLoop) { if (k >= 3) { continueCreate = false; break; } // Read user input readMsg = reader.readLine(); if (readMsg.trim().equalsIgnoreCase("yes") || readMsg.trim().equalsIgnoreCase("y")) { continueLoop = false; } else if (readMsg.trim().equalsIgnoreCase("no") || readMsg.trim().equalsIgnoreCase("n")) { continueLoop = false; continueCreate = false; } else { k++; } } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterName, operateType, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); continueCreate = false; } return continueCreate; } private NodeGroupRole getNodeGroupRole(NodeGroupCreate nodeGroupCreate) { //Find roles list from current NodeGroupCreate instance. List<String> roles = nodeGroupCreate.getRoles(); for (NodeGroupRole role : NodeGroupRole.values()) { if (matchRole(role, roles)) { return role; } } return NodeGroupRole.NONE; } /** * Check the roles was introduced, whether matching with system's specialize * role. */ private boolean matchRole(NodeGroupRole role, List<String> roles) { List<String> matchRoles = new LinkedList<String>(); switch (role) { case MASTER: if (roles.size() == 1) { String r = roles.get(0); return Constants.ROLE_HADOOP_NAME_NODE.equals(r) || Constants.ROLE_HADOOP_JOB_TRACKER.equals(r); } else if (roles.size() == 2) { matchRoles.add(Constants.ROLE_HADOOP_NAME_NODE); matchRoles.add(Constants.ROLE_HADOOP_JOB_TRACKER); matchRoles.removeAll(roles); return matchRoles.size() == 0 ? true : false; } return false; case WORKER: if (roles.size() == 1) { if (Constants.ROLE_HADOOP_DATANODE.equals(roles.get(0)) || Constants.ROLE_HADOOP_TASKTRACKER.equals(roles.get(0))) { return true; } return false; } else { matchRoles.add(Constants.ROLE_HADOOP_DATANODE); matchRoles.add(Constants.ROLE_HADOOP_TASKTRACKER); matchRoles.removeAll(roles); return matchRoles.size() == 0 ? true : false; } case CLIENT: if (roles.size() < 1 || roles.size() > 4) { return false; } else { matchRoles.add(Constants.ROLE_HADOOP_CLIENT); matchRoles.add(Constants.ROLE_HIVE); matchRoles.add(Constants.ROLE_HIVE_SERVER); matchRoles.add(Constants.ROLE_PIG); int diffNum = matchRoles.size() - roles.size(); matchRoles.removeAll(roles); return roles.contains(Constants.ROLE_HADOOP_CLIENT) && (diffNum >= 0) && (diffNum == matchRoles.size()) ? true : false; } } return false; } private void showWarningMsg() { System.out.println(Constants.PARAM_CLUSTER_WARNING); } private boolean checkInstanceNum(NodeGroupCreate nodeGroup, List<String> failedMsgList) { boolean validated = true; if (nodeGroup.getInstanceNum() < 0) { validated = false; collectInstanceNumInvalidateMsg(nodeGroup, failedMsgList); } return validated; } private void collectInstanceNumInvalidateMsg(NodeGroupCreate nodeGroup, List<String> failedMsgList) { failedMsgList.add(new StringBuilder().append(nodeGroup.getName()) .append(".").append("instanceNum=") .append(nodeGroup.getInstanceNum()).toString()); } private boolean checkNodeGroupRoles(NodeGroupCreate nodeGroup, List<String> distroRoles, List<String> failedMsgList) { List<String> roles = nodeGroup.getRoles(); boolean validated = true; StringBuilder rolesMsg = new StringBuilder(); for (String role : roles) { if (!distroRoles.contains(role)) { validated = false; rolesMsg.append(",").append(role); } } if (!validated) { rolesMsg.replace(0, 1, ""); failedMsgList.add(new StringBuilder().append(nodeGroup.getName()) .append(".").append("roles=").append("\"") .append(rolesMsg.toString()).append("\"").toString()); } return validated; } private List<String> findDistroRoles(ClusterCreate clusterCreate) { DistroRead distroRead = null; distroRead = distroRestClient .get(clusterCreate.getDistro() != null ? clusterCreate .getDistro() : Constants.DEFAULT_DISTRO); if (distroRead != null) { return distroRead.getRoles(); } else { return null; } } private void showFailedMsg(String name, List<String> failedMsgList) { //cluster creation failed message. StringBuilder failedMsg = new StringBuilder(); failedMsg.append(Constants.INVALID_VALUE); if (failedMsgList.size() > 1) { failedMsg.append("s"); } failedMsg.append(" "); StringBuilder tmpMsg = new StringBuilder(); for (String msg : failedMsgList) { tmpMsg.append(",").append(msg); } tmpMsg.replace(0, 1, ""); failedMsg.append(tmpMsg); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, failedMsg.toString()); } private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) { // validate blacklist ValidateResult blackListResult = validateBlackList(cluster); if (blackListResult != null) { addBlackListWarning(blackListResult, warningMsgList); } if (!skipConfigValidation) { // validate whitelist ValidateResult whiteListResult = validateWhiteList(cluster); addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList); } else { cluster.setValidateConfig(false); } } private ValidateResult validateBlackList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.BLACK_LIST); } private ValidateResult validateWhiteList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.WHITE_LIST); } private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) { ValidateResult validateResult = new ValidateResult(); // validate cluster level Configuration ValidateResult vr = null; if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); validateResult.setFailureNames(vr.getFailureNames()); } } // validate nodegroup level Configuration for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) { if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); List<String> failureNames = new LinkedList<String>(); failureNames.addAll(validateResult.getFailureNames()); for (String name : vr.getFailureNames()) { if (!failureNames.contains(name)) { failureNames.add(name); } } validateResult.setFailureNames(vr.getFailureNames()); } } } return validateResult; } private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult, List<String> warningMsgList) { if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) { String warningMsg = getValidateWarningMsg(whiteListResult.getFailureNames(), Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING); if (warningMsgList != null) { warningMsgList.add(warningMsg); } } } private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) { if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) { String warningMsg = getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING); if (warningList != null) warningList.add(warningMsg); } } private String getValidateWarningMsg(List<String> failureNames, String warningMsg) { StringBuilder warningMsgBuff = new StringBuilder(); if (failureNames != null && !failureNames.isEmpty()) { warningMsgBuff.append("Warning: "); for (String failureName : failureNames) { warningMsgBuff.append(failureName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (failureNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append(warningMsg); } return warningMsgBuff.toString(); } private boolean showWarningMsg(String clusterName, List<String> warningMsgList) { if (warningMsgList != null && !warningMsgList.isEmpty()) { for (String message : warningMsgList) { System.out.println(message); } if (!isContinue(clusterName, Constants.OUTPUT_OP_CREATE, Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) { return false; } } return true; } private boolean isHAFlag(NodeGroupCreate nodeGroupCreate) { return !CommandsUtils.isBlank(nodeGroupCreate.getHaFlag()) && !nodeGroupCreate.getHaFlag().equalsIgnoreCase("off"); } private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) { List<String> haFlagList = Arrays.asList("off","on","ft"); if (nodeGroups != null){ for(NodeGroupCreate group : nodeGroups){ if (!haFlagList.contains(group.getHaFlag().toLowerCase())){ return false; } } } return true; } }
true
true
public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "Hadoop Distro") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName, @CliOption(key = { "topology" }, mandatory = false, help = "Please specify the topology type: HVE or RACK_HOST or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { this.alwaysAnswerYes = alwaysAnswerYes; //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } //process resume if (resume) { resumeCreateCluster(name); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } clusterCreate.setType(clusterType); } if (topology != null) { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException ex) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } } else { clusterCreate.setTopologyPolicy(null); } if (distro != null) { List<String> distroNames = getDistroNames(); if (validName(distro, distroNames)) { clusterCreate.setDistro(distro); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + distroNames); return; } } if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> warningMsgList = new ArrayList<String>(); List<String> networkNames = null; try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList); if (!validateHAInfo(clusterCreate.getNodeGroups())){ CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } } networkNames = getNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (networkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED); return; } else { if (networkName != null) { if (validName(networkName, networkNames)) { clusterCreate.setNetworkName(networkName); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + networkNames); return; } } else { if (networkNames.size() == 1) { clusterCreate.setNetworkName(networkNames.get(0)); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } } // Validate that the specified file is correct json format and proper value. if (specFilePath != null) { if (!validateClusterCreate(clusterCreate)) { return; } } // process topology option if (topology == null) { clusterCreate.setTopologyPolicy(TopologyType.NONE); } else { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_TOPOLOGY_INVALID_VALUE); System.out.println("Please specify the topology type: HVE or RACK_HOST or HOST_AS_RACK"); return; } } // rest invocation try { if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) { return; } restClient.create(clusterCreate); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster list", help = "Get cluster information") public void getCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { ClusterRead[] clusters = restClient.getAll(); if (clusters != null) { prettyOutputClustersInfo(clusters, detail); } } else { ClusterRead cluster = restClient.get(name); if (cluster != null) { prettyOutputClusterInfo(cluster, detail); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster export --spec", help = "Export cluster specification") public void exportClusterSpec( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) { // rest invocation try { ClusterCreate cluster = restClient.getSpec(name); if (cluster != null) { CommandsUtils.prettyJsonOutput(cluster, fileName); } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster delete", help = "Delete a cluster") public void deleteCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_DELETE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster start", help = "Start a cluster") public void startCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings .put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START); //rest invocation try { if (!validateNodeGroupName(nodeGroupName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node group name"); return; } if (!validateNodeName(clusterName, nodeGroupName, nodeName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node name"); return; } String groupName = nodeGroupName; String fullNodeName = nodeName; if (nodeName != null) { if (nodeGroupName == null) { groupName = extractNodeGroupName(nodeName); if (groupName == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "missing node group name"); return; } } else { fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName); } } String resource = getClusterResourceName(clusterName, groupName, fullNodeName); if (resource != null) { restClient.actionOps(resource, clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_START); } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster stop", help = "Stop a cluster") public void stopCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP); //rest invocation try { if (!validateNodeGroupName(nodeGroupName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node group name"); return; } if (!validateNodeName(clusterName, nodeGroupName, nodeName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node name"); return; } String groupName = nodeGroupName; String fullNodeName = nodeName; if (nodeName != null) { if (nodeGroupName == null) { groupName = extractNodeGroupName(nodeName); if (groupName == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "missing node group name"); return; } } else { fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName); } } String resource = getClusterResourceName(clusterName, groupName, fullNodeName); if (resource != null) { restClient.actionOps(resource, clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_STOP); } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster resize", help = "Resize a cluster") public void resizeCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup, @CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) { if (instanceNum > 1) { try { restClient.resize(name, nodeGroup, instanceNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESIZE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " instanceNum=" + instanceNum); } } @CliCommand(value = "cluster limit", help = "Set number of instances powered on in a node group") public void limitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "activeComputeNodeNum" }, mandatory = true, help = "The number of instances powered on") final int activeComputeNodeNum) { try { // The active compute node number must be a integer and cannot be less than zero. if (activeComputeNodeNum < 0) { System.out.println("Invalid instance number:" + activeComputeNodeNum); return; } ClusterRead cluster = restClient.get(clusterName); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName, activeComputeNodeNum)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster target", help = "Set or query target cluster to run commands") public void targetCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) { ClusterRead cluster = null; try { if (info) { if (name != null) { System.out.println("Warning: can't specify option --name and --info at the same time"); return; } String fsUrl = hadoopConfiguration.get("fs.default.name"); String jtUrl = hadoopConfiguration.get("mapred.job.tracker"); if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) { System.out.println("There is no targeted cluster. Please use \"cluster target --name\" to target first"); return; } if(targetClusterName != null && targetClusterName.length() > 0){ System.out.println("Cluster : " + targetClusterName); } if (fsUrl != null && fsUrl.length() > 0) { System.out.println("HDFS url : " + fsUrl); } if (jtUrl != null && jtUrl.length() > 0) { System.out.println("Job Tracker url : " + jtUrl); } if (hiveInfo != null && hiveInfo.length() > 0) { System.out.println("Hive server info: " + hiveInfo); } } else { if (name == null) { ClusterRead[] clusters = restClient.getAll(); if (clusters != null && clusters.length > 0) { cluster = clusters[0]; } } else { cluster = restClient.get(name); } if (cluster == null) { System.out.println("Failed to target cluster: The cluster " + name + "is not found"); setFsURL(""); setJobTrackerURL(""); this.setHiveServer(""); } else { targetClusterName = cluster.getName(); for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) { for (String role : nodeGroup.getRoles()) { if (role.equals("hadoop_namenode")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String nameNodeIP = nodes.get(0).getIp(); setNameNode(nameNodeIP); } else { throw new CliRestException("no name node available"); } } if (role.equals("hadoop_jobtracker")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String jobTrackerIP = nodes.get(0).getIp(); setJobTracker(jobTrackerIP); } else { throw new CliRestException("no job tracker available"); } } if (role.equals("hive_server")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String hiveServerIP = nodes.get(0).getIp(); setHiveServer(hiveServerIP); } else { throw new CliRestException("no hive server available"); } } } } if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { setFsURL(cluster.getExternalHDFS()); } } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); setFsURL(""); setJobTrackerURL(""); this.setHiveServer(""); } } private void setNameNode(String nameNodeAddress) { String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020"; setFsURL(hdfsUrl); } private void setFsURL(String fsURL) { hadoopConfiguration.set("fs.default.name", fsURL); } private void setJobTracker(String jobTrackerAddress) { String jobTrackerUrl = jobTrackerAddress + ":8021"; setJobTrackerURL(jobTrackerUrl); } private void setJobTrackerURL(String jobTrackerUrl){ hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl); } private void setHiveServer(String hiveServerAddress) { try { hiveInfo = hiveCommands.config(hiveServerAddress, 10000, null); } catch (Exception e) { throw new CliRestException("faild to set hive server address"); } } @CliCommand(value = "cluster config", help = "Config an existing cluster") public void configCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { this.alwaysAnswerYes = alwaysAnswerYes; //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } try { ClusterRead clusterRead = restClient.get(name); // build ClusterCreate object ClusterCreate clusterConfig = new ClusterCreate(); clusterConfig.setName(clusterRead.getName()); ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterConfig.setNodeGroups(clusterSpec.getNodeGroups()); clusterConfig.setConfiguration(clusterSpec.getConfiguration()); clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS()); List<String> warningMsgList = new ArrayList<String>(); validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList); // add a confirm message for running job warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING); if (!showWarningMsg(clusterConfig.getName(), warningMsgList)) { return; } restClient.configCluster(clusterConfig); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } } private String getClusterResourceName(String cluster, String nodeGroup, String node) { assert cluster != null; // Spring shell guarantees this if (node != null && nodeGroup == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, cluster, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, Constants.OUTPUT_OP_NODEGROUP_MISSING); return null; } StringBuilder res = new StringBuilder(); res.append(cluster); if (nodeGroup != null) { res.append("/nodegroup/").append(nodeGroup); if (node != null) { res.append("/node/").append(node); } } return res.toString(); } private boolean validateNodeName(String cluster, String group, String node) { if (node != null) { String[] parts = node.split("-"); if (parts.length == 1) { return true; } if (parts.length == 3) { if (!parts[0].equals(cluster)) { return false; } if (group != null && !parts[1].equals(group)) { return false; } return true; } return false; } return true; } private boolean validateNodeGroupName(String group) { if (group != null) { return group.indexOf("-") == -1; } return true; } private String autoCompleteNodeName(String cluster, String group, String node) { assert cluster != null; assert group != null; assert node != null; if (node.indexOf("-") == -1) { StringBuilder sb = new StringBuilder(); sb.append(cluster).append("-").append(group).append("-").append(node); return sb.toString(); } return node; } private String extractNodeGroupName(String node) { String[] parts = node.split("-"); if (parts.length == 3) { return parts[1]; } return null; } private void resumeCreateCluster(final String name) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_RESUME); try { restClient.actionOps(name, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESUME); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> getNetworkNames() { List<String> networkNames = new ArrayList<String>(0); NetworkRead[] networks = networkRestClient.getAll(false); if (networks != null) { for (NetworkRead network : networks) networkNames.add(network.getName()); } return networkNames; } private List<String> getDistroNames() { List<String> distroNames = new ArrayList<String>(0); DistroRead[] distros = distroRestClient.getAll(); if (distros != null) { for (DistroRead distro : distros) distroNames.add(distro.getName()); } return distroNames; } private boolean validName(String inputName, List<String> validNames) { for (String name : validNames) { if (name.equals(inputName)) { return true; } } return false; } private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) { TopologyType topology = cluster.getTopologyPolicy(); if (topology == null || topology == TopologyType.NONE) { System.out.printf("name: %s, distro: %s, status: %s", cluster.getName(), cluster.getDistro(), cluster.getStatus()); } else { System.out.printf("name: %s, distro: %s, topology: %s, status: %s", cluster.getName(), cluster.getDistro(), topology, cluster.getStatus()); } System.out.println(); if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS()); } LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); List<NodeGroupRead> nodegroups = cluster.getNodeGroups(); if (nodegroups != null) { ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_INSTANCE, Arrays.asList("getInstanceNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU, Arrays.asList("getCpuNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM, Arrays.asList("getMemCapacityMB")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("getStorage", "getType")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_SIZE, Arrays.asList("getStorage", "getSizeGB")); try { if (detail) { LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); if (topology == TopologyType.RACK_AS_RACK || topology == TopologyType.HVE) { nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_RACK, Arrays.asList("getRack")); } nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_HOST, Arrays.asList("getHostName")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_STATUS, Arrays.asList("getStatus")); for (NodeGroupRead nodegroup : nodegroups) { CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, new NodeGroupRead[] { nodegroup }, Constants.OUTPUT_INDENT); List<NodeRead> nodes = nodegroup.getInstances(); if (nodes != null) { System.out.println(); CommandsUtils.printInTableFormat( nColumnNamesWithGetMethodNames, nodes.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } System.out.println(); } } else CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, nodegroups.toArray(), Constants.OUTPUT_INDENT); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, cluster.getName(), Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) { for (ClusterRead cluster : clusters) { prettyOutputClusterInfo(cluster, detail); System.out.println(); } } /** * Validate nodeGroupCreates member formats and values in the ClusterCreate. */ private boolean validateClusterCreate(ClusterCreate clusterCreate) { // validation status boolean validated = true; // show warning message boolean warning = false; //role count int masterCount = 0, workerCount = 0, clientCount = 0; //Find NodeGroupCreate array from current ClusterCreate instance. NodeGroupCreate[] nodeGroupCreates = clusterCreate.getNodeGroups(); if (nodeGroupCreates == null || nodeGroupCreates.length == 0) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.MULTI_INPUTS_CHECK); return !validated; } else { //used for collecting failed message. List<String> failedMsgList = new LinkedList<String>(); List<String> warningMsgList = new LinkedList<String>(); //find distro roles. List<String> distroRoles = findDistroRoles(clusterCreate); if (distroRoles == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NO_DISTRO_AVAILABLE); return !validated; } if (nodeGroupCreates.length < 2 || nodeGroupCreates.length > 5) { warningMsgList.add(Constants.PARAM_CLUSTER_WARNING); warning = true; } // check external HDFS if (clusterCreate.hasHDFSUrlConfigured() && !clusterCreate.validateHDFSUrl()) { failedMsgList.add(new StringBuilder() .append("externalHDFS=") .append(clusterCreate.getExternalHDFS()).toString()); validated = false; } // check placement policies if (!clusterCreate.validateNodeGroupPlacementPolicies(failedMsgList, warningMsgList)) { validated = false; } if (!clusterCreate.validateNodeGroupRoles(failedMsgList)) { validated = false; } for (NodeGroupCreate nodeGroupCreate : nodeGroupCreates) { // check node group's instanceNum if (!checkInstanceNum(nodeGroupCreate, failedMsgList)) { validated = false; } // check node group's roles if (!checkNodeGroupRoles(nodeGroupCreate, distroRoles, failedMsgList)) { validated = false; } // get node group role . NodeGroupRole role = getNodeGroupRole(nodeGroupCreate); switch (role) { case MASTER: masterCount++; if (nodeGroupCreate.getInstanceNum() >= 0 && nodeGroupCreate.getInstanceNum() != 1) { validated = false; collectInstanceNumInvalidateMsg(nodeGroupCreate, failedMsgList); } break; case WORKER: workerCount++; if (nodeGroupCreate.getInstanceNum() == 0) { validated = false; collectInstanceNumInvalidateMsg(nodeGroupCreate, failedMsgList); } else if (isHAFlag(nodeGroupCreate)) { warning = true; } break; case CLIENT: clientCount++; if (isHAFlag(nodeGroupCreate)) { warning = true; } break; case NONE: warning = true; break; default: } } if ((masterCount < 1 || masterCount > 2) || (workerCount < 1 || workerCount > 2) || clientCount > 1) { warning = true; } if (!validated) { showFailedMsg(clusterCreate.getName(), failedMsgList); } else if (warning || warningMsgList != null) { // If warning is true,show waring message. if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) { // When exist warning message,whether to proceed validated = false; } } return validated; } } private boolean isContinue(String clusterName, String operateType, String promptMsg) { if (this.alwaysAnswerYes) { return true; } boolean continueCreate = true; boolean continueLoop = true; String readMsg = ""; try { ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setDefaultPrompt(promptMsg); int k = 0; while (continueLoop) { if (k >= 3) { continueCreate = false; break; } // Read user input readMsg = reader.readLine(); if (readMsg.trim().equalsIgnoreCase("yes") || readMsg.trim().equalsIgnoreCase("y")) { continueLoop = false; } else if (readMsg.trim().equalsIgnoreCase("no") || readMsg.trim().equalsIgnoreCase("n")) { continueLoop = false; continueCreate = false; } else { k++; } } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterName, operateType, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); continueCreate = false; } return continueCreate; } private NodeGroupRole getNodeGroupRole(NodeGroupCreate nodeGroupCreate) { //Find roles list from current NodeGroupCreate instance. List<String> roles = nodeGroupCreate.getRoles(); for (NodeGroupRole role : NodeGroupRole.values()) { if (matchRole(role, roles)) { return role; } } return NodeGroupRole.NONE; } /** * Check the roles was introduced, whether matching with system's specialize * role. */ private boolean matchRole(NodeGroupRole role, List<String> roles) { List<String> matchRoles = new LinkedList<String>(); switch (role) { case MASTER: if (roles.size() == 1) { String r = roles.get(0); return Constants.ROLE_HADOOP_NAME_NODE.equals(r) || Constants.ROLE_HADOOP_JOB_TRACKER.equals(r); } else if (roles.size() == 2) { matchRoles.add(Constants.ROLE_HADOOP_NAME_NODE); matchRoles.add(Constants.ROLE_HADOOP_JOB_TRACKER); matchRoles.removeAll(roles); return matchRoles.size() == 0 ? true : false; } return false; case WORKER: if (roles.size() == 1) { if (Constants.ROLE_HADOOP_DATANODE.equals(roles.get(0)) || Constants.ROLE_HADOOP_TASKTRACKER.equals(roles.get(0))) { return true; } return false; } else { matchRoles.add(Constants.ROLE_HADOOP_DATANODE); matchRoles.add(Constants.ROLE_HADOOP_TASKTRACKER); matchRoles.removeAll(roles); return matchRoles.size() == 0 ? true : false; } case CLIENT: if (roles.size() < 1 || roles.size() > 4) { return false; } else { matchRoles.add(Constants.ROLE_HADOOP_CLIENT); matchRoles.add(Constants.ROLE_HIVE); matchRoles.add(Constants.ROLE_HIVE_SERVER); matchRoles.add(Constants.ROLE_PIG); int diffNum = matchRoles.size() - roles.size(); matchRoles.removeAll(roles); return roles.contains(Constants.ROLE_HADOOP_CLIENT) && (diffNum >= 0) && (diffNum == matchRoles.size()) ? true : false; } } return false; } private void showWarningMsg() { System.out.println(Constants.PARAM_CLUSTER_WARNING); } private boolean checkInstanceNum(NodeGroupCreate nodeGroup, List<String> failedMsgList) { boolean validated = true; if (nodeGroup.getInstanceNum() < 0) { validated = false; collectInstanceNumInvalidateMsg(nodeGroup, failedMsgList); } return validated; } private void collectInstanceNumInvalidateMsg(NodeGroupCreate nodeGroup, List<String> failedMsgList) { failedMsgList.add(new StringBuilder().append(nodeGroup.getName()) .append(".").append("instanceNum=") .append(nodeGroup.getInstanceNum()).toString()); } private boolean checkNodeGroupRoles(NodeGroupCreate nodeGroup, List<String> distroRoles, List<String> failedMsgList) { List<String> roles = nodeGroup.getRoles(); boolean validated = true; StringBuilder rolesMsg = new StringBuilder(); for (String role : roles) { if (!distroRoles.contains(role)) { validated = false; rolesMsg.append(",").append(role); } } if (!validated) { rolesMsg.replace(0, 1, ""); failedMsgList.add(new StringBuilder().append(nodeGroup.getName()) .append(".").append("roles=").append("\"") .append(rolesMsg.toString()).append("\"").toString()); } return validated; } private List<String> findDistroRoles(ClusterCreate clusterCreate) { DistroRead distroRead = null; distroRead = distroRestClient .get(clusterCreate.getDistro() != null ? clusterCreate .getDistro() : Constants.DEFAULT_DISTRO); if (distroRead != null) { return distroRead.getRoles(); } else { return null; } } private void showFailedMsg(String name, List<String> failedMsgList) { //cluster creation failed message. StringBuilder failedMsg = new StringBuilder(); failedMsg.append(Constants.INVALID_VALUE); if (failedMsgList.size() > 1) { failedMsg.append("s"); } failedMsg.append(" "); StringBuilder tmpMsg = new StringBuilder(); for (String msg : failedMsgList) { tmpMsg.append(",").append(msg); } tmpMsg.replace(0, 1, ""); failedMsg.append(tmpMsg); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, failedMsg.toString()); } private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) { // validate blacklist ValidateResult blackListResult = validateBlackList(cluster); if (blackListResult != null) { addBlackListWarning(blackListResult, warningMsgList); } if (!skipConfigValidation) { // validate whitelist ValidateResult whiteListResult = validateWhiteList(cluster); addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList); } else { cluster.setValidateConfig(false); } } private ValidateResult validateBlackList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.BLACK_LIST); } private ValidateResult validateWhiteList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.WHITE_LIST); } private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) { ValidateResult validateResult = new ValidateResult(); // validate cluster level Configuration ValidateResult vr = null; if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); validateResult.setFailureNames(vr.getFailureNames()); } } // validate nodegroup level Configuration for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) { if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); List<String> failureNames = new LinkedList<String>(); failureNames.addAll(validateResult.getFailureNames()); for (String name : vr.getFailureNames()) { if (!failureNames.contains(name)) { failureNames.add(name); } } validateResult.setFailureNames(vr.getFailureNames()); } } } return validateResult; } private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult, List<String> warningMsgList) { if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) { String warningMsg = getValidateWarningMsg(whiteListResult.getFailureNames(), Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING); if (warningMsgList != null) { warningMsgList.add(warningMsg); } } } private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) { if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) { String warningMsg = getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING); if (warningList != null) warningList.add(warningMsg); } } private String getValidateWarningMsg(List<String> failureNames, String warningMsg) { StringBuilder warningMsgBuff = new StringBuilder(); if (failureNames != null && !failureNames.isEmpty()) { warningMsgBuff.append("Warning: "); for (String failureName : failureNames) { warningMsgBuff.append(failureName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (failureNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append(warningMsg); } return warningMsgBuff.toString(); } private boolean showWarningMsg(String clusterName, List<String> warningMsgList) { if (warningMsgList != null && !warningMsgList.isEmpty()) { for (String message : warningMsgList) { System.out.println(message); } if (!isContinue(clusterName, Constants.OUTPUT_OP_CREATE, Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) { return false; } } return true; } private boolean isHAFlag(NodeGroupCreate nodeGroupCreate) { return !CommandsUtils.isBlank(nodeGroupCreate.getHaFlag()) && !nodeGroupCreate.getHaFlag().equalsIgnoreCase("off"); } private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) { List<String> haFlagList = Arrays.asList("off","on","ft"); if (nodeGroups != null){ for(NodeGroupCreate group : nodeGroups){ if (!haFlagList.contains(group.getHaFlag().toLowerCase())){ return false; } } } return true; } }
public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "Hadoop Distro") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName, @CliOption(key = { "topology" }, mandatory = false, help = "Please specify the topology type: HVE or RACK_HOST or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { this.alwaysAnswerYes = alwaysAnswerYes; //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } //process resume if (resume) { resumeCreateCluster(name); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "type=" + type); return; } clusterCreate.setType(clusterType); } if (topology != null) { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException ex) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } } else { clusterCreate.setTopologyPolicy(null); } if (distro != null) { List<String> distroNames = getDistroNames(); if (validName(distro, distroNames)) { clusterCreate.setDistro(distro); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + distroNames); return; } } if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> warningMsgList = new ArrayList<String>(); List<String> networkNames = null; try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList); if (!validateHAInfo(clusterCreate.getNodeGroups())){ CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } } networkNames = getNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (networkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED); return; } else { if (networkName != null) { if (validName(networkName, networkNames)) { clusterCreate.setNetworkName(networkName); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + networkNames); return; } } else { if (networkNames.size() == 1) { clusterCreate.setNetworkName(networkNames.get(0)); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } } // Validate that the specified file is correct json format and proper value. if (specFilePath != null) { if (!validateClusterCreate(clusterCreate)) { return; } } // process topology option if (topology == null) { clusterCreate.setTopologyPolicy(TopologyType.NONE); } else { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_TOPOLOGY_INVALID_VALUE); System.out.println("Please specify the topology type: HVE or RACK_HOST or HOST_AS_RACK"); return; } } // rest invocation try { if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) { return; } restClient.create(clusterCreate); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster list", help = "Get cluster information") public void getCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { ClusterRead[] clusters = restClient.getAll(); if (clusters != null) { prettyOutputClustersInfo(clusters, detail); } } else { ClusterRead cluster = restClient.get(name); if (cluster != null) { prettyOutputClusterInfo(cluster, detail); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster export --spec", help = "Export cluster specification") public void exportClusterSpec( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) { // rest invocation try { ClusterCreate cluster = restClient.getSpec(name); if (cluster != null) { CommandsUtils.prettyJsonOutput(cluster, fileName); } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster delete", help = "Delete a cluster") public void deleteCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_DELETE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster start", help = "Start a cluster") public void startCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings .put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START); //rest invocation try { if (!validateNodeGroupName(nodeGroupName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node group name"); return; } if (!validateNodeName(clusterName, nodeGroupName, nodeName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node name"); return; } String groupName = nodeGroupName; String fullNodeName = nodeName; if (nodeName != null) { if (nodeGroupName == null) { groupName = extractNodeGroupName(nodeName); if (groupName == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, "missing node group name"); return; } } else { fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName); } } String resource = getClusterResourceName(clusterName, groupName, fullNodeName); if (resource != null) { restClient.actionOps(resource, clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_START); } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster stop", help = "Stop a cluster") public void stopCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroupName" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "nodeName" }, mandatory = false, help = "The node name") final String nodeName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP); //rest invocation try { if (!validateNodeGroupName(nodeGroupName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node group name"); return; } if (!validateNodeName(clusterName, nodeGroupName, nodeName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "invalid node name"); return; } String groupName = nodeGroupName; String fullNodeName = nodeName; if (nodeName != null) { if (nodeGroupName == null) { groupName = extractNodeGroupName(nodeName); if (groupName == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, "missing node group name"); return; } } else { fullNodeName = autoCompleteNodeName(clusterName, nodeGroupName, nodeName); } } String resource = getClusterResourceName(clusterName, groupName, fullNodeName); if (resource != null) { restClient.actionOps(resource, clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_STOP); } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster resize", help = "Resize a cluster") public void resizeCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup, @CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) { if (instanceNum > 1) { try { restClient.resize(name, nodeGroup, instanceNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESIZE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " instanceNum=" + instanceNum); } } @CliCommand(value = "cluster limit", help = "Set number of instances powered on in a node group") public void limitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "activeComputeNodeNum" }, mandatory = true, help = "The number of instances powered on") final int activeComputeNodeNum) { try { // The active compute node number must be a integer and cannot be less than zero. if (activeComputeNodeNum < 0) { System.out.println("Invalid instance number:" + activeComputeNodeNum); return; } ClusterRead cluster = restClient.get(clusterName); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName, activeComputeNodeNum)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster target", help = "Set or query target cluster to run commands") public void targetCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) { ClusterRead cluster = null; try { if (info) { if (name != null) { System.out.println("Warning: can't specify option --name and --info at the same time"); return; } String fsUrl = hadoopConfiguration.get("fs.default.name"); String jtUrl = hadoopConfiguration.get("mapred.job.tracker"); if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) { System.out.println("There is no targeted cluster. Please use \"cluster target --name\" to target first"); return; } if(targetClusterName != null && targetClusterName.length() > 0){ System.out.println("Cluster : " + targetClusterName); } if (fsUrl != null && fsUrl.length() > 0) { System.out.println("HDFS url : " + fsUrl); } if (jtUrl != null && jtUrl.length() > 0) { System.out.println("Job Tracker url : " + jtUrl); } if (hiveInfo != null && hiveInfo.length() > 0) { System.out.println("Hive server info: " + hiveInfo); } } else { if (name == null) { ClusterRead[] clusters = restClient.getAll(); if (clusters != null && clusters.length > 0) { cluster = clusters[0]; } } else { cluster = restClient.get(name); } if (cluster == null) { System.out.println("Failed to target cluster: The cluster " + name + "is not found"); setFsURL(""); setJobTrackerURL(""); this.setHiveServer(""); } else { targetClusterName = cluster.getName(); for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) { for (String role : nodeGroup.getRoles()) { if (role.equals("hadoop_namenode")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String nameNodeIP = nodes.get(0).getIp(); setNameNode(nameNodeIP); } else { throw new CliRestException("no name node available"); } } if (role.equals("hadoop_jobtracker")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String jobTrackerIP = nodes.get(0).getIp(); setJobTracker(jobTrackerIP); } else { throw new CliRestException("no job tracker available"); } } if (role.equals("hive_server")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String hiveServerIP = nodes.get(0).getIp(); setHiveServer(hiveServerIP); } else { throw new CliRestException("no hive server available"); } } } } if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { setFsURL(cluster.getExternalHDFS()); } } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); setFsURL(""); setJobTrackerURL(""); this.setHiveServer(""); } } private void setNameNode(String nameNodeAddress) { String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020"; setFsURL(hdfsUrl); } private void setFsURL(String fsURL) { hadoopConfiguration.set("fs.default.name", fsURL); } private void setJobTracker(String jobTrackerAddress) { String jobTrackerUrl = jobTrackerAddress + ":8021"; setJobTrackerURL(jobTrackerUrl); } private void setJobTrackerURL(String jobTrackerUrl){ hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl); } private void setHiveServer(String hiveServerAddress) { try { hiveInfo = hiveCommands.config(hiveServerAddress, 10000, null); } catch (Exception e) { throw new CliRestException("faild to set hive server address"); } } @CliCommand(value = "cluster config", help = "Config an existing cluster") public void configCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { this.alwaysAnswerYes = alwaysAnswerYes; //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } try { ClusterRead clusterRead = restClient.get(name); // build ClusterCreate object ClusterCreate clusterConfig = new ClusterCreate(); clusterConfig.setName(clusterRead.getName()); ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterConfig.setNodeGroups(clusterSpec.getNodeGroups()); clusterConfig.setConfiguration(clusterSpec.getConfiguration()); clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS()); List<String> warningMsgList = new ArrayList<String>(); validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList); // add a confirm message for running job warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING); if (!showWarningMsg(clusterConfig.getName(), warningMsgList)) { return; } restClient.configCluster(clusterConfig); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } } private String getClusterResourceName(String cluster, String nodeGroup, String node) { assert cluster != null; // Spring shell guarantees this if (node != null && nodeGroup == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, cluster, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, Constants.OUTPUT_OP_NODEGROUP_MISSING); return null; } StringBuilder res = new StringBuilder(); res.append(cluster); if (nodeGroup != null) { res.append("/nodegroup/").append(nodeGroup); if (node != null) { res.append("/node/").append(node); } } return res.toString(); } private boolean validateNodeName(String cluster, String group, String node) { if (node != null) { String[] parts = node.split("-"); if (parts.length == 1) { return true; } if (parts.length == 3) { if (!parts[0].equals(cluster)) { return false; } if (group != null && !parts[1].equals(group)) { return false; } return true; } return false; } return true; } private boolean validateNodeGroupName(String group) { if (group != null) { return group.indexOf("-") == -1; } return true; } private String autoCompleteNodeName(String cluster, String group, String node) { assert cluster != null; assert group != null; assert node != null; if (node.indexOf("-") == -1) { StringBuilder sb = new StringBuilder(); sb.append(cluster).append("-").append(group).append("-").append(node); return sb.toString(); } return node; } private String extractNodeGroupName(String node) { String[] parts = node.split("-"); if (parts.length == 3) { return parts[1]; } return null; } private void resumeCreateCluster(final String name) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_RESUME); try { restClient.actionOps(name, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESUME); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> getNetworkNames() { List<String> networkNames = new ArrayList<String>(0); NetworkRead[] networks = networkRestClient.getAll(false); if (networks != null) { for (NetworkRead network : networks) networkNames.add(network.getName()); } return networkNames; } private List<String> getDistroNames() { List<String> distroNames = new ArrayList<String>(0); DistroRead[] distros = distroRestClient.getAll(); if (distros != null) { for (DistroRead distro : distros) distroNames.add(distro.getName()); } return distroNames; } private boolean validName(String inputName, List<String> validNames) { for (String name : validNames) { if (name.equals(inputName)) { return true; } } return false; } private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) { TopologyType topology = cluster.getTopologyPolicy(); if (topology == null || topology == TopologyType.NONE) { System.out.printf("name: %s, distro: %s, status: %s", cluster.getName(), cluster.getDistro(), cluster.getStatus()); } else { System.out.printf("name: %s, distro: %s, topology: %s, status: %s", cluster.getName(), cluster.getDistro(), topology, cluster.getStatus()); } System.out.println(); if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS()); } LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); List<NodeGroupRead> nodegroups = cluster.getNodeGroups(); if (nodegroups != null) { ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_INSTANCE, Arrays.asList("getInstanceNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU, Arrays.asList("getCpuNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM, Arrays.asList("getMemCapacityMB")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("getStorage", "getType")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_SIZE, Arrays.asList("getStorage", "getSizeGB")); try { if (detail) { LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); if (topology == TopologyType.RACK_AS_RACK || topology == TopologyType.HVE) { nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_RACK, Arrays.asList("getRack")); } nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_HOST, Arrays.asList("getHostName")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_STATUS, Arrays.asList("getStatus")); for (NodeGroupRead nodegroup : nodegroups) { CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, new NodeGroupRead[] { nodegroup }, Constants.OUTPUT_INDENT); List<NodeRead> nodes = nodegroup.getInstances(); if (nodes != null) { System.out.println(); CommandsUtils.printInTableFormat( nColumnNamesWithGetMethodNames, nodes.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } System.out.println(); } } else CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, nodegroups.toArray(), Constants.OUTPUT_INDENT); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, cluster.getName(), Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) { for (ClusterRead cluster : clusters) { prettyOutputClusterInfo(cluster, detail); System.out.println(); } } /** * Validate nodeGroupCreates member formats and values in the ClusterCreate. */ private boolean validateClusterCreate(ClusterCreate clusterCreate) { // validation status boolean validated = true; // show warning message boolean warning = false; //role count int masterCount = 0, workerCount = 0, clientCount = 0; //Find NodeGroupCreate array from current ClusterCreate instance. NodeGroupCreate[] nodeGroupCreates = clusterCreate.getNodeGroups(); if (nodeGroupCreates == null || nodeGroupCreates.length == 0) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.MULTI_INPUTS_CHECK); return !validated; } else { //used for collecting failed message. List<String> failedMsgList = new LinkedList<String>(); List<String> warningMsgList = new LinkedList<String>(); //find distro roles. List<String> distroRoles = findDistroRoles(clusterCreate); if (distroRoles == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NO_DISTRO_AVAILABLE); return !validated; } if (nodeGroupCreates.length < 2 || nodeGroupCreates.length > 5) { warningMsgList.add(Constants.PARAM_CLUSTER_WARNING); warning = true; } // check external HDFS if (clusterCreate.hasHDFSUrlConfigured() && !clusterCreate.validateHDFSUrl()) { failedMsgList.add(new StringBuilder() .append("externalHDFS=") .append(clusterCreate.getExternalHDFS()).toString()); validated = false; } // check placement policies if (!clusterCreate.validateNodeGroupPlacementPolicies(failedMsgList, warningMsgList)) { validated = false; } if (!clusterCreate.validateNodeGroupRoles(failedMsgList)) { validated = false; } for (NodeGroupCreate nodeGroupCreate : nodeGroupCreates) { // check node group's instanceNum if (!checkInstanceNum(nodeGroupCreate, failedMsgList)) { validated = false; } // check node group's roles if (!checkNodeGroupRoles(nodeGroupCreate, distroRoles, failedMsgList)) { validated = false; } // get node group role . NodeGroupRole role = getNodeGroupRole(nodeGroupCreate); switch (role) { case MASTER: masterCount++; if (nodeGroupCreate.getInstanceNum() >= 0 && nodeGroupCreate.getInstanceNum() != 1) { validated = false; collectInstanceNumInvalidateMsg(nodeGroupCreate, failedMsgList); } break; case WORKER: workerCount++; if (nodeGroupCreate.getInstanceNum() == 0) { validated = false; collectInstanceNumInvalidateMsg(nodeGroupCreate, failedMsgList); } else if (isHAFlag(nodeGroupCreate)) { warning = true; } break; case CLIENT: clientCount++; if (isHAFlag(nodeGroupCreate)) { warning = true; } break; case NONE: warning = true; break; default: } } if ((masterCount < 1 || masterCount > 2) || (workerCount < 1 || workerCount > 2) || clientCount > 1) { warning = true; } if (!validated) { showFailedMsg(clusterCreate.getName(), failedMsgList); } else if (warning || warningMsgList != null) { // If warning is true,show waring message. if (!showWarningMsg(clusterCreate.getName(), warningMsgList)) { // When exist warning message,whether to proceed validated = false; } } return validated; } } private boolean isContinue(String clusterName, String operateType, String promptMsg) { if (this.alwaysAnswerYes) { return true; } boolean continueCreate = true; boolean continueLoop = true; String readMsg = ""; try { ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setDefaultPrompt(promptMsg); int k = 0; while (continueLoop) { if (k >= 3) { continueCreate = false; break; } // Read user input readMsg = reader.readLine(); if (readMsg.trim().equalsIgnoreCase("yes") || readMsg.trim().equalsIgnoreCase("y")) { continueLoop = false; } else if (readMsg.trim().equalsIgnoreCase("no") || readMsg.trim().equalsIgnoreCase("n")) { continueLoop = false; continueCreate = false; } else { k++; } } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, clusterName, operateType, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); continueCreate = false; } return continueCreate; } private NodeGroupRole getNodeGroupRole(NodeGroupCreate nodeGroupCreate) { //Find roles list from current NodeGroupCreate instance. List<String> roles = nodeGroupCreate.getRoles(); for (NodeGroupRole role : NodeGroupRole.values()) { if (matchRole(role, roles)) { return role; } } return NodeGroupRole.NONE; } /** * Check the roles was introduced, whether matching with system's specialize * role. */ private boolean matchRole(NodeGroupRole role, List<String> roles) { List<String> matchRoles = new LinkedList<String>(); switch (role) { case MASTER: if (roles.size() == 1) { String r = roles.get(0); return Constants.ROLE_HADOOP_NAME_NODE.equals(r) || Constants.ROLE_HADOOP_JOB_TRACKER.equals(r); } else if (roles.size() == 2) { matchRoles.add(Constants.ROLE_HADOOP_NAME_NODE); matchRoles.add(Constants.ROLE_HADOOP_JOB_TRACKER); matchRoles.removeAll(roles); return matchRoles.size() == 0 ? true : false; } return false; case WORKER: if (roles.size() == 1) { if (Constants.ROLE_HADOOP_DATANODE.equals(roles.get(0)) || Constants.ROLE_HADOOP_TASKTRACKER.equals(roles.get(0))) { return true; } return false; } else { matchRoles.add(Constants.ROLE_HADOOP_DATANODE); matchRoles.add(Constants.ROLE_HADOOP_TASKTRACKER); matchRoles.removeAll(roles); return matchRoles.size() == 0 ? true : false; } case CLIENT: if (roles.size() < 1 || roles.size() > 4) { return false; } else { matchRoles.add(Constants.ROLE_HADOOP_CLIENT); matchRoles.add(Constants.ROLE_HIVE); matchRoles.add(Constants.ROLE_HIVE_SERVER); matchRoles.add(Constants.ROLE_PIG); int diffNum = matchRoles.size() - roles.size(); matchRoles.removeAll(roles); return roles.contains(Constants.ROLE_HADOOP_CLIENT) && (diffNum >= 0) && (diffNum == matchRoles.size()) ? true : false; } } return false; } private void showWarningMsg() { System.out.println(Constants.PARAM_CLUSTER_WARNING); } private boolean checkInstanceNum(NodeGroupCreate nodeGroup, List<String> failedMsgList) { boolean validated = true; if (nodeGroup.getInstanceNum() < 0) { validated = false; collectInstanceNumInvalidateMsg(nodeGroup, failedMsgList); } return validated; } private void collectInstanceNumInvalidateMsg(NodeGroupCreate nodeGroup, List<String> failedMsgList) { failedMsgList.add(new StringBuilder().append(nodeGroup.getName()) .append(".").append("instanceNum=") .append(nodeGroup.getInstanceNum()).toString()); } private boolean checkNodeGroupRoles(NodeGroupCreate nodeGroup, List<String> distroRoles, List<String> failedMsgList) { List<String> roles = nodeGroup.getRoles(); boolean validated = true; StringBuilder rolesMsg = new StringBuilder(); for (String role : roles) { if (!distroRoles.contains(role)) { validated = false; rolesMsg.append(",").append(role); } } if (!validated) { rolesMsg.replace(0, 1, ""); failedMsgList.add(new StringBuilder().append(nodeGroup.getName()) .append(".").append("roles=").append("\"") .append(rolesMsg.toString()).append("\"").toString()); } return validated; } private List<String> findDistroRoles(ClusterCreate clusterCreate) { DistroRead distroRead = null; distroRead = distroRestClient .get(clusterCreate.getDistro() != null ? clusterCreate .getDistro() : Constants.DEFAULT_DISTRO); if (distroRead != null) { return distroRead.getRoles(); } else { return null; } } private void showFailedMsg(String name, List<String> failedMsgList) { //cluster creation failed message. StringBuilder failedMsg = new StringBuilder(); failedMsg.append(Constants.INVALID_VALUE); if (failedMsgList.size() > 1) { failedMsg.append("s"); } failedMsg.append(" "); StringBuilder tmpMsg = new StringBuilder(); for (String msg : failedMsgList) { tmpMsg.append(",").append(msg); } tmpMsg.replace(0, 1, ""); failedMsg.append(tmpMsg); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, failedMsg.toString()); } private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) { // validate blacklist ValidateResult blackListResult = validateBlackList(cluster); if (blackListResult != null) { addBlackListWarning(blackListResult, warningMsgList); } if (!skipConfigValidation) { // validate whitelist ValidateResult whiteListResult = validateWhiteList(cluster); addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList); } else { cluster.setValidateConfig(false); } } private ValidateResult validateBlackList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.BLACK_LIST); } private ValidateResult validateWhiteList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.WHITE_LIST); } private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) { ValidateResult validateResult = new ValidateResult(); // validate cluster level Configuration ValidateResult vr = null; if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); validateResult.setFailureNames(vr.getFailureNames()); } } // validate nodegroup level Configuration for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) { if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); List<String> failureNames = new LinkedList<String>(); failureNames.addAll(validateResult.getFailureNames()); for (String name : vr.getFailureNames()) { if (!failureNames.contains(name)) { failureNames.add(name); } } validateResult.setFailureNames(vr.getFailureNames()); } } } return validateResult; } private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult, List<String> warningMsgList) { if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) { String warningMsg = getValidateWarningMsg(whiteListResult.getFailureNames(), Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING); if (warningMsgList != null) { warningMsgList.add(warningMsg); } } } private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) { if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) { String warningMsg = getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING); if (warningList != null) warningList.add(warningMsg); } } private String getValidateWarningMsg(List<String> failureNames, String warningMsg) { StringBuilder warningMsgBuff = new StringBuilder(); if (failureNames != null && !failureNames.isEmpty()) { warningMsgBuff.append("Warning: "); for (String failureName : failureNames) { warningMsgBuff.append(failureName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (failureNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append(warningMsg); } return warningMsgBuff.toString(); } private boolean showWarningMsg(String clusterName, List<String> warningMsgList) { if (warningMsgList != null && !warningMsgList.isEmpty()) { for (String message : warningMsgList) { System.out.println(message); } if (!isContinue(clusterName, Constants.OUTPUT_OP_CREATE, Constants.PARAM_PROMPT_CONTINUE_MESSAGE)) { return false; } } return true; } private boolean isHAFlag(NodeGroupCreate nodeGroupCreate) { return !CommandsUtils.isBlank(nodeGroupCreate.getHaFlag()) && !nodeGroupCreate.getHaFlag().equalsIgnoreCase("off"); } private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) { List<String> haFlagList = Arrays.asList("off","on","ft"); if (nodeGroups != null){ for(NodeGroupCreate group : nodeGroups){ if (!haFlagList.contains(group.getHaFlag().toLowerCase())){ return false; } } } return true; } }
diff --git a/src/com/denerosarmy/inventory/Item.java b/src/com/denerosarmy/inventory/Item.java index 14d7730..49c43d3 100755 --- a/src/com/denerosarmy/inventory/Item.java +++ b/src/com/denerosarmy/inventory/Item.java @@ -1,82 +1,82 @@ package com.denerosarmy.inventory; import java.util.Date; import android.view.animation.Animation; public class Item implements Comparable { private String id; private String name; private String compId; private Integer pic; public boolean isNew; public boolean toBeDeleted; private Date created; public Item(String id, String name, Integer pic){ this.id = id; this.name = name; this.pic = pic; this.isNew = true; this.toBeDeleted = false; this.created = new Date(); Container.inst().addItem(this); } protected void putInto(String compId){ this.compId = compId; Container.inst().getComp(compId).putItem(this); } protected void remove(){ Container.inst().getComp(compId).popItem(this.getId()); this.compId = null; } protected void scheduleDeletion() { this.toBeDeleted = true; } - protected void flip() { + protected String flip() { System.out.println("FLIP CALLED FLIP CALLED"); if (inContainer()) { scheduleDeletion(); return name + " removed from bag"; } else { putInto("1"); return name + " entered bag"; } } protected String getId(){ return this.id; } protected String getName(){ return this.name; } protected Integer getPic(){ return this.pic; } protected Compartment getComp(){ if (this.compId == null){ return null; } return Container.inst().getComp(this.compId); } protected boolean inContainer(){ return this.compId != null; } public int compareTo(Object other) throws ClassCastException { if (!(other instanceof Item)) throw new ClassCastException("An Item object expected."); return ((Date) this.created).compareTo((Date) ((Item) other).created); } }
true
true
protected void flip() { System.out.println("FLIP CALLED FLIP CALLED"); if (inContainer()) { scheduleDeletion(); return name + " removed from bag"; } else { putInto("1"); return name + " entered bag"; } }
protected String flip() { System.out.println("FLIP CALLED FLIP CALLED"); if (inContainer()) { scheduleDeletion(); return name + " removed from bag"; } else { putInto("1"); return name + " entered bag"; } }
diff --git a/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/steps/HTSAnnotationStep.java b/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/steps/HTSAnnotationStep.java index 9ec91ed1f..83f176cf9 100644 --- a/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/steps/HTSAnnotationStep.java +++ b/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/steps/HTSAnnotationStep.java @@ -1,150 +1,151 @@ package uk.ac.ebi.gxa.loader.steps; import com.google.common.io.Files; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.arrayexpress2.magetab.datamodel.MAGETABInvestigation; import uk.ac.ebi.gxa.data.AtlasDataDAO; import uk.ac.ebi.gxa.loader.AtlasLoaderException; import uk.ac.ebi.gxa.loader.service.GeneAnnotationFormatConverterService; import uk.ac.ebi.gxa.utils.StringUtil; import uk.ac.ebi.microarray.atlas.model.Experiment; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Collection; /** * This class deals with: * 1. Conversion of .gtf file corresponding to HTS experiment's species into a format that can be handled by WiggleRequestHandler. * The converted file (with .anno extension) is then put into <ncdf_dir>/<experiment_accession>/annotations directory. * 2. Copying of accepted_hits.sorted.bam files from HTS processing directory into <ncdf_dir>/<experiment_accession>/assays directory. * <p/> * Both types of file are needed for the user to be able to view genes from HTS experiments on Ensembl genome browser. * * @author rpetry */ public class HTSAnnotationStep { private final static Logger log = LoggerFactory.getLogger(HTSAnnotationStep.class); private final static String ANNOTATIONS = "annotations"; private final static String ASSAYS = "assays"; private final static String ASSAY_PROCESSING_DIRS_PATTERN = "*RR*"; private final static String TOPHAT_OUT = "tophat_out"; private final static String BAM = "accepted_hits.sorted.bam"; private final static String GTF_EXT_PATTERN = ".gtf$"; private final static String ANNO_EXT_PATTERN = ".anno"; public static String displayName() { return "Fetching HTS experiment's annotations and BAM files"; } /** * Populates into experiment's ncdf directory a .gtf annotation file (needed by WiggleRequestHandler) corresponding to the first species associated with experiment * for which such .gtf file exists in experiment's HTS processing directory (N.B. assumptions below) * <p/> * Assumptions: * 1. Processed HTS experiment's sdrf file resides in <processing_dir>/<experiment_accession>/data/<experiment_accession>.sdrf.txt * 2. <processing_dir> contains a soft link, ANNOTATIONS, pointing to a directory containing .gtf files corresponding to all species needed to load HTS-experiments into Atlas. * The files inside <processing_dir>/<experiment_accession>/ANNOTATIONS are e.g. Caenorhabditis_elegans.WS220.65.gtf where 65 is the release number * of the Ensembl release against which experiment was processed. To avoid confusion only one Ensembl release's gtf file is allowed to be stored in <processing_dir>/ANNOTATIONS * per species (an error will be thrown otherwise) * * @param experiment * @param investigation * @param atlasDataDAO * @throws AtlasLoaderException if * 1. <ncdf_dir>/<experiment_acc>/ANNOTATIONS dir does not exist and could not be created; * 2. <processing_dir>/<experiment_accession>/ANNOTATIONS directory does not exist * 3. More than one <processing_dir>/<experiment_accession>/ANNOTATIONS/.gtf file exists for a given experiment's species (it could be * that more than one Ensembl release's gtf files are stored under <processing_dir>/<experiment_accession>/ANNOTATIONS; this leads to error * as we need to be sure which Ensembl release we are loading annotations for) * 4. There was an error copying a gtf file from <processing_dir>/<experiment_accession>/ANNOTATIONS/ to <ncdf_dir>/<experiment_acc>/ANNOTATIONS * 5. No .gtf files were found for any of the experiment's species */ public void populateAnnotationsForSpecies(MAGETABInvestigation investigation, Experiment experiment, AtlasDataDAO atlasDataDAO) throws AtlasLoaderException { Collection<String> species = experiment.getSpecies(); File sdrfFilePath = new File(investigation.SDRF.getLocation().getFile()); File htsAnnotationsDir = new File(sdrfFilePath.getParentFile().getParentFile(), ANNOTATIONS); if (!htsAnnotationsDir.exists()) throw new AtlasLoaderException("Cannot find " + htsAnnotationsDir.getAbsolutePath() + "folder to retrieve annotations from for experiment: " + experiment.getAccession()); boolean found = false; for (String specie : species) { + if (found) + continue; String encodedSpecies = StringUtil.upcaseFirst(specie.replaceAll(" ", "_")); FileFilter fileFilter = new WildcardFileFilter(encodedSpecies + "*" + ".gtf"); File[] files = htsAnnotationsDir.listFiles(fileFilter); File experimentAnnotationsDir = null; try { experimentAnnotationsDir = new File(atlasDataDAO.getDataDirectory(experiment), ANNOTATIONS); if (!experimentAnnotationsDir.exists() && !experimentAnnotationsDir.mkdirs()) { throw new AtlasLoaderException("Cannot create folder to insert annotations into for experiment: " + experiment.getAccession()); } if (files.length == 1) { GeneAnnotationFormatConverterService.transferAnnotation(files[0], new File(experimentAnnotationsDir, files[0].getName().replaceAll(GTF_EXT_PATTERN, ANNO_EXT_PATTERN))); found = true; } else if (files.length > 0) { throw new AtlasLoaderException("More than one file in Gene Annotation Format (.gtf) exists in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession() + " and species: " + specie); } } catch (IOException ioe) { throw new AtlasLoaderException("Error copying annotations from: " + files[0].getAbsolutePath() + " to: " + experimentAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession(), ioe); } - log.warn("Failed to find any files in Gene Annotation Format (.gtf) in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession() + " and species: " + specie); } if (!found) throw new AtlasLoaderException("Failed to find any files in Gene Annotation Format (.gtf) in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession()); } /** * Populates into experiment's ncdf directory a BAM file (needed by WiggleRequestHandler) for each of experiment's assays. * <p/> * Assumptions: * 1. Processed HTS experiment's sdrf file resides in <processing_dir>/<experiment_accession>/data/<experiment_accession>.sdrf.txt * 2. <processing_dir>&#47;*RR*&#47;TOPHAT_OUT/BAM pattern pick out BAM files for all assays that were processed for experiment. * * @param experiment * @param investigation * @param atlasDataDAO * @throws AtlasLoaderException if * 1. <processing_dir> does not exist * 2. A given <processing_dir>/<assay_id> (matching pattern <processing_dir>&#47;*RR*&#47;) processing directory does not contain a BAM file * 3. There was an error copying a BAM file from <processing_dir>&#47;*RR*&#47;TOPHAT_OUT/BAM to <ncdf_dir>/<experiment_acc>/ASSAYS * 4. No <processing_dir>/<assay_id> matching pattern <processing_dir>&#47;*RR*&#47; was found. */ public void populateBams(MAGETABInvestigation investigation, Experiment experiment, AtlasDataDAO atlasDataDAO) throws AtlasLoaderException { File sdrfFilePath = new File(investigation.SDRF.getLocation().getFile()); File htsProcessingDir = sdrfFilePath.getParentFile().getParentFile(); if (!htsProcessingDir.exists()) throw new AtlasLoaderException("Cannot find " + htsProcessingDir.getAbsolutePath() + "folder to retrieve BAM files from for experiment: " + experiment.getAccession()); FileFilter dirFilter = new WildcardFileFilter(ASSAY_PROCESSING_DIRS_PATTERN); File[] dirs = htsProcessingDir.listFiles(dirFilter); if (dirs.length == 0) throw new AtlasLoaderException("Failed to find any assay processing directories matching pattern: " + ASSAY_PROCESSING_DIRS_PATTERN + " in: " + htsProcessingDir.getAbsolutePath() + " for experiment: " + experiment.getAccession()); for (int i = 0; i < dirs.length; i++) { File bamFile = new File(new File(dirs[i], TOPHAT_OUT), BAM); if (!bamFile.exists()) throw new AtlasLoaderException("BAM file: + " + bamFile.getAbsolutePath() + "does not exist for experiment: " + experiment.getAccession() + " and assay: " + dirs[i]); File toFile = null; try { File experimentAssaysDir = new File(atlasDataDAO.getDataDirectory(experiment), ASSAYS); toFile = new File(experimentAssaysDir, new File(dirs[i].getName(), bamFile.getName()).getPath()); Files.createParentDirs(toFile); Files.copy(bamFile, toFile); } catch (IOException ioe) { throw new AtlasLoaderException("Error copying BAM file from: " + bamFile.getAbsolutePath() + (toFile != null ? " to: " + toFile.getAbsolutePath() : "") + " for experiment: " + experiment.getAccession(), ioe); } } } }
false
true
public void populateAnnotationsForSpecies(MAGETABInvestigation investigation, Experiment experiment, AtlasDataDAO atlasDataDAO) throws AtlasLoaderException { Collection<String> species = experiment.getSpecies(); File sdrfFilePath = new File(investigation.SDRF.getLocation().getFile()); File htsAnnotationsDir = new File(sdrfFilePath.getParentFile().getParentFile(), ANNOTATIONS); if (!htsAnnotationsDir.exists()) throw new AtlasLoaderException("Cannot find " + htsAnnotationsDir.getAbsolutePath() + "folder to retrieve annotations from for experiment: " + experiment.getAccession()); boolean found = false; for (String specie : species) { String encodedSpecies = StringUtil.upcaseFirst(specie.replaceAll(" ", "_")); FileFilter fileFilter = new WildcardFileFilter(encodedSpecies + "*" + ".gtf"); File[] files = htsAnnotationsDir.listFiles(fileFilter); File experimentAnnotationsDir = null; try { experimentAnnotationsDir = new File(atlasDataDAO.getDataDirectory(experiment), ANNOTATIONS); if (!experimentAnnotationsDir.exists() && !experimentAnnotationsDir.mkdirs()) { throw new AtlasLoaderException("Cannot create folder to insert annotations into for experiment: " + experiment.getAccession()); } if (files.length == 1) { GeneAnnotationFormatConverterService.transferAnnotation(files[0], new File(experimentAnnotationsDir, files[0].getName().replaceAll(GTF_EXT_PATTERN, ANNO_EXT_PATTERN))); found = true; } else if (files.length > 0) { throw new AtlasLoaderException("More than one file in Gene Annotation Format (.gtf) exists in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession() + " and species: " + specie); } } catch (IOException ioe) { throw new AtlasLoaderException("Error copying annotations from: " + files[0].getAbsolutePath() + " to: " + experimentAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession(), ioe); } log.warn("Failed to find any files in Gene Annotation Format (.gtf) in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession() + " and species: " + specie); } if (!found) throw new AtlasLoaderException("Failed to find any files in Gene Annotation Format (.gtf) in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession()); }
public void populateAnnotationsForSpecies(MAGETABInvestigation investigation, Experiment experiment, AtlasDataDAO atlasDataDAO) throws AtlasLoaderException { Collection<String> species = experiment.getSpecies(); File sdrfFilePath = new File(investigation.SDRF.getLocation().getFile()); File htsAnnotationsDir = new File(sdrfFilePath.getParentFile().getParentFile(), ANNOTATIONS); if (!htsAnnotationsDir.exists()) throw new AtlasLoaderException("Cannot find " + htsAnnotationsDir.getAbsolutePath() + "folder to retrieve annotations from for experiment: " + experiment.getAccession()); boolean found = false; for (String specie : species) { if (found) continue; String encodedSpecies = StringUtil.upcaseFirst(specie.replaceAll(" ", "_")); FileFilter fileFilter = new WildcardFileFilter(encodedSpecies + "*" + ".gtf"); File[] files = htsAnnotationsDir.listFiles(fileFilter); File experimentAnnotationsDir = null; try { experimentAnnotationsDir = new File(atlasDataDAO.getDataDirectory(experiment), ANNOTATIONS); if (!experimentAnnotationsDir.exists() && !experimentAnnotationsDir.mkdirs()) { throw new AtlasLoaderException("Cannot create folder to insert annotations into for experiment: " + experiment.getAccession()); } if (files.length == 1) { GeneAnnotationFormatConverterService.transferAnnotation(files[0], new File(experimentAnnotationsDir, files[0].getName().replaceAll(GTF_EXT_PATTERN, ANNO_EXT_PATTERN))); found = true; } else if (files.length > 0) { throw new AtlasLoaderException("More than one file in Gene Annotation Format (.gtf) exists in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession() + " and species: " + specie); } } catch (IOException ioe) { throw new AtlasLoaderException("Error copying annotations from: " + files[0].getAbsolutePath() + " to: " + experimentAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession(), ioe); } } if (!found) throw new AtlasLoaderException("Failed to find any files in Gene Annotation Format (.gtf) in " + htsAnnotationsDir.getAbsolutePath() + " for experiment: " + experiment.getAccession()); }
diff --git a/src/test/java/com/wikia/webdriver/Common/DriverProvider/DriverProvider.java b/src/test/java/com/wikia/webdriver/Common/DriverProvider/DriverProvider.java index 70d7d43..f4e95b8 100644 --- a/src/test/java/com/wikia/webdriver/Common/DriverProvider/DriverProvider.java +++ b/src/test/java/com/wikia/webdriver/Common/DriverProvider/DriverProvider.java @@ -1,196 +1,196 @@ package com.wikia.webdriver.Common.DriverProvider; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.browsermob.proxy.ProxyServer; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.safari.SafariDriver; import org.openqa.selenium.support.events.EventFiringWebDriver; import com.wikia.webdriver.Common.Core.Global; import com.wikia.webdriver.Common.Logging.PageObjectLogging; public class DriverProvider { private static final DriverProvider instance = new DriverProvider(); private static WebDriver driver; private static ProxyServer server; private static DesiredCapabilities caps = new DesiredCapabilities(); private static FirefoxProfile profile = new FirefoxProfile(); /** * creating webdriver instance based on given browser string * @return instance of webdriver * @author Karol Kujawiak */ public static DriverProvider getInstance() { PageObjectLogging listener = new PageObjectLogging(); Global.JS_ERROR_ENABLED = false; if (Global.BROWSER.equals("IE")) { setIEProperties(); driver = new EventFiringWebDriver( new InternetExplorerDriver(caps) ).register(listener); } else if (Global.BROWSER.contains("FF")) { - if (System.getProperty("os.name").toLowerCase().contains("win8")){ + if (System.getProperty("os.name").toLowerCase().equals("windows 8")){ System.setProperty("webdriver.firefox.bin", "c:\\Program Files (x86)\\Mozilla Firefox\\"); } if (Global.BROWSER.contains("CONSOLE")){ try{ File jsErr = new File("./src/test/resources/Firebug/JSErrorCollector.xpi"); profile.addExtension(jsErr); Global.JS_ERROR_ENABLED = true; } catch(FileNotFoundException e){ System.out.println("JS extension file doesn't exist in provided location"); } catch (IOException e) { System.out.println("Error with adding firefox extension"); } } driver = new EventFiringWebDriver( new FirefoxDriver(profile) ).register(listener); } else if (Global.BROWSER.equals("CHROME")) { setChromeProperties(); driver = new EventFiringWebDriver( new ChromeDriver(caps) ).register(listener); } else if (Global.BROWSER.equals("SAFARI")) { /* * clone following repository * https://github.com/senthilnayagam/safari-webdriver.git * webdriver.safari.driver property should be set to path to the SafariDriver.safariextz file */ System.setProperty("webdriver.safari.driver", ""); driver = new EventFiringWebDriver(new SafariDriver()).register(listener); } // else if (Global.BROWSER.contains("FFPROXY")) { // server = new ProxyServer(4569); // try { // server.start(); // server.setCaptureHeaders(true); // server.setCaptureContent(true); // server.newHar("test"); // Proxy proxy = server.seleniumProxy(); // FirefoxProfile profile = new FirefoxProfile(); // profile.setAcceptUntrustedCertificates(true); // profile.setAssumeUntrustedCertificateIssuer(true); // profile.setPreference("network.proxy.http", "localhost"); // profile.setPreference("network.proxy.http_port", 4569); // profile.setPreference("network.proxy.ssl", "localhost"); // profile.setPreference("network.proxy.ssl_port", 4569); // profile.setPreference("network.proxy.type", 1); // profile.setPreference("network.proxy.no_proxies_on", ""); // profile.setProxyPreferences(proxy); // caps.setCapability(FirefoxDriver.PROFILE,profile); // caps.setCapability(CapabilityType.PROXY, proxy); // driver = new EventFiringWebDriver(new FirefoxDriver(caps)).register(listener); // } catch(Exception e){ // e.printStackTrace(); // } // } else if (Global.BROWSER.equals("CHROMEMOBILE")) { setChromeProperties(); ChromeOptions o = new ChromeOptions(); o.addArguments( "--user-agent=" + "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3" ); driver = new EventFiringWebDriver(new ChromeDriver(o)).register(listener); } else if (Global.BROWSER.equals("HTMLUNIT")) { driver = new EventFiringWebDriver(new HtmlUnitDriver()).register(listener); } else { System.out.println("This browser is not supported. Check -Dbrowser property value"); } if (!(Global.BROWSER.equals("CHROME")||Global.BROWSER.equals("CHROMEMOBILE")||Global.BROWSER.equals("SAFARI"))) { driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); } else { System.out.print(Global.BROWSER+" browser detected. Unable to set pageLoadTimeout()"); } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return instance; } /** * creating webdriver instance based on given browser string * @return * @author Karol Kujawiak */ public static DriverProvider getInstanceFF() { PageObjectLogging listener = new PageObjectLogging(); driver = new EventFiringWebDriver(new FirefoxDriver()).register(listener); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return instance; } /** * * @return * @author Karol Kujawiak */ public static WebDriver getWebDriver() { return driver; } public static ProxyServer getServer() { return server; } /** * @author Karol Kujawiak */ private static void setIEProperties() { String sysArch = System.getProperty("os.arch"); if (sysArch.equals("x86")) { File file = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "IEDriver" + File.separator + "IEDriverServer_x86.exe" ); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); } else { File file = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "IEDriver" + File.separator + "IEDriverServer_x64.exe" ); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); } } /** * @author Karol Kujawiak */ private static void setChromeProperties() { File file = new File ( "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ChromeDriver" + File.separator + "chromedriver.exe" ); System.setProperty("webdriver.chrome.driver", file.getAbsolutePath()); } public static void setCapabilities(DesiredCapabilities newCaps) { caps = newCaps; } }
true
true
public static DriverProvider getInstance() { PageObjectLogging listener = new PageObjectLogging(); Global.JS_ERROR_ENABLED = false; if (Global.BROWSER.equals("IE")) { setIEProperties(); driver = new EventFiringWebDriver( new InternetExplorerDriver(caps) ).register(listener); } else if (Global.BROWSER.contains("FF")) { if (System.getProperty("os.name").toLowerCase().contains("win8")){ System.setProperty("webdriver.firefox.bin", "c:\\Program Files (x86)\\Mozilla Firefox\\"); } if (Global.BROWSER.contains("CONSOLE")){ try{ File jsErr = new File("./src/test/resources/Firebug/JSErrorCollector.xpi"); profile.addExtension(jsErr); Global.JS_ERROR_ENABLED = true; } catch(FileNotFoundException e){ System.out.println("JS extension file doesn't exist in provided location"); } catch (IOException e) { System.out.println("Error with adding firefox extension"); } } driver = new EventFiringWebDriver( new FirefoxDriver(profile) ).register(listener); } else if (Global.BROWSER.equals("CHROME")) { setChromeProperties(); driver = new EventFiringWebDriver( new ChromeDriver(caps) ).register(listener); } else if (Global.BROWSER.equals("SAFARI")) { /* * clone following repository * https://github.com/senthilnayagam/safari-webdriver.git * webdriver.safari.driver property should be set to path to the SafariDriver.safariextz file */ System.setProperty("webdriver.safari.driver", ""); driver = new EventFiringWebDriver(new SafariDriver()).register(listener); } // else if (Global.BROWSER.contains("FFPROXY")) { // server = new ProxyServer(4569); // try { // server.start(); // server.setCaptureHeaders(true); // server.setCaptureContent(true); // server.newHar("test"); // Proxy proxy = server.seleniumProxy(); // FirefoxProfile profile = new FirefoxProfile(); // profile.setAcceptUntrustedCertificates(true); // profile.setAssumeUntrustedCertificateIssuer(true); // profile.setPreference("network.proxy.http", "localhost"); // profile.setPreference("network.proxy.http_port", 4569); // profile.setPreference("network.proxy.ssl", "localhost"); // profile.setPreference("network.proxy.ssl_port", 4569); // profile.setPreference("network.proxy.type", 1); // profile.setPreference("network.proxy.no_proxies_on", ""); // profile.setProxyPreferences(proxy); // caps.setCapability(FirefoxDriver.PROFILE,profile); // caps.setCapability(CapabilityType.PROXY, proxy); // driver = new EventFiringWebDriver(new FirefoxDriver(caps)).register(listener); // } catch(Exception e){ // e.printStackTrace(); // } // } else if (Global.BROWSER.equals("CHROMEMOBILE")) { setChromeProperties(); ChromeOptions o = new ChromeOptions(); o.addArguments( "--user-agent=" + "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3" ); driver = new EventFiringWebDriver(new ChromeDriver(o)).register(listener); } else if (Global.BROWSER.equals("HTMLUNIT")) { driver = new EventFiringWebDriver(new HtmlUnitDriver()).register(listener); } else { System.out.println("This browser is not supported. Check -Dbrowser property value"); } if (!(Global.BROWSER.equals("CHROME")||Global.BROWSER.equals("CHROMEMOBILE")||Global.BROWSER.equals("SAFARI"))) { driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); } else { System.out.print(Global.BROWSER+" browser detected. Unable to set pageLoadTimeout()"); } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return instance; }
public static DriverProvider getInstance() { PageObjectLogging listener = new PageObjectLogging(); Global.JS_ERROR_ENABLED = false; if (Global.BROWSER.equals("IE")) { setIEProperties(); driver = new EventFiringWebDriver( new InternetExplorerDriver(caps) ).register(listener); } else if (Global.BROWSER.contains("FF")) { if (System.getProperty("os.name").toLowerCase().equals("windows 8")){ System.setProperty("webdriver.firefox.bin", "c:\\Program Files (x86)\\Mozilla Firefox\\"); } if (Global.BROWSER.contains("CONSOLE")){ try{ File jsErr = new File("./src/test/resources/Firebug/JSErrorCollector.xpi"); profile.addExtension(jsErr); Global.JS_ERROR_ENABLED = true; } catch(FileNotFoundException e){ System.out.println("JS extension file doesn't exist in provided location"); } catch (IOException e) { System.out.println("Error with adding firefox extension"); } } driver = new EventFiringWebDriver( new FirefoxDriver(profile) ).register(listener); } else if (Global.BROWSER.equals("CHROME")) { setChromeProperties(); driver = new EventFiringWebDriver( new ChromeDriver(caps) ).register(listener); } else if (Global.BROWSER.equals("SAFARI")) { /* * clone following repository * https://github.com/senthilnayagam/safari-webdriver.git * webdriver.safari.driver property should be set to path to the SafariDriver.safariextz file */ System.setProperty("webdriver.safari.driver", ""); driver = new EventFiringWebDriver(new SafariDriver()).register(listener); } // else if (Global.BROWSER.contains("FFPROXY")) { // server = new ProxyServer(4569); // try { // server.start(); // server.setCaptureHeaders(true); // server.setCaptureContent(true); // server.newHar("test"); // Proxy proxy = server.seleniumProxy(); // FirefoxProfile profile = new FirefoxProfile(); // profile.setAcceptUntrustedCertificates(true); // profile.setAssumeUntrustedCertificateIssuer(true); // profile.setPreference("network.proxy.http", "localhost"); // profile.setPreference("network.proxy.http_port", 4569); // profile.setPreference("network.proxy.ssl", "localhost"); // profile.setPreference("network.proxy.ssl_port", 4569); // profile.setPreference("network.proxy.type", 1); // profile.setPreference("network.proxy.no_proxies_on", ""); // profile.setProxyPreferences(proxy); // caps.setCapability(FirefoxDriver.PROFILE,profile); // caps.setCapability(CapabilityType.PROXY, proxy); // driver = new EventFiringWebDriver(new FirefoxDriver(caps)).register(listener); // } catch(Exception e){ // e.printStackTrace(); // } // } else if (Global.BROWSER.equals("CHROMEMOBILE")) { setChromeProperties(); ChromeOptions o = new ChromeOptions(); o.addArguments( "--user-agent=" + "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3" ); driver = new EventFiringWebDriver(new ChromeDriver(o)).register(listener); } else if (Global.BROWSER.equals("HTMLUNIT")) { driver = new EventFiringWebDriver(new HtmlUnitDriver()).register(listener); } else { System.out.println("This browser is not supported. Check -Dbrowser property value"); } if (!(Global.BROWSER.equals("CHROME")||Global.BROWSER.equals("CHROMEMOBILE")||Global.BROWSER.equals("SAFARI"))) { driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); } else { System.out.print(Global.BROWSER+" browser detected. Unable to set pageLoadTimeout()"); } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return instance; }
diff --git a/src/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java b/src/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java index 8a77bfd8..f8cc4ec5 100644 --- a/src/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java +++ b/src/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java @@ -1,326 +1,327 @@ // $Id$ /* * WorldGuard * Copyright (C) 2010 sk89q <http://www.sk89q.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 com.sk89q.worldguard.bukkit; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.entity.Player; import org.bukkit.Server; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginLoader; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.config.Configuration; import com.sk89q.bukkit.migration.ConfigurationPermissionsResolver; import com.sk89q.worldguard.blacklist.Blacklist; import com.sk89q.worldguard.blacklist.BlacklistLogger; import com.sk89q.worldguard.blacklist.loggers.*; import com.sk89q.worldguard.protection.*; /** * Plugin for Bukkit. * * @author sk89qs */ public class WorldGuardPlugin extends JavaPlugin { private static final Logger logger = Logger.getLogger("Minecraft.WorldGuard"); private final WorldGuardPlayerListener playerListener = new WorldGuardPlayerListener(this); private final WorldGuardBlockListener blockListener = new WorldGuardBlockListener(this); private final WorldGuardEntityListener entityListener = new WorldGuardEntityListener(this); private final ConfigurationPermissionsResolver perms; Blacklist blacklist; RegionManager regionManager = new FlatRegionManager(); ProtectionDatabase regionLoader; Set<String> invinciblePlayers = new HashSet<String>(); Set<String> amphibiousPlayers = new HashSet<String>(); boolean fireSpreadDisableToggle; // Configuration follows boolean enforceOneSession; boolean itemDurability; boolean classicWater; boolean simulateSponge; int spongeRadius; boolean noPhysicsGravel; boolean noPhysicsSand; boolean allowPortalAnywhere; Set<Integer> preventWaterDamage; boolean blockTNT; boolean blockLighter; boolean disableFireSpread; Set<Integer> disableFireSpreadBlocks; boolean preventLavaFire; Set<Integer> allowedLavaSpreadOver; boolean blockCreeperExplosions; int loginProtection; int spawnProtection; boolean kickOnDeath; boolean exactRespawn; boolean teleportToHome; boolean disableFallDamage; boolean disableLavaDamage; boolean disableFireDamage; boolean disableDrowningDamage; boolean disableSuffocationDamage; boolean teleportOnSuffocation; boolean useRegions; int regionWand = 287; public WorldGuardPlugin(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) { super(pluginLoader, instance, desc, folder, plugin, cLoader); logger.info("WorldGuard " + desc.getVersion() + " loaded."); folder.mkdirs(); regionLoader = new CSVDatabase(new File(folder, "regions.txt")); perms = new ConfigurationPermissionsResolver(getConfiguration()); loadConfiguration(); postReload(); registerEvents(); } public void onEnable() { } public void onDisable() { } private void registerEvents() { registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal); registerEvent(Event.Type.BLOCK_FLOW, blockListener, Priority.Normal); registerEvent(Event.Type.BLOCK_IGNITE, blockListener, Priority.Normal); registerEvent(Event.Type.BLOCK_PHYSICS, blockListener, Priority.Normal); registerEvent(Event.Type.BLOCK_INTERACT, blockListener, Priority.Normal); registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal); registerEvent(Event.Type.BLOCK_RIGHTCLICKED, blockListener, Priority.Normal); registerEvent(Event.Type.ENTITY_DAMAGEDBY_BLOCK, entityListener, Priority.Normal); registerEvent(Event.Type.ENTITY_DAMAGEDBY_ENTITY, entityListener, Priority.Normal); registerEvent(Event.Type.PLAYER_COMMAND, playerListener, Priority.Normal); registerEvent(Event.Type.PLAYER_ITEM, playerListener, Priority.Normal); registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal); registerEvent(Event.Type.PLAYER_LOGIN, playerListener, Priority.Normal); registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Normal); } private void registerEvent(Event.Type type, Listener listener, Priority priority) { getServer().getPluginManager().registerEvent(type, listener, priority, this); } /** * Load the configuration */ public void loadConfiguration() { Configuration config = getConfiguration(); + config.load(); enforceOneSession = config.getBoolean("protection.enforce-single-session", true); itemDurability = config.getBoolean("protection.item-durability", true); classicWater = config.getBoolean("simulation.classic-water", false); simulateSponge = config.getBoolean("simulation.sponge.enable", true); spongeRadius = Math.max(1, config.getInt("simulation.sponge.radius", 3)) - 1; noPhysicsGravel = config.getBoolean("physics.no-physics-gravel", false); noPhysicsSand = config.getBoolean("physics.no-physics-sand", false); allowPortalAnywhere = config.getBoolean("physics.allow-portal-anywhere", false); preventWaterDamage = new HashSet<Integer>(config.getIntList("physics.disable-water-damage-blocks", null)); blockTNT = config.getBoolean("ignition.block-tnt", false); blockLighter = config.getBoolean("ignition.block-lighter", false); preventLavaFire = config.getBoolean("fire.disable-lava-fire-spread", true); disableFireSpread = config.getBoolean("fire.disable-all-fire-spread", false); disableFireSpreadBlocks = new HashSet<Integer>(config.getIntList("fire.disable-fire-spread-blocks", null)); allowedLavaSpreadOver = new HashSet<Integer>(config.getIntList("fire.lava-spread-blocks", null)); blockCreeperExplosions = config.getBoolean("mobs.block-creeper-explosions", false); loginProtection = config.getInt("spawn.login-protection", 3); spawnProtection = config.getInt("spawn.spawn-protection", 0); kickOnDeath = config.getBoolean("spawn.kick-on-death", false); exactRespawn = config.getBoolean("spawn.exact-respawn", false); teleportToHome = config.getBoolean("spawn.teleport-to-home-on-death", false); disableFallDamage = config.getBoolean("player-damage.disable-fall-damage", false); disableLavaDamage = config.getBoolean("player-damage.disable-lava-damage", false); disableFireDamage = config.getBoolean("player-damage.disable-fire-damage", false); disableDrowningDamage = config.getBoolean("player-damage.disable-water-damage", false); disableSuffocationDamage = config.getBoolean("player-damage.disable-suffocation-damage", false); teleportOnSuffocation = config.getBoolean("player-damage.teleport-on-suffocation", false); useRegions = config.getBoolean("regions.enable", true); regionWand = config.getInt("regions.wand", 287); try { regionLoader.load(); regionManager.setRegions(regionLoader.getRegions()); } catch (IOException e) { logger.warning("WorldGuard: Failed to load regions: " + e.getMessage()); } // Console log configuration boolean logConsole = config.getBoolean("blacklist.logging.console.enable", true); // Database log configuration boolean logDatabase = config.getBoolean("blacklist.logging.database.enable", false); String dsn = config.getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft"); String user = config.getString("blacklist.logging.database.user", "root"); String pass = config.getString("blacklist.logging.database.pass", ""); String table = config.getString("blacklist.logging.database.table", "blacklist_events"); // File log configuration boolean logFile = config.getBoolean("blacklist.logging.file.enable", false); String logFilePattern = config.getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log"); int logFileCacheSize = Math.max(1, config.getInt("blacklist.logging.file.open-files", 10)); // Load the blacklist try { // If there was an existing blacklist, close loggers if (blacklist != null) { blacklist.getLogger().close(); } // First load the blacklist data from worldguard-blacklist.txt Blacklist blist = new BukkitBlacklist(this); blist.load(new File(getDataFolder(), "blacklist.txt")); // If the blacklist is empty, then set the field to null // and save some resources if (blist.isEmpty()) { this.blacklist = null; } else { this.blacklist = blist; logger.log(Level.INFO, "WorldGuard: Blacklist loaded."); BlacklistLogger blacklistLogger = blist.getLogger(); if (logDatabase) { blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table)); } if (logConsole) { blacklistLogger.addHandler(new ConsoleLoggerHandler()); } if (logFile) { FileLoggerHandler handler = new FileLoggerHandler(logFilePattern, logFileCacheSize); blacklistLogger.addHandler(handler); } } } catch (FileNotFoundException e) { logger.log(Level.WARNING, "WorldGuard blacklist does not exist."); } catch (IOException e) { logger.log(Level.WARNING, "Could not load WorldGuard blacklist: " + e.getMessage()); } // Print an overview of settings if (config.getBoolean("summary-on-start", true)) { logger.log(Level.INFO, enforceOneSession ? "WorldGuard: Single session is enforced." : "WorldGuard: Single session is NOT ENFORCED."); logger.log(Level.INFO, blockTNT ? "WorldGuard: TNT ignition is blocked." : "WorldGuard: TNT ignition is PERMITTED."); logger.log(Level.INFO, blockLighter ? "WorldGuard: Lighters are blocked." : "WorldGuard: Lighters are PERMITTED."); logger.log(Level.INFO, preventLavaFire ? "WorldGuard: Lava fire is blocked." : "WorldGuard: Lava fire is PERMITTED."); if (disableFireSpread) { logger.log(Level.INFO, "WorldGuard: All fire spread is disabled."); } else { if (disableFireSpreadBlocks != null) { logger.log(Level.INFO, "WorldGuard: Fire spread is limited to " + disableFireSpreadBlocks.size() + " block types."); } else { logger.log(Level.INFO, "WorldGuard: Fire spread is UNRESTRICTED."); } } } // Temporary perms.load(); } /** * Populates various lists. */ public void postReload() { invinciblePlayers.clear(); amphibiousPlayers.clear(); try { for (Player player : getServer().getOnlinePlayers()) { if (inGroup(player, "wg-invincible")) { invinciblePlayers.add(player.getName()); } if (inGroup(player, "wg-amphibious")) { amphibiousPlayers.add(player.getName()); } } } catch (NullPointerException e) { // Thrown if loaded too early } } boolean inGroup(Player player, String group) { return perms.inGroup(player.getName(), group); } boolean hasPermission(Player player, String perm) { return perms.hasPermission(player.getName(), perm); } List<String> getGroups(Player player) { return new ArrayList<String>(); } BukkitPlayer wrapPlayer(Player player) { return new BukkitPlayer(this, player); } }
true
true
public void loadConfiguration() { Configuration config = getConfiguration(); enforceOneSession = config.getBoolean("protection.enforce-single-session", true); itemDurability = config.getBoolean("protection.item-durability", true); classicWater = config.getBoolean("simulation.classic-water", false); simulateSponge = config.getBoolean("simulation.sponge.enable", true); spongeRadius = Math.max(1, config.getInt("simulation.sponge.radius", 3)) - 1; noPhysicsGravel = config.getBoolean("physics.no-physics-gravel", false); noPhysicsSand = config.getBoolean("physics.no-physics-sand", false); allowPortalAnywhere = config.getBoolean("physics.allow-portal-anywhere", false); preventWaterDamage = new HashSet<Integer>(config.getIntList("physics.disable-water-damage-blocks", null)); blockTNT = config.getBoolean("ignition.block-tnt", false); blockLighter = config.getBoolean("ignition.block-lighter", false); preventLavaFire = config.getBoolean("fire.disable-lava-fire-spread", true); disableFireSpread = config.getBoolean("fire.disable-all-fire-spread", false); disableFireSpreadBlocks = new HashSet<Integer>(config.getIntList("fire.disable-fire-spread-blocks", null)); allowedLavaSpreadOver = new HashSet<Integer>(config.getIntList("fire.lava-spread-blocks", null)); blockCreeperExplosions = config.getBoolean("mobs.block-creeper-explosions", false); loginProtection = config.getInt("spawn.login-protection", 3); spawnProtection = config.getInt("spawn.spawn-protection", 0); kickOnDeath = config.getBoolean("spawn.kick-on-death", false); exactRespawn = config.getBoolean("spawn.exact-respawn", false); teleportToHome = config.getBoolean("spawn.teleport-to-home-on-death", false); disableFallDamage = config.getBoolean("player-damage.disable-fall-damage", false); disableLavaDamage = config.getBoolean("player-damage.disable-lava-damage", false); disableFireDamage = config.getBoolean("player-damage.disable-fire-damage", false); disableDrowningDamage = config.getBoolean("player-damage.disable-water-damage", false); disableSuffocationDamage = config.getBoolean("player-damage.disable-suffocation-damage", false); teleportOnSuffocation = config.getBoolean("player-damage.teleport-on-suffocation", false); useRegions = config.getBoolean("regions.enable", true); regionWand = config.getInt("regions.wand", 287); try { regionLoader.load(); regionManager.setRegions(regionLoader.getRegions()); } catch (IOException e) { logger.warning("WorldGuard: Failed to load regions: " + e.getMessage()); } // Console log configuration boolean logConsole = config.getBoolean("blacklist.logging.console.enable", true); // Database log configuration boolean logDatabase = config.getBoolean("blacklist.logging.database.enable", false); String dsn = config.getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft"); String user = config.getString("blacklist.logging.database.user", "root"); String pass = config.getString("blacklist.logging.database.pass", ""); String table = config.getString("blacklist.logging.database.table", "blacklist_events"); // File log configuration boolean logFile = config.getBoolean("blacklist.logging.file.enable", false); String logFilePattern = config.getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log"); int logFileCacheSize = Math.max(1, config.getInt("blacklist.logging.file.open-files", 10)); // Load the blacklist try { // If there was an existing blacklist, close loggers if (blacklist != null) { blacklist.getLogger().close(); } // First load the blacklist data from worldguard-blacklist.txt Blacklist blist = new BukkitBlacklist(this); blist.load(new File(getDataFolder(), "blacklist.txt")); // If the blacklist is empty, then set the field to null // and save some resources if (blist.isEmpty()) { this.blacklist = null; } else { this.blacklist = blist; logger.log(Level.INFO, "WorldGuard: Blacklist loaded."); BlacklistLogger blacklistLogger = blist.getLogger(); if (logDatabase) { blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table)); } if (logConsole) { blacklistLogger.addHandler(new ConsoleLoggerHandler()); } if (logFile) { FileLoggerHandler handler = new FileLoggerHandler(logFilePattern, logFileCacheSize); blacklistLogger.addHandler(handler); } } } catch (FileNotFoundException e) { logger.log(Level.WARNING, "WorldGuard blacklist does not exist."); } catch (IOException e) { logger.log(Level.WARNING, "Could not load WorldGuard blacklist: " + e.getMessage()); } // Print an overview of settings if (config.getBoolean("summary-on-start", true)) { logger.log(Level.INFO, enforceOneSession ? "WorldGuard: Single session is enforced." : "WorldGuard: Single session is NOT ENFORCED."); logger.log(Level.INFO, blockTNT ? "WorldGuard: TNT ignition is blocked." : "WorldGuard: TNT ignition is PERMITTED."); logger.log(Level.INFO, blockLighter ? "WorldGuard: Lighters are blocked." : "WorldGuard: Lighters are PERMITTED."); logger.log(Level.INFO, preventLavaFire ? "WorldGuard: Lava fire is blocked." : "WorldGuard: Lava fire is PERMITTED."); if (disableFireSpread) { logger.log(Level.INFO, "WorldGuard: All fire spread is disabled."); } else { if (disableFireSpreadBlocks != null) { logger.log(Level.INFO, "WorldGuard: Fire spread is limited to " + disableFireSpreadBlocks.size() + " block types."); } else { logger.log(Level.INFO, "WorldGuard: Fire spread is UNRESTRICTED."); } } } // Temporary perms.load(); }
public void loadConfiguration() { Configuration config = getConfiguration(); config.load(); enforceOneSession = config.getBoolean("protection.enforce-single-session", true); itemDurability = config.getBoolean("protection.item-durability", true); classicWater = config.getBoolean("simulation.classic-water", false); simulateSponge = config.getBoolean("simulation.sponge.enable", true); spongeRadius = Math.max(1, config.getInt("simulation.sponge.radius", 3)) - 1; noPhysicsGravel = config.getBoolean("physics.no-physics-gravel", false); noPhysicsSand = config.getBoolean("physics.no-physics-sand", false); allowPortalAnywhere = config.getBoolean("physics.allow-portal-anywhere", false); preventWaterDamage = new HashSet<Integer>(config.getIntList("physics.disable-water-damage-blocks", null)); blockTNT = config.getBoolean("ignition.block-tnt", false); blockLighter = config.getBoolean("ignition.block-lighter", false); preventLavaFire = config.getBoolean("fire.disable-lava-fire-spread", true); disableFireSpread = config.getBoolean("fire.disable-all-fire-spread", false); disableFireSpreadBlocks = new HashSet<Integer>(config.getIntList("fire.disable-fire-spread-blocks", null)); allowedLavaSpreadOver = new HashSet<Integer>(config.getIntList("fire.lava-spread-blocks", null)); blockCreeperExplosions = config.getBoolean("mobs.block-creeper-explosions", false); loginProtection = config.getInt("spawn.login-protection", 3); spawnProtection = config.getInt("spawn.spawn-protection", 0); kickOnDeath = config.getBoolean("spawn.kick-on-death", false); exactRespawn = config.getBoolean("spawn.exact-respawn", false); teleportToHome = config.getBoolean("spawn.teleport-to-home-on-death", false); disableFallDamage = config.getBoolean("player-damage.disable-fall-damage", false); disableLavaDamage = config.getBoolean("player-damage.disable-lava-damage", false); disableFireDamage = config.getBoolean("player-damage.disable-fire-damage", false); disableDrowningDamage = config.getBoolean("player-damage.disable-water-damage", false); disableSuffocationDamage = config.getBoolean("player-damage.disable-suffocation-damage", false); teleportOnSuffocation = config.getBoolean("player-damage.teleport-on-suffocation", false); useRegions = config.getBoolean("regions.enable", true); regionWand = config.getInt("regions.wand", 287); try { regionLoader.load(); regionManager.setRegions(regionLoader.getRegions()); } catch (IOException e) { logger.warning("WorldGuard: Failed to load regions: " + e.getMessage()); } // Console log configuration boolean logConsole = config.getBoolean("blacklist.logging.console.enable", true); // Database log configuration boolean logDatabase = config.getBoolean("blacklist.logging.database.enable", false); String dsn = config.getString("blacklist.logging.database.dsn", "jdbc:mysql://localhost:3306/minecraft"); String user = config.getString("blacklist.logging.database.user", "root"); String pass = config.getString("blacklist.logging.database.pass", ""); String table = config.getString("blacklist.logging.database.table", "blacklist_events"); // File log configuration boolean logFile = config.getBoolean("blacklist.logging.file.enable", false); String logFilePattern = config.getString("blacklist.logging.file.path", "worldguard/logs/%Y-%m-%d.log"); int logFileCacheSize = Math.max(1, config.getInt("blacklist.logging.file.open-files", 10)); // Load the blacklist try { // If there was an existing blacklist, close loggers if (blacklist != null) { blacklist.getLogger().close(); } // First load the blacklist data from worldguard-blacklist.txt Blacklist blist = new BukkitBlacklist(this); blist.load(new File(getDataFolder(), "blacklist.txt")); // If the blacklist is empty, then set the field to null // and save some resources if (blist.isEmpty()) { this.blacklist = null; } else { this.blacklist = blist; logger.log(Level.INFO, "WorldGuard: Blacklist loaded."); BlacklistLogger blacklistLogger = blist.getLogger(); if (logDatabase) { blacklistLogger.addHandler(new DatabaseLoggerHandler(dsn, user, pass, table)); } if (logConsole) { blacklistLogger.addHandler(new ConsoleLoggerHandler()); } if (logFile) { FileLoggerHandler handler = new FileLoggerHandler(logFilePattern, logFileCacheSize); blacklistLogger.addHandler(handler); } } } catch (FileNotFoundException e) { logger.log(Level.WARNING, "WorldGuard blacklist does not exist."); } catch (IOException e) { logger.log(Level.WARNING, "Could not load WorldGuard blacklist: " + e.getMessage()); } // Print an overview of settings if (config.getBoolean("summary-on-start", true)) { logger.log(Level.INFO, enforceOneSession ? "WorldGuard: Single session is enforced." : "WorldGuard: Single session is NOT ENFORCED."); logger.log(Level.INFO, blockTNT ? "WorldGuard: TNT ignition is blocked." : "WorldGuard: TNT ignition is PERMITTED."); logger.log(Level.INFO, blockLighter ? "WorldGuard: Lighters are blocked." : "WorldGuard: Lighters are PERMITTED."); logger.log(Level.INFO, preventLavaFire ? "WorldGuard: Lava fire is blocked." : "WorldGuard: Lava fire is PERMITTED."); if (disableFireSpread) { logger.log(Level.INFO, "WorldGuard: All fire spread is disabled."); } else { if (disableFireSpreadBlocks != null) { logger.log(Level.INFO, "WorldGuard: Fire spread is limited to " + disableFireSpreadBlocks.size() + " block types."); } else { logger.log(Level.INFO, "WorldGuard: Fire spread is UNRESTRICTED."); } } } // Temporary perms.load(); }
diff --git a/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java b/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java index 2e75f61..6644293 100644 --- a/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java +++ b/src/main/java/nl/vu/datalayer/hbase/sail/HBaseSailConnection.java @@ -1,604 +1,604 @@ package nl.vu.datalayer.hbase.sail; import info.aduna.iteration.CloseableIteration; import info.aduna.iteration.CloseableIteratorIteration; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import nl.vu.datalayer.hbase.HBaseClientSolution; import org.openrdf.model.Namespace; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.BNodeImpl; import org.openrdf.model.impl.ContextStatementImpl; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.Dataset; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.Var; import org.openrdf.query.impl.TupleQueryResultImpl; import org.openrdf.sail.NotifyingSailConnection; import org.openrdf.sail.SailException; import org.openrdf.sail.helpers.NotifyingSailConnectionBase; import org.openrdf.sail.helpers.SailBase; import org.openrdf.sail.memory.MemoryStore; /** * A connection to an HBase Sail object. This class implements methods to break down SPARQL * queries into statement patterns that can be used for querying HBase, to set up an in-memory * store for loading the quads retrieved from HBase, and finally, to run the intial SPARQL query * over the in-memory store and return the results. * <p> * This class implements * An HBaseSailConnection is active from the moment it is created until it is closed. Care * should be taken to properly close HBaseSailConnections as they might block concurrent queries * and/or updates on the Sail while active, depending on the Sail-implementation that is being * used. * * @author Anca Dumitrache */ public class HBaseSailConnection extends NotifyingSailConnectionBase { MemoryStore memStore; NotifyingSailConnection memStoreCon; HBaseClientSolution hbase; // Builder to write the query to bit by bit StringBuilder queryString = new StringBuilder(); /** * Establishes the connection to the HBase Sail, and sets up the in-memory store. * * @param sailBase */ public HBaseSailConnection(SailBase sailBase) { super(sailBase); // System.out.println("SailConnection created"); hbase = ((HBaseSail) sailBase).getHBase(); memStore = new MemoryStore(); try { memStore.initialize(); memStoreCon = memStore.getConnection(); } catch (SailException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void addStatementInternal(Resource arg0, URI arg1, Value arg2, Resource... arg3) throws SailException { ArrayList<Statement> myList = new ArrayList(); Statement s = new StatementImpl(arg0, arg1, arg2); myList.add(s); // TODO: update method for adding quads // try { // HBaseClientSolution sol = // HBaseFactory.getHBaseSolution(HBHexastoreSchema.SCHEMA_NAME, con, // myList); // sol.schema.create(); // sol.util.populateTables(myList); // } // catch (Exception e) { // e.printStackTrace(); // // TODO error handling // } } @Override protected void clearInternal(Resource... arg0) throws SailException { // TODO Auto-generated method stub } @Override protected void clearNamespacesInternal() throws SailException { // TODO Auto-generated method stub } @Override protected void closeInternal() throws SailException { memStoreCon.close(); } @Override protected void commitInternal() throws SailException { // TODO Auto-generated method stub } @Override protected CloseableIteration<? extends Resource, SailException> getContextIDsInternal() throws SailException { // TODO Auto-generated method stub return null; } @Override protected String getNamespaceInternal(String arg0) throws SailException { // TODO Auto-generated method stub return null; } @Override protected CloseableIteration<? extends Namespace, SailException> getNamespacesInternal() throws SailException { // TODO Auto-generated method stub return null; } /** * This function sends a statement pattern to HBase for querying, * then returns the results in RDF Statement format. * * @param arg0 * @param arg1 * @param arg2 * @param arg3 * @param contexts * @return * @throws SailException */ protected CloseableIteration<? extends Statement, SailException> getStatementsInternal(Resource arg0, URI arg1, Value arg2, boolean arg3, Set<URI> contexts) throws SailException { try { ArrayList<Value> g = new ArrayList(); if (contexts != null && contexts.size() != 0) { for (Resource r : contexts) { g.add(r); } } else { g.add(null); } ArrayList<Statement> myList = new ArrayList(); for (Value graph : g) { System.out.println("HBase Query: " + arg0 + " - " + arg1 + " - " + arg2 + " - " + graph); Value[] query = { arg0, arg1, arg2, graph }; ArrayList<ArrayList<Value>> result = null; try { result = hbase.util.getResults(query); myList.addAll(reconstructTriples(result, query)); } catch (Exception e) { // empty list retrieved from HBase } } try { Iterator it = myList.iterator(); CloseableIteration<Statement, SailException> ci = new CloseableIteratorIteration<Statement, SailException>( it); return ci; } catch (Exception e) { // if there are no results to retrieve return null; } } catch (Exception e) { Exception ex = new SailException("HBase connection error: " + e.getMessage()); try { throw ex; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } /** * This function reconstructs RDF Statements from the list of Value items * returned from HBase. * * @param result * @param triple * @return * @throws SailException */ protected ArrayList<Statement> reconstructTriples(ArrayList<ArrayList<Value>> result, Value[] triple) throws SailException { ArrayList<Statement> list = new ArrayList(); for (ArrayList<Value> arrayList : result) { int index = 0; Resource s = null; URI p = null; Value o = null; Resource c = null; for (Value value : arrayList) { if (index == 0) { // s = (Resource)getSubject(value); s = (Resource) value; } else if (index == 1) { // p = (URI) getPredicate(value); p = (URI) value; } else if (index == 2) { // o = getObject(value); o = value; } else { // c = (Resource)getContext(value); c = (Resource) value; Statement statement = new ContextStatementImpl(s, p, o, c); list.add(statement); } index++; } } return list; } /** * This functions parses a String to return the subject in a query. * * @param s * @return */ Value getSubject(String s) { // System.out.println("SUBJECT: " + s); if (s.startsWith("_")) { return new BNodeImpl(s.substring(2)); } return new URIImpl(s); } /** * This functions parses a String to return the predicate in a query. * * @param s * @return */ Value getPredicate(String s) { // System.out.println("PREDICATE: " + s); return new URIImpl(s); } /** * This functions parses a String to return the object in a query. * * @param s * @return */ Value getObject(String s) { // System.out.println("OBJECT: " + s); if (s.startsWith("_")) { return new BNodeImpl(s.substring(2)); } else if (s.startsWith("\"")) { String literal = ""; String language = ""; String datatype = ""; for (int i = 1; i < s.length(); i++) { while (s.charAt(i) != '"') { // read literal value literal += s.charAt(i); if (s.charAt(i) == '\\') { i++; literal += s.charAt(i); } i++; if (i == s.length()) { // EOF exception } } // System.out.println(literal); // charAt(i) = '"', read next char i++; if (s.charAt(i) == '@') { // read language // System.out.println("reading language"); i++; while (i < s.length()) { language += s.charAt(i); i++; } // System.out.println(language); return new LiteralImpl(literal, language); } else if (s.charAt(i) == '^') { // read datatype i++; // check for second '^' if (i == s.length()) { // EOF exception } else if (s.charAt(i) != '^') { // incorrect formatting exception } i++; // check for '<' if (i == s.length()) { // EOF exception } else if (s.charAt(i) != '<') { // incorrect formatting exception } i++; while (s.charAt(i) != '>') { datatype += s.charAt(i); i++; if (i == s.length()) { // EOF exception } } // System.out.println(datatype); return new LiteralImpl(literal, new URIImpl(datatype)); } else { return new LiteralImpl(literal); } } } Value object; try { object = new URIImpl(s); } catch (Exception e) { object = new LiteralImpl(s); } return object; } /** * This functions parses a String to return the graph in a query. * * @param s * @return */ Value getContext(String s) { // System.out.println("GRAPH: " + s); return new URIImpl(s); } @Override protected void removeNamespaceInternal(String arg0) throws SailException { // TODO Auto-generated method stub } @Override protected void removeStatementsInternal(Resource arg0, URI arg1, Value arg2, Resource... arg3) throws SailException { // TODO Auto-generated method stub } @Override protected void rollbackInternal() throws SailException { // TODO Auto-generated method stub } @Override protected void setNamespaceInternal(String arg0, String arg1) throws SailException { // TODO Auto-generated method stub } @Override protected long sizeInternal(Resource... arg0) throws SailException { // TODO Auto-generated method stub return 0; } @Override protected void startTransactionInternal() throws SailException { // TODO Auto-generated method stub } /** * This function retrieves all the triples from HBase that match with * StatementPatterns in the SPARQL query, without executing the SPARQL query * on them. * * @param arg0 * @return * @throws SailException */ protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); // } // } Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>) it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); // } // } Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var) jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource) getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource) getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI) getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { - obj = getObject(var.getValue().stringValue()); + obj = getObject(var.getValue().toString()); System.out.println("OBJECT: " + var.getValue().toString()); } else if (var.isAnonymous()) { obj = getObject(var.getName()); } } index += 1; } if (obj != null) { // System.out.println("OBJECT:" + obj.stringValue()) ; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement) ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; } @Override protected CloseableIteration<? extends BindingSet, QueryEvaluationException> evaluateInternal(TupleExpr arg0, Dataset arg1, BindingSet arg2, boolean arg3) throws SailException { return null; } /** * This function retrieves the relevant triples from HBase, loads them into * an in-memory store, then evaluates the SPARQL query on them. * * @param tupleExpr * @param dataset * @param bindings * @param includeInferred * @return * @throws SailException */ public TupleQueryResult query(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { // System.out.println("Evaluating query"); // System.out.println("EVALUATE:" + tupleExpr.toString()); try { ArrayList<Statement> statements = evaluateInternal(tupleExpr, dataset); // System.out.println("Statements retrieved: " + statements.size()); Resource[] context = null; try { Set<URI> contexts = dataset.getNamedGraphs(); context = new Resource[contexts.size()]; int index = 0; for (URI cont : contexts) { context[index] = cont; index++; } } catch (Exception e) { context = new Resource[1]; context[0] = new URIImpl("http://hbase.sail.vu.nl"); } Iterator it = statements.iterator(); while (it.hasNext()) { Statement statement = (Statement) it.next(); try { memStoreCon.addStatement(statement.getSubject(), statement.getPredicate(), statement.getObject(), context); } catch (Exception e) { System.out.println("THE FOLLOWING STATEMENT COULD NOT BE ADDED TO THE MEMORY STORE: " + statement.toString()); } } CloseableIteration<? extends BindingSet, QueryEvaluationException> ci = memStoreCon.evaluate(tupleExpr, dataset, bindings, includeInferred); CloseableIteration<? extends BindingSet, QueryEvaluationException> cj = memStoreCon.evaluate(tupleExpr, dataset, bindings, includeInferred); List<String> bindingList = new ArrayList<String>(); int index = 0; while (ci.hasNext()) { index++; BindingSet bs = ci.next(); Set<String> localBindings = bs.getBindingNames(); Iterator jt = localBindings.iterator(); while (jt.hasNext()) { String binding = (String) jt.next(); if (bindingList.contains(binding) == false) { bindingList.add(binding); } } } TupleQueryResult result = new TupleQueryResultImpl(bindingList, cj); return result; } catch (SailException e) { e.printStackTrace(); throw e; } catch (QueryEvaluationException e) { throw new SailException(e); } } @Override protected CloseableIteration<? extends Statement, SailException> getStatementsInternal(Resource arg0, URI arg1, Value arg2, boolean arg3, Resource... arg4) throws SailException { // TODO Auto-generated method stub return null; } }
true
true
protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); // } // } Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>) it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); // } // } Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var) jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource) getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource) getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI) getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { obj = getObject(var.getValue().stringValue()); System.out.println("OBJECT: " + var.getValue().toString()); } else if (var.isAnonymous()) { obj = getObject(var.getName()); } } index += 1; } if (obj != null) { // System.out.println("OBJECT:" + obj.stringValue()) ; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement) ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; }
protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); // } // } Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>) it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); // } // } Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var) jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource) getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource) getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI) getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { obj = getObject(var.getValue().toString()); System.out.println("OBJECT: " + var.getValue().toString()); } else if (var.isAnonymous()) { obj = getObject(var.getName()); } } index += 1; } if (obj != null) { // System.out.println("OBJECT:" + obj.stringValue()) ; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement) ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; }
diff --git a/src/org/knoesis/sparql/api/QueryRDFGraph.java b/src/org/knoesis/sparql/api/QueryRDFGraph.java index 035dbad..44a8713 100644 --- a/src/org/knoesis/sparql/api/QueryRDFGraph.java +++ b/src/org/knoesis/sparql/api/QueryRDFGraph.java @@ -1,62 +1,62 @@ package org.knoesis.sparql.api; import com.hp.hpl.jena.query.ResultSetFormatter; import com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP; import com.hp.hpl.jena.sparql.resultset.ResultsFormat; /* * This class queries the given RDF dataset with the given SPARQL query */ public class QueryRDFGraph { private String sparqlEndpoint; private String sparqlQuery; private com.hp.hpl.jena.query.ResultSet results; public QueryRDFGraph(String sparqlEndpoint, String sparqlQuery){ this.sparqlEndpoint = sparqlEndpoint; this.sparqlQuery = sparqlQuery; } /* * This method queries the graph using queryEngineHttp. * @output ResultSet */ public com.hp.hpl.jena.query.ResultSet query(){ QueryEngineHTTP httpengine = new QueryEngineHTTP(sparqlEndpoint,sparqlQuery); results = httpengine.execSelect(); return results; } public static void main(String[] args) { String graphURI = "http://dbpedia.org/sparql/"; String query1 = "PREFIX owl: <http://www.w3.org/2002/07/owl#>" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"+ "PREFIX dc: <http://purl.org/dc/elements/1.1/>"+ "PREFIX : <http://dbpedia.org/resource/>"+ "PREFIX dbpedia2: <http://dbpedia.org/property/>"+ "PREFIX dbpedia: <http://dbpedia.org/>"+ "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> \n" + "SELECT ?route ?y ?jump WHERE \n" + "{ \n"+ "{ \n" + "SELECT ?x ?y WHERE \n" + "{ ?x foaf:page ?xpage ; ?predicate ?y . filter( isURI(?y) ) } \n" + "} \n" + "OPTION ( TRANSITIVE, T_DISTINCT, T_SHORTEST_ONLY,t_in(?x), t_out(?y), t_max(10), t_step('path_id') as ?path, t_step(?x) as ?route, t_step('step_no') AS ?jump ). \n"+ "FILTER ( ?y = <http://dbpedia.org/resource/Mitt_Romney> && ?x = <http://dbpedia.org/resource/Barack_Obama> ) \n"+ "}"; String query2 = "PREFIX owl: <http://www.w3.org/2002/07/owl#> Select count(?s) where {?s ?p ?o.}"; QueryRDFGraph querygraph = new QueryRDFGraph(graphURI, query1); // This method is used to format the output as per your requirements. - ResultSetFormatter.output(querygraph.query(),ResultsFormat.FMT_RS_JSON); + //ResultSetFormatter.output(querygraph.query(),ResultsFormat.FMT_RS_JSON); } }
true
true
public static void main(String[] args) { String graphURI = "http://dbpedia.org/sparql/"; String query1 = "PREFIX owl: <http://www.w3.org/2002/07/owl#>" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"+ "PREFIX dc: <http://purl.org/dc/elements/1.1/>"+ "PREFIX : <http://dbpedia.org/resource/>"+ "PREFIX dbpedia2: <http://dbpedia.org/property/>"+ "PREFIX dbpedia: <http://dbpedia.org/>"+ "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> \n" + "SELECT ?route ?y ?jump WHERE \n" + "{ \n"+ "{ \n" + "SELECT ?x ?y WHERE \n" + "{ ?x foaf:page ?xpage ; ?predicate ?y . filter( isURI(?y) ) } \n" + "} \n" + "OPTION ( TRANSITIVE, T_DISTINCT, T_SHORTEST_ONLY,t_in(?x), t_out(?y), t_max(10), t_step('path_id') as ?path, t_step(?x) as ?route, t_step('step_no') AS ?jump ). \n"+ "FILTER ( ?y = <http://dbpedia.org/resource/Mitt_Romney> && ?x = <http://dbpedia.org/resource/Barack_Obama> ) \n"+ "}"; String query2 = "PREFIX owl: <http://www.w3.org/2002/07/owl#> Select count(?s) where {?s ?p ?o.}"; QueryRDFGraph querygraph = new QueryRDFGraph(graphURI, query1); // This method is used to format the output as per your requirements. ResultSetFormatter.output(querygraph.query(),ResultsFormat.FMT_RS_JSON); }
public static void main(String[] args) { String graphURI = "http://dbpedia.org/sparql/"; String query1 = "PREFIX owl: <http://www.w3.org/2002/07/owl#>" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+ "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"+ "PREFIX dc: <http://purl.org/dc/elements/1.1/>"+ "PREFIX : <http://dbpedia.org/resource/>"+ "PREFIX dbpedia2: <http://dbpedia.org/property/>"+ "PREFIX dbpedia: <http://dbpedia.org/>"+ "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> \n" + "SELECT ?route ?y ?jump WHERE \n" + "{ \n"+ "{ \n" + "SELECT ?x ?y WHERE \n" + "{ ?x foaf:page ?xpage ; ?predicate ?y . filter( isURI(?y) ) } \n" + "} \n" + "OPTION ( TRANSITIVE, T_DISTINCT, T_SHORTEST_ONLY,t_in(?x), t_out(?y), t_max(10), t_step('path_id') as ?path, t_step(?x) as ?route, t_step('step_no') AS ?jump ). \n"+ "FILTER ( ?y = <http://dbpedia.org/resource/Mitt_Romney> && ?x = <http://dbpedia.org/resource/Barack_Obama> ) \n"+ "}"; String query2 = "PREFIX owl: <http://www.w3.org/2002/07/owl#> Select count(?s) where {?s ?p ?o.}"; QueryRDFGraph querygraph = new QueryRDFGraph(graphURI, query1); // This method is used to format the output as per your requirements. //ResultSetFormatter.output(querygraph.query(),ResultsFormat.FMT_RS_JSON); }
diff --git a/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java b/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java index 42c4ec387..2306a67d6 100644 --- a/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java +++ b/main/src/main/java/com/bloatit/web/linkable/features/FeatureOfferListComponent.java @@ -1,212 +1,212 @@ /* * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt is free * software: you can redistribute it and/or modify it under the terms of the GNU * Affero General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * BloatIt is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. You should have received a copy of the GNU Affero General Public * License along with BloatIt. If not, see <http://www.gnu.org/licenses/>. */ package com.bloatit.web.linkable.features; import static com.bloatit.framework.webprocessor.context.Context.tr; import static com.bloatit.framework.webprocessor.context.Context.trn; import java.math.BigDecimal; import com.bloatit.data.queries.EmptyPageIterable; import com.bloatit.framework.utils.PageIterable; import com.bloatit.framework.utils.datetime.DateUtils; import com.bloatit.framework.utils.datetime.TimeRenderer; import com.bloatit.framework.utils.i18n.CurrencyLocale; import com.bloatit.framework.webprocessor.components.HtmlDiv; import com.bloatit.framework.webprocessor.components.HtmlLink; import com.bloatit.framework.webprocessor.components.HtmlParagraph; import com.bloatit.framework.webprocessor.components.HtmlSpan; import com.bloatit.framework.webprocessor.components.HtmlTitle; import com.bloatit.framework.webprocessor.components.PlaceHolderElement; import com.bloatit.framework.webprocessor.components.meta.HtmlElement; import com.bloatit.framework.webprocessor.components.meta.HtmlMixedText; import com.bloatit.framework.webprocessor.context.Context; import com.bloatit.model.Feature; import com.bloatit.model.Offer; import com.bloatit.web.url.MakeOfferPageUrl; public class FeatureOfferListComponent extends HtmlDiv { protected FeatureOfferListComponent(final Feature feature) { super(); PageIterable<Offer> offers = new EmptyPageIterable<Offer>(); offers = feature.getOffers(); int nbUnselected = offers.size(); final Offer selectedOffer = feature.getSelectedOffer(); if (selectedOffer != null) { nbUnselected--; } final HtmlDiv offersBlock = new HtmlDiv("offers_block"); switch (feature.getFeatureState()) { case PENDING: { if (nbUnselected > 0) { offersBlock.add(new HtmlTitle(tr("No selected offer"), 1)); } else { offersBlock.add(new HtmlTitle(tr("No offer"), 1)); } final BicolumnOfferBlock block = new BicolumnOfferBlock(true); offersBlock.add(block); block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer will be selected by default."))); final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(tr("Make an offer")); link.setCssClass("button"); final HtmlDiv noOffer = new HtmlDiv("no_offer_block"); { noOffer.add(link); } if (nbUnselected > 0) { generateUnselectedOfferList(feature, offers, nbUnselected, selectedOffer, offersBlock); } block.addInRightColumn(noOffer); } break; case PREPARING: { offersBlock.add(new HtmlTitle(tr("Selected offer"), 1)); // Selected final BicolumnOfferBlock block = new BicolumnOfferBlock(true); offersBlock.add(block); // Generating the left column block.addInLeftColumn(new HtmlParagraph(tr("The selected offer is the one with the more popularity."))); if (selectedOffer != null) { if (feature.getValidationDate() != null && DateUtils.isInTheFuture(feature.getValidationDate())) { final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate())); final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution()); if (amountLeft.compareTo(BigDecimal.ZERO) > 0) { final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); final HtmlSpan timeSpan = new HtmlSpan("bold"); timeSpan.addText(renderer.getTimeString()); final HtmlMixedText timeToValid = new HtmlMixedText(tr("This offer will be validated in about <0::>. After this time, the offer will go into development as soon as the requested amount is available ({0} left).", currency.getSimpleEuroString()), timeSpan); final HtmlParagraph element = new HtmlParagraph(timeToValid); block.addInLeftColumn(element); } else { final HtmlSpan timeSpan = new HtmlSpan("bold"); timeSpan.addText(renderer.getTimeString()); final HtmlMixedText timeToValid = new HtmlMixedText(Context.tr("This offer will go into development in about <0::>."), timeSpan); block.addInLeftColumn(timeToValid); } } else { final BigDecimal amountLeft = feature.getSelectedOffer().getAmount().subtract(feature.getContribution()); final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); block.addInLeftColumn(new HtmlParagraph(tr("This offer is validated and will go into development as soon as the requested amount is available ({0} left).", - currency.toString()))); + currency.getSimpleEuroString()))); } // Generating the right column block.addInRightColumn(new OfferBlock(selectedOffer, true)); } generateUnselectedOfferList(feature, offers, nbUnselected, selectedOffer, offersBlock); break; } case DEVELOPPING: final BicolumnOfferBlock block; offersBlock.add(new HtmlTitle(tr("Offer in development"), 1)); offersBlock.add(block = new BicolumnOfferBlock(true)); block.addInLeftColumn(new HtmlParagraph(tr("This offer is in development. You can discuss about it in the comments."))); if (selectedOffer != null && selectedOffer.hasRelease()) { block.addInLeftColumn(new HtmlParagraph(tr("Test the last release and report bugs."))); } block.addInRightColumn(new OfferBlock(selectedOffer, true)); generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock); break; case FINISHED: offersBlock.add(new HtmlTitle(tr("Finished offer"), 1)); offersBlock.add(block = new BicolumnOfferBlock(true)); block.addInLeftColumn(new HtmlParagraph(tr("This offer is finished."))); block.addInRightColumn(new OfferBlock(selectedOffer, true)); generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock); break; case DISCARDED: offersBlock.add(new HtmlTitle(tr("Feature discarded ..."), 1)); break; default: break; } add(offersBlock); } private void generateUnselectedOfferList(final Feature feature, final PageIterable<Offer> offers, final int nbUnselected, final Offer selectedOffer, final HtmlDiv offersBlock) { // UnSelected offersBlock.add(new HtmlTitle(trn("Unselected offer ({0})", "Unselected offers ({0})", nbUnselected, nbUnselected), 1)); final BicolumnOfferBlock unselectedBlock = new BicolumnOfferBlock(true); offersBlock.add(unselectedBlock); unselectedBlock.addInLeftColumn(new MakeOfferPageUrl(feature).getHtmlLink(tr("Make a concurrent offer"))); unselectedBlock.addInLeftColumn(new HtmlParagraph(tr("Vote on a competing offer to select it."))); for (final Offer offer : offers) { if (offer != selectedOffer) { unselectedBlock.addInRightColumn(new OfferBlock(offer, false)); } } } private void generateOldOffersList(final PageIterable<Offer> offers, final int nbUnselected, final Offer selectedOffer, final HtmlDiv offersBlock) { // UnSelected offersBlock.add(new HtmlTitle(trn("Old offer ({0})", "Old offers ({0})", nbUnselected, nbUnselected), 1)); final BicolumnOfferBlock unselectedBlock = new BicolumnOfferBlock(true); offersBlock.add(unselectedBlock); unselectedBlock.addInLeftColumn(new HtmlParagraph(tr("These offers have not been selected and will never be developed."))); for (final Offer offer : offers) { if (offer != selectedOffer) { unselectedBlock.addInRightColumn(new OfferBlock(offer, false)); } } } private static class BicolumnOfferBlock extends HtmlDiv { private final PlaceHolderElement leftColumn = new PlaceHolderElement(); private final PlaceHolderElement rightColumn = new PlaceHolderElement(); public BicolumnOfferBlock(final boolean isSelected) { super("offer_type_block"); HtmlDiv divSelected; if (isSelected) { divSelected = new HtmlDiv("offer_selected_description"); } else { divSelected = new HtmlDiv("offer_unselected_description"); } add(new HtmlDiv("offer_type_left_column").add(divSelected.add(leftColumn))); add(new HtmlDiv("offer_type_right_column").add(rightColumn)); } public void addInLeftColumn(final HtmlElement elment) { leftColumn.add(elment); } public void addInRightColumn(final HtmlElement elment) { rightColumn.add(elment); } } }
true
true
protected FeatureOfferListComponent(final Feature feature) { super(); PageIterable<Offer> offers = new EmptyPageIterable<Offer>(); offers = feature.getOffers(); int nbUnselected = offers.size(); final Offer selectedOffer = feature.getSelectedOffer(); if (selectedOffer != null) { nbUnselected--; } final HtmlDiv offersBlock = new HtmlDiv("offers_block"); switch (feature.getFeatureState()) { case PENDING: { if (nbUnselected > 0) { offersBlock.add(new HtmlTitle(tr("No selected offer"), 1)); } else { offersBlock.add(new HtmlTitle(tr("No offer"), 1)); } final BicolumnOfferBlock block = new BicolumnOfferBlock(true); offersBlock.add(block); block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer will be selected by default."))); final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(tr("Make an offer")); link.setCssClass("button"); final HtmlDiv noOffer = new HtmlDiv("no_offer_block"); { noOffer.add(link); } if (nbUnselected > 0) { generateUnselectedOfferList(feature, offers, nbUnselected, selectedOffer, offersBlock); } block.addInRightColumn(noOffer); } break; case PREPARING: { offersBlock.add(new HtmlTitle(tr("Selected offer"), 1)); // Selected final BicolumnOfferBlock block = new BicolumnOfferBlock(true); offersBlock.add(block); // Generating the left column block.addInLeftColumn(new HtmlParagraph(tr("The selected offer is the one with the more popularity."))); if (selectedOffer != null) { if (feature.getValidationDate() != null && DateUtils.isInTheFuture(feature.getValidationDate())) { final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate())); final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution()); if (amountLeft.compareTo(BigDecimal.ZERO) > 0) { final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); final HtmlSpan timeSpan = new HtmlSpan("bold"); timeSpan.addText(renderer.getTimeString()); final HtmlMixedText timeToValid = new HtmlMixedText(tr("This offer will be validated in about <0::>. After this time, the offer will go into development as soon as the requested amount is available ({0} left).", currency.getSimpleEuroString()), timeSpan); final HtmlParagraph element = new HtmlParagraph(timeToValid); block.addInLeftColumn(element); } else { final HtmlSpan timeSpan = new HtmlSpan("bold"); timeSpan.addText(renderer.getTimeString()); final HtmlMixedText timeToValid = new HtmlMixedText(Context.tr("This offer will go into development in about <0::>."), timeSpan); block.addInLeftColumn(timeToValid); } } else { final BigDecimal amountLeft = feature.getSelectedOffer().getAmount().subtract(feature.getContribution()); final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); block.addInLeftColumn(new HtmlParagraph(tr("This offer is validated and will go into development as soon as the requested amount is available ({0} left).", currency.toString()))); } // Generating the right column block.addInRightColumn(new OfferBlock(selectedOffer, true)); } generateUnselectedOfferList(feature, offers, nbUnselected, selectedOffer, offersBlock); break; } case DEVELOPPING: final BicolumnOfferBlock block; offersBlock.add(new HtmlTitle(tr("Offer in development"), 1)); offersBlock.add(block = new BicolumnOfferBlock(true)); block.addInLeftColumn(new HtmlParagraph(tr("This offer is in development. You can discuss about it in the comments."))); if (selectedOffer != null && selectedOffer.hasRelease()) { block.addInLeftColumn(new HtmlParagraph(tr("Test the last release and report bugs."))); } block.addInRightColumn(new OfferBlock(selectedOffer, true)); generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock); break; case FINISHED: offersBlock.add(new HtmlTitle(tr("Finished offer"), 1)); offersBlock.add(block = new BicolumnOfferBlock(true)); block.addInLeftColumn(new HtmlParagraph(tr("This offer is finished."))); block.addInRightColumn(new OfferBlock(selectedOffer, true)); generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock); break; case DISCARDED: offersBlock.add(new HtmlTitle(tr("Feature discarded ..."), 1)); break; default: break; } add(offersBlock); }
protected FeatureOfferListComponent(final Feature feature) { super(); PageIterable<Offer> offers = new EmptyPageIterable<Offer>(); offers = feature.getOffers(); int nbUnselected = offers.size(); final Offer selectedOffer = feature.getSelectedOffer(); if (selectedOffer != null) { nbUnselected--; } final HtmlDiv offersBlock = new HtmlDiv("offers_block"); switch (feature.getFeatureState()) { case PENDING: { if (nbUnselected > 0) { offersBlock.add(new HtmlTitle(tr("No selected offer"), 1)); } else { offersBlock.add(new HtmlTitle(tr("No offer"), 1)); } final BicolumnOfferBlock block = new BicolumnOfferBlock(true); offersBlock.add(block); block.addInLeftColumn(new HtmlParagraph(tr("There is not yet offer to develop this feature. The first offer will be selected by default."))); final HtmlLink link = new MakeOfferPageUrl(feature).getHtmlLink(tr("Make an offer")); link.setCssClass("button"); final HtmlDiv noOffer = new HtmlDiv("no_offer_block"); { noOffer.add(link); } if (nbUnselected > 0) { generateUnselectedOfferList(feature, offers, nbUnselected, selectedOffer, offersBlock); } block.addInRightColumn(noOffer); } break; case PREPARING: { offersBlock.add(new HtmlTitle(tr("Selected offer"), 1)); // Selected final BicolumnOfferBlock block = new BicolumnOfferBlock(true); offersBlock.add(block); // Generating the left column block.addInLeftColumn(new HtmlParagraph(tr("The selected offer is the one with the more popularity."))); if (selectedOffer != null) { if (feature.getValidationDate() != null && DateUtils.isInTheFuture(feature.getValidationDate())) { final TimeRenderer renderer = new TimeRenderer(DateUtils.elapsed(DateUtils.now(), feature.getValidationDate())); final BigDecimal amountLeft = selectedOffer.getAmount().subtract(feature.getContribution()); if (amountLeft.compareTo(BigDecimal.ZERO) > 0) { final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); final HtmlSpan timeSpan = new HtmlSpan("bold"); timeSpan.addText(renderer.getTimeString()); final HtmlMixedText timeToValid = new HtmlMixedText(tr("This offer will be validated in about <0::>. After this time, the offer will go into development as soon as the requested amount is available ({0} left).", currency.getSimpleEuroString()), timeSpan); final HtmlParagraph element = new HtmlParagraph(timeToValid); block.addInLeftColumn(element); } else { final HtmlSpan timeSpan = new HtmlSpan("bold"); timeSpan.addText(renderer.getTimeString()); final HtmlMixedText timeToValid = new HtmlMixedText(Context.tr("This offer will go into development in about <0::>."), timeSpan); block.addInLeftColumn(timeToValid); } } else { final BigDecimal amountLeft = feature.getSelectedOffer().getAmount().subtract(feature.getContribution()); final CurrencyLocale currency = Context.getLocalizator().getCurrency(amountLeft); block.addInLeftColumn(new HtmlParagraph(tr("This offer is validated and will go into development as soon as the requested amount is available ({0} left).", currency.getSimpleEuroString()))); } // Generating the right column block.addInRightColumn(new OfferBlock(selectedOffer, true)); } generateUnselectedOfferList(feature, offers, nbUnselected, selectedOffer, offersBlock); break; } case DEVELOPPING: final BicolumnOfferBlock block; offersBlock.add(new HtmlTitle(tr("Offer in development"), 1)); offersBlock.add(block = new BicolumnOfferBlock(true)); block.addInLeftColumn(new HtmlParagraph(tr("This offer is in development. You can discuss about it in the comments."))); if (selectedOffer != null && selectedOffer.hasRelease()) { block.addInLeftColumn(new HtmlParagraph(tr("Test the last release and report bugs."))); } block.addInRightColumn(new OfferBlock(selectedOffer, true)); generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock); break; case FINISHED: offersBlock.add(new HtmlTitle(tr("Finished offer"), 1)); offersBlock.add(block = new BicolumnOfferBlock(true)); block.addInLeftColumn(new HtmlParagraph(tr("This offer is finished."))); block.addInRightColumn(new OfferBlock(selectedOffer, true)); generateOldOffersList(offers, nbUnselected, selectedOffer, offersBlock); break; case DISCARDED: offersBlock.add(new HtmlTitle(tr("Feature discarded ..."), 1)); break; default: break; } add(offersBlock); }
diff --git a/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java b/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java index 44bdb07..94b95a6 100644 --- a/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java +++ b/src/org/opensolaris/opengrok/analysis/sql/SQLAnalyzer.java @@ -1,69 +1,69 @@ /* * 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.analysis.sql; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import org.opensolaris.opengrok.analysis.FileAnalyzerFactory; import org.opensolaris.opengrok.analysis.plain.PlainAnalyzer; import org.opensolaris.opengrok.configuration.Project; import org.opensolaris.opengrok.history.Annotation; public class SQLAnalyzer extends PlainAnalyzer { private final SQLXref xref = new SQLXref((Reader)null); public SQLAnalyzer(FileAnalyzerFactory factory) { super(factory); } /** * Write a cross referenced HTML file. * @param out Writer to write HTML cross-reference */ public void writeXref(Writer out) throws IOException { xref.reInit(content, len); xref.project = project; - // @TODO xref.setDefs(defs); + xref.setDefs(defs); xref.write(out); } /** * Write a cross referenced HTML file. Reads the source from * an input stream. * * @param in input source * @param out output xref writer * @param annotation annotation for the file (could be null) */ static void writeXref(InputStream in, Writer out, Annotation annotation, Project project) throws IOException { SQLXref xref = new SQLXref(in); xref.annotation = annotation; xref.project = project; xref.write(out); } }
true
true
public void writeXref(Writer out) throws IOException { xref.reInit(content, len); xref.project = project; // @TODO xref.setDefs(defs); xref.write(out); }
public void writeXref(Writer out) throws IOException { xref.reInit(content, len); xref.project = project; xref.setDefs(defs); xref.write(out); }
diff --git a/android/src/com/google/zxing/client/android/camera/CameraManager.java b/android/src/com/google/zxing/client/android/camera/CameraManager.java index 2eb094a2..dcc04ab4 100755 --- a/android/src/com/google/zxing/client/android/camera/CameraManager.java +++ b/android/src/com/google/zxing/client/android/camera/CameraManager.java @@ -1,331 +1,331 @@ /* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android.camera; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Point; import android.graphics.Rect; import android.hardware.Camera; import android.os.Build; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; import com.google.zxing.PlanarYUVLuminanceSource; import com.google.zxing.client.android.camera.open.OpenCameraManager; import java.lang.Math; import java.io.IOException; /** * This object wraps the Camera service object and expects to be the only one talking to it. The * implementation encapsulates the steps needed to take preview-sized images, which are used for * both preview and decoding. * * @author [email protected] (Daniel Switkin) */ @TargetApi(Build.VERSION_CODES.FROYO) //Because getHorizontalViewAngle and getVerticalViewAngle only support after FROYO. public final class CameraManager { private static final String TAG = CameraManager.class.getSimpleName(); private final Context context; private final CameraConfigurationManager configManager; private Camera camera; private AutoFocusManager autoFocusManager; private Rect framingRect; private Rect framingRectInPreview; private boolean initialized; private boolean previewing; private int requestedFramingRectWidth; private int requestedFramingRectHeight; private double HorizontalViewAngle; private double VerticalViewAngle; /** * Preview frames are delivered here, which we pass on to the registered handler. Make sure to * clear the handler so it will only receive one message. */ private final PreviewCallback previewCallback; public CameraManager(Context context) { this.context = context; this.configManager = new CameraConfigurationManager(context); previewCallback = new PreviewCallback(configManager); } /** * Opens the camera driver and initializes the hardware parameters. * * @param holder The surface object which the camera will draw preview frames into. * @throws IOException Indicates the camera driver failed to open. */ public synchronized void openDriver(SurfaceHolder holder) throws IOException { Camera theCamera = camera; if (theCamera == null) { theCamera = new OpenCameraManager().build().open(); if (theCamera == null) { throw new IOException(); } camera = theCamera; } theCamera.setPreviewDisplay(holder); if (!initialized) { initialized = true; configManager.initFromCameraParameters(theCamera); if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight); requestedFramingRectWidth = 0; requestedFramingRectHeight = 0; } } Camera.Parameters parameters = theCamera.getParameters(); //Because parameters from device is not correct. We measure by ourself and get precise value. //Current value is for NEW HTC ONE //HorizontalViewAngle = Math.PI / 180 * parameters.getHorizontalViewAngle(); //VerticalViewAngle = Math.PI / 180 * parameters.getVerticalViewAngle(); - HorizontalViewAngle = 1.38834772296; - VerticalViewAngle = 0.78507758145; + HorizontalViewAngle = 1.48762690614; + VerticalViewAngle = 0.84121759574; String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save these, temporarily try { configManager.setDesiredCameraParameters(theCamera, false); } catch (RuntimeException re) { // Driver failed Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); // Reset: if (parametersFlattened != null) { parameters = theCamera.getParameters(); parameters.unflatten(parametersFlattened); try { theCamera.setParameters(parameters); configManager.setDesiredCameraParameters(theCamera, true); } catch (RuntimeException re2) { // Well, darn. Give up Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); } } } } /** * return camera horizontal view angle.(unit is Radian) * @author [email protected] */ public double getHorizontalViewAngle() { return HorizontalViewAngle; } /** * return camera vertical view angle.(unit is Radian) * @author [email protected] */ public double getVerticalViewAngle() { return VerticalViewAngle; } /** * Pass camera resolution * @author [email protected] * @return camera resolution */ public Point getCameraResolution() { return configManager.getCameraResolution(); } public synchronized boolean isOpen() { return camera != null; } /** * Closes the camera driver if still in use. */ public synchronized void closeDriver() { if (camera != null) { camera.release(); camera = null; // Make sure to clear these each time we close the camera, so that any scanning rect // requested by intent is forgotten. framingRect = null; framingRectInPreview = null; } } /** * Asks the camera hardware to begin drawing preview frames to the screen. */ public synchronized void startPreview() { Camera theCamera = camera; if (theCamera != null && !previewing) { theCamera.startPreview(); previewing = true; autoFocusManager = new AutoFocusManager(context, camera); } } /** * Tells the camera to stop drawing preview frames. */ public synchronized void stopPreview() { if (autoFocusManager != null) { autoFocusManager.stop(); autoFocusManager = null; } if (camera != null && previewing) { camera.stopPreview(); previewCallback.setHandler(null, 0); previewing = false; } } /** * Convenience method for {@link com.google.zxing.client.android.CaptureActivity} */ public synchronized void setTorch(boolean newSetting) { if (newSetting != configManager.getTorchState(camera)) { if (camera != null) { if (autoFocusManager != null) { autoFocusManager.stop(); } configManager.setTorch(camera, newSetting); if (autoFocusManager != null) { autoFocusManager.start(); } } } } /** * A single preview frame will be returned to the handler supplied. The data will arrive as byte[] * in the message.obj field, with width and height encoded as message.arg1 and message.arg2, * respectively. * * @param handler The handler to send the message to. * @param message The what field of the message to be sent. */ public synchronized void requestPreviewFrame(Handler handler, int message) { Camera theCamera = camera; if (theCamera != null && previewing) { previewCallback.setHandler(handler, message); theCamera.setOneShotPreviewCallback(previewCallback); } } /** * Calculates the framing rect which the UI should draw to show the user where to place the * barcode. This target helps with alignment as well as forces the user to hold the device * far enough away to ensure the image will be in focus. * * @return The rectangle to draw on screen in window coordinates. * bravesheng: Modified code to let system scan whole screen for localization use. */ public synchronized Rect getFramingRect() { if (framingRect == null) { if (camera == null) { return null; } Point screenResolution = configManager.getScreenResolution(); if (screenResolution == null) { // Called early, before init even finished return null; } //bravesheng: set to let zxing scan whole screen int width = screenResolution.x; int height = screenResolution.y; int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated framing rect: " + framingRect); } return framingRect; } /** * Like {@link #getFramingRect} but coordinates are in terms of the preview frame, * not UI / screen. */ public synchronized Rect getFramingRectInPreview() { if (framingRectInPreview == null) { Rect framingRect = getFramingRect(); if (framingRect == null) { return null; } Rect rect = new Rect(framingRect); Point cameraResolution = configManager.getCameraResolution(); Point screenResolution = configManager.getScreenResolution(); if (cameraResolution == null || screenResolution == null) { // Called early, before init even finished return null; } rect.left = rect.left * cameraResolution.x / screenResolution.x; rect.right = rect.right * cameraResolution.x / screenResolution.x; rect.top = rect.top * cameraResolution.y / screenResolution.y; rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y; framingRectInPreview = rect; } return framingRectInPreview; } /** * Allows third party apps to specify the scanning rectangle dimensions, rather than determine * them automatically based on screen resolution. * * @param width The width in pixels to scan. * @param height The height in pixels to scan. */ public synchronized void setManualFramingRect(int width, int height) { if (initialized) { Point screenResolution = configManager.getScreenResolution(); if (width > screenResolution.x) { width = screenResolution.x; } if (height > screenResolution.y) { height = screenResolution.y; } int leftOffset = (screenResolution.x - width) / 2; int topOffset = (screenResolution.y - height) / 2; framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); Log.d(TAG, "Calculated manual framing rect: " + framingRect); framingRectInPreview = null; } else { requestedFramingRectWidth = width; requestedFramingRectHeight = height; } } /** * A factory method to build the appropriate LuminanceSource object based on the format * of the preview buffers, as described by Camera.Parameters. * * @param data A preview frame. * @param width The width of the image. * @param height The height of the image. * @return A PlanarYUVLuminanceSource instance. */ public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) { Rect rect = getFramingRectInPreview(); if (rect == null) { return null; } // Go ahead and assume it's YUV rather than die. return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(), false); } }
true
true
public synchronized void openDriver(SurfaceHolder holder) throws IOException { Camera theCamera = camera; if (theCamera == null) { theCamera = new OpenCameraManager().build().open(); if (theCamera == null) { throw new IOException(); } camera = theCamera; } theCamera.setPreviewDisplay(holder); if (!initialized) { initialized = true; configManager.initFromCameraParameters(theCamera); if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight); requestedFramingRectWidth = 0; requestedFramingRectHeight = 0; } } Camera.Parameters parameters = theCamera.getParameters(); //Because parameters from device is not correct. We measure by ourself and get precise value. //Current value is for NEW HTC ONE //HorizontalViewAngle = Math.PI / 180 * parameters.getHorizontalViewAngle(); //VerticalViewAngle = Math.PI / 180 * parameters.getVerticalViewAngle(); HorizontalViewAngle = 1.38834772296; VerticalViewAngle = 0.78507758145; String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save these, temporarily try { configManager.setDesiredCameraParameters(theCamera, false); } catch (RuntimeException re) { // Driver failed Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); // Reset: if (parametersFlattened != null) { parameters = theCamera.getParameters(); parameters.unflatten(parametersFlattened); try { theCamera.setParameters(parameters); configManager.setDesiredCameraParameters(theCamera, true); } catch (RuntimeException re2) { // Well, darn. Give up Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); } } } }
public synchronized void openDriver(SurfaceHolder holder) throws IOException { Camera theCamera = camera; if (theCamera == null) { theCamera = new OpenCameraManager().build().open(); if (theCamera == null) { throw new IOException(); } camera = theCamera; } theCamera.setPreviewDisplay(holder); if (!initialized) { initialized = true; configManager.initFromCameraParameters(theCamera); if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight); requestedFramingRectWidth = 0; requestedFramingRectHeight = 0; } } Camera.Parameters parameters = theCamera.getParameters(); //Because parameters from device is not correct. We measure by ourself and get precise value. //Current value is for NEW HTC ONE //HorizontalViewAngle = Math.PI / 180 * parameters.getHorizontalViewAngle(); //VerticalViewAngle = Math.PI / 180 * parameters.getVerticalViewAngle(); HorizontalViewAngle = 1.48762690614; VerticalViewAngle = 0.84121759574; String parametersFlattened = parameters == null ? null : parameters.flatten(); // Save these, temporarily try { configManager.setDesiredCameraParameters(theCamera, false); } catch (RuntimeException re) { // Driver failed Log.w(TAG, "Camera rejected parameters. Setting only minimal safe-mode parameters"); Log.i(TAG, "Resetting to saved camera params: " + parametersFlattened); // Reset: if (parametersFlattened != null) { parameters = theCamera.getParameters(); parameters.unflatten(parametersFlattened); try { theCamera.setParameters(parameters); configManager.setDesiredCameraParameters(theCamera, true); } catch (RuntimeException re2) { // Well, darn. Give up Log.w(TAG, "Camera rejected even safe-mode parameters! No configuration"); } } } }
diff --git a/java/drda/org/apache/derby/impl/drda/NetworkServerControlImpl.java b/java/drda/org/apache/derby/impl/drda/NetworkServerControlImpl.java index ed676e426..38f181445 100644 --- a/java/drda/org/apache/derby/impl/drda/NetworkServerControlImpl.java +++ b/java/drda/org/apache/derby/impl/drda/NetworkServerControlImpl.java @@ -1,4074 +1,4074 @@ /* Derby - Class org.apache.derby.impl.drda.NetworkServerControlImpl Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.drda; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import javax.net.SocketFactory; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLServerSocketFactory; import java.net.UnknownHostException; import java.nio.charset.Charset; import java.security.Permission; import java.security.AccessController; import java.security.AccessControlException; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; import org.apache.derby.drda.NetworkServerControl; import org.apache.derby.security.SystemPermission; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.jdbc.DRDAServerStarter; import org.apache.derby.iapi.reference.Attribute; import org.apache.derby.iapi.reference.DRDAConstants; import org.apache.derby.iapi.reference.Module; import org.apache.derby.iapi.reference.Property; import org.apache.derby.iapi.reference.SQLState; import org.apache.derby.iapi.services.i18n.MessageService; import org.apache.derby.iapi.services.info.ProductGenusNames; import org.apache.derby.iapi.services.info.ProductVersionHolder; import org.apache.derby.iapi.services.info.Version; import org.apache.derby.iapi.services.jmx.ManagementService; import org.apache.derby.iapi.services.monitor.Monitor; import org.apache.derby.iapi.services.property.PropertyUtil; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.tools.i18n.LocalizedOutput; import org.apache.derby.iapi.tools.i18n.LocalizedResource; import org.apache.derby.iapi.util.CheapDateFormatter; import org.apache.derby.iapi.util.StringUtil; import org.apache.derby.impl.jdbc.EmbedSQLException; import org.apache.derby.impl.jdbc.Util; import org.apache.derby.iapi.jdbc.AuthenticationService; import org.apache.derby.iapi.reference.MessageId; import org.apache.derby.iapi.security.SecurityUtil; import org.apache.derby.mbeans.VersionMBean; import org.apache.derby.mbeans.drda.NetworkServerMBean; /** NetworkServerControlImpl does all the work for NetworkServerControl @see NetworkServerControl for description */ public final class NetworkServerControlImpl { private final static int NO_USAGE_MSGS= 12; private final static String [] COMMANDS = {"start","shutdown","trace","tracedirectory","ping", "logconnections", "sysinfo", "runtimeinfo", "maxthreads", "timeslice", ""}; // number of required arguments for each command private final static int [] COMMAND_ARGS = {0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0}; public final static int COMMAND_START = 0; public final static int COMMAND_SHUTDOWN = 1; public final static int COMMAND_TRACE = 2; public final static int COMMAND_TRACEDIRECTORY = 3; public final static int COMMAND_TESTCONNECTION = 4; public final static int COMMAND_LOGCONNECTIONS = 5; public final static int COMMAND_SYSINFO = 6; public final static int COMMAND_RUNTIME_INFO = 7; public final static int COMMAND_MAXTHREADS = 8; public final static int COMMAND_TIMESLICE = 9; public final static int COMMAND_PROPERTIES = 10; public final static int COMMAND_UNKNOWN = -1; public final static String [] DASHARGS = {"p", "d", "user", "password", "ld", "ea", "ep", "b", "h", "s", "noSecurityManager", "ssl"}; public final static int DASHARG_PORT = 0; public final static int DASHARG_DATABASE = 1; public final static int DASHARG_USER = 2; public final static int DASHARG_PASSWORD = 3; public final static int DASHARG_LOADSYSIBM = 4; public final static int DASHARG_ENCALG = 5; public final static int DASHARG_ENCPRV = 6; public final static int DASHARG_BOOTPASSWORD = 7; public final static int DASHARG_HOST = 8; public final static int DASHARG_SESSION = 9; public final static int DASHARG_UNSECURE = 10; private final static int DASHARG_SSL = 11; // command protocol version - you need to increase this number each time // the command protocol changes // DERBY-2109: shutdown command now transmits user credentials private final static int PROTOCOL_VERSION = 2; private final static String COMMAND_HEADER = "CMD:"; private final static String REPLY_HEADER = "RPY:"; private final static int REPLY_HEADER_LENGTH = REPLY_HEADER.length(); private final static int OK = 0; private final static int WARNING = 1; private final static int ERROR = 2; private final static int SQLERROR = 3; private final static int SQLWARNING = 4; private final static String DRDA_PROP_MESSAGES = "org.apache.derby.loc.drda.messages"; private final static String DRDA_PROP_DEBUG = "derby.drda.debug"; private final static String CLOUDSCAPE_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver"; public final static String UNEXPECTED_ERR = "Unexpected exception"; private final static int MIN_MAXTHREADS = -1; private final static int MIN_TIMESLICE = -1; private final static int USE_DEFAULT = -1; private final static int DEFAULT_MAXTHREADS = 0; //for now create whenever needed private final static int DEFAULT_TIMESLICE = 0; //for now never yield private final static String DEFAULT_HOST = "localhost"; private final static String DRDA_MSG_PREFIX = "DRDA_"; private final static String DEFAULT_LOCALE= "en"; private final static String DEFAULT_LOCALE_COUNTRY="US"; // Check up to 10 seconds to see if shutdown occurred private final static int SHUTDOWN_CHECK_ATTEMPTS = 100; private final static int SHUTDOWN_CHECK_INTERVAL= 100; // maximum reply size private final static int MAXREPLY = 32767; // Application Server Attributes. protected static String att_srvclsnm; protected final static String ATT_SRVNAM = "NetworkServerControl"; protected static String att_extnam; protected static String att_srvrlslv; protected static String prdId; protected static byte[] prdIdBytes_; private static String buildNumber; private static String versionString; // we will use single or mixed, not double byte to reduce traffic on the // wire, this is in keeping with JCC // Note we specify UTF8 for the single byte encoding even though it can // be multi-byte. protected final static int CCSIDSBC = 1208; //use UTF8 protected final static int CCSIDMBC = 1208; //use UTF8 protected final static String DEFAULT_ENCODING = "UTF8"; // use UTF8 for writing final static Charset DEFAULT_CHARSET = Charset.forName(DEFAULT_ENCODING); protected final static int DEFAULT_CCSID = 1208; protected final static byte SPACE_CHAR = 32; // Application Server manager levels - this needs to be in sync // with CodePoint.MGR_CODEPOINTS protected final static int [] MGR_LEVELS = { 7, // AGENT 4, // CCSID Manager 0, // CNMAPPC not implemented 0, // CMNSYNCPT not implemented 5, // CMNTCPIP 0, // DICTIONARY 7, // RDB 0, // RSYNCMGR 7, // SECMGR 7, // SQLAM 0, // SUPERVISOR 0, // SYNCPTMGR 7 // XAMGR }; protected PrintWriter logWriter; // console protected PrintWriter cloudscapeLogWriter; // derby.log private static Driver cloudscapeDriver; // error types private final static int ERRTYPE_SEVERE = 1; private final static int ERRTYPE_USER = 2; private final static int ERRTYPE_INFO = 3; private final static int ERRTYPE_UNKNOWN = -1; // command argument information private Vector commandArgs = new Vector(); private String databaseArg; // DERBY-2109: Note that derby JDBC clients have a default user name // "APP" (= Property.DEFAULT_USER_NAME) assigned if they don't provide // credentials. We could do the same for NetworkServerControl clients // here, but this class is robust enough to allow for null as default. private String userArg = null; private String passwordArg = null; private String bootPasswordArg; private String encAlgArg; private String encPrvArg; private String hostArg = DEFAULT_HOST; private InetAddress hostAddress; private int sessionArg; private boolean unsecureArg; // Used to debug memory in SanityManager.DEBUG mode private memCheck mc; // reply buffer private byte [] replyBuffer; private int replyBufferCount; //length of reply private int replyBufferPos; //current position in reply // // server configuration // // static values - set at start can't be changed once server has started private int portNumber = NetworkServerControl.DEFAULT_PORTNUMBER; // port server listens to // configurable values private String traceDirectory; // directory to place trace files in private Object traceDirectorySync = new Object();// object to use for syncing private boolean traceAll; // trace all sessions private Object traceAllSync = new Object(); // object to use for syncing reading // and changing trace all private Object serverStartSync = new Object(); // for syncing start of server. private boolean logConnections; // log connects private Object logConnectionsSync = new Object(); // object to use for syncing // logConnections value private int minThreads; // default minimum number of connection threads private int maxThreads; // default maximum number of connection threads private Object threadsSync = new Object(); // object to use for syncing reading // and changing default min and max threads private int timeSlice; // default time slice of a session to a thread private Object timeSliceSync = new Object();// object to use for syncing reading // and changing timeSlice private boolean keepAlive = true; // keepAlive value for client socket private int minPoolSize; //minimum pool size for pooled connections private int maxPoolSize; //maximum pool size for pooled connections private Object poolSync = new Object(); // object to use for syning reading protected boolean debugOutput = false; private boolean cleanupOnStart = false; // Should we clean up when starting the server? private boolean restartFlag = false; protected final static int INVALID_OR_NOTSET_SECURITYMECHANISM = -1; // variable to store value set to derby.drda.securityMechanism // default value is -1 which indicates that this property isnt set or // the value is invalid private int allowOnlySecurityMechanism = INVALID_OR_NOTSET_SECURITYMECHANISM; // // variables for a client command session // private Socket clientSocket = null; private InputStream clientIs = null; private OutputStream clientOs = null; private ByteArrayOutputStream byteArrayOs = new ByteArrayOutputStream(); private DataOutputStream commandOs = new DataOutputStream(byteArrayOs); private Object shutdownSync = new Object(); private boolean shutdown; private int connNum; // number of connections since server started private ServerSocket serverSocket; private NetworkServerControlImpl serverInstance; private LocalizedResource langUtil; public String clientLocale; ArrayList localAddresses; // list of local addresses for checking admin // commands. // open sessions private Hashtable sessionTable = new Hashtable(); // current session private Session currentSession; // DRDAConnThreads private Vector threadList = new Vector(); // queue of sessions waiting for a free thread - the queue is managed // in a simple first come, first serve manner - no priorities private Vector runQueue = new Vector(); // number of DRDAConnThreads waiting for something to do private int freeThreads; // known application requesters private Hashtable appRequesterTable = new Hashtable(); // accessed by inner classes for privileged action private String propertyFileName; private NetworkServerControlImpl thisControl = this; // if the server is started from the command line, it should shutdown the // databases it has booted. private boolean shutdownDatabasesOnShutdown = false; // SSL related stuff private static final int SSL_OFF = 0; private static final int SSL_BASIC = 1; private static final int SSL_PEER_AUTHENTICATION = 2; private int sslMode = SSL_OFF; /** * Can EUSRIDPWD security mechanism be used with * the current JVM */ private static boolean SUPPORTS_EUSRIDPWD = false; /* * DRDA Specification for the EUSRIDPWD security mechanism * requires DH algorithm support with a 32-byte prime to be * used. Not all JCE implementations have support for this. * Hence here we need to find out if EUSRIDPWD can be used * with the current JVM. */ static { try { // The DecryptionManager class will instantiate objects of the required // security algorithms that are needed for EUSRIDPWD // An exception will be thrown if support is not available // in the JCE implementation in the JVM in which the server // is started. new DecryptionManager(); SUPPORTS_EUSRIDPWD = true; }catch(Exception e) { // if an exception is thrown, ignore exception. // set SUPPORTS_EUSRIDPWD to false indicating that the server // does not have support for EUSRIDPWD security mechanism SUPPORTS_EUSRIDPWD = false; } } /** * Get the host where we listen for connections. */ public String getHost() { return hostArg; } /** * Return true if the customer forcibly overrode our decision to install a * default SecurityManager. */ public boolean runningUnsecure() { return unsecureArg; } // constructor public NetworkServerControlImpl() throws Exception { init(); getPropertyInfo(); } /** * Internal constructor for NetworkServerControl API. * @param address InetAddress to listen on, throws NPE if null * @param portNumber portNumber to listen on, -1 use property or default * @throws Exception on error * @see NetworkServerControl */ public NetworkServerControlImpl(InetAddress address, int portNumber) throws Exception { this(); this.hostAddress = address; this.portNumber = (portNumber <= 0) ? this.portNumber: portNumber; this.hostArg = address.getHostAddress(); } /** * Internal constructor for NetworkServerControl API. * @param userName the user name for actions requiring authorization * @param password the password for actions requiring authorization * @throws Exception on error * @see NetworkServerControl */ public NetworkServerControlImpl(String userName, String password) throws Exception { this(); this.userArg = userName; this.passwordArg = password; } /** * Internal constructor for NetworkServerControl API. * @param address InetAddress to listen on, throws NPE if null * @param portNumber portNumber to listen on, -1 use property or default * @param userName the user name for actions requiring authorization * @param password the password for actions requiring authorization * @throws Exception on error * @see NetworkServerControl */ public NetworkServerControlImpl(InetAddress address, int portNumber, String userName, String password) throws Exception { this(address, portNumber); this.userArg = userName; this.passwordArg = password; } private void init() throws Exception { // adjust the application in accordance with derby.ui.locale and derby.ui.codeset langUtil = new LocalizedResource(null,null,DRDA_PROP_MESSAGES); serverInstance = this; //set Server attributes to be used in EXCSAT ProductVersionHolder myPVH = getNetProductVersionHolder(); att_extnam = ATT_SRVNAM + " " + java.lang.Thread.currentThread().getName(); att_srvclsnm = myPVH.getProductName(); versionString = myPVH.getVersionBuildString(true); String majorStr = String.valueOf(myPVH.getMajorVersion()); String minorStr = String.valueOf(myPVH.getMinorVersion()); // Maintenance version. Server protocol version. // Only changed if client needs to recognize a new server version. String drdaMaintStr = String.valueOf(myPVH.getDrdaMaintVersion()); // PRDID format as JCC expects it: CSSMMmx // MM = major version // mm = minor version // x = drda MaintenanceVersion prdId = DRDAConstants.DERBY_DRDA_SERVER_ID; if (majorStr.length() == 1) prdId += "0"; prdId += majorStr; if (minorStr.length() == 1) prdId += "0"; prdId += minorStr; prdId += drdaMaintStr; att_srvrlslv = prdId + "/" + myPVH.getVersionBuildString(true); // Precompute this to save some cycles prdIdBytes_ = prdId.getBytes(DEFAULT_ENCODING); if (SanityManager.DEBUG) { if (majorStr.length() > 2 || minorStr.length() > 2 || drdaMaintStr.length() > 1) SanityManager.THROWASSERT("version values out of expected range for PRDID"); } buildNumber = myPVH.getBuildNumber(); } private PrintWriter makePrintWriter( OutputStream out) { if (out != null) return new PrintWriter(out, true /* flush the buffer at the end of each line */); else return null; } protected static Driver getDriver() { return cloudscapeDriver; } /******************************************************************************** * Implementation of NetworkServerControl API * The server commands throw exceptions for errors, so that users can handle * them themselves in addition to having the errors written to the console * and possibly derby.log. To turn off logging the errors to the console, * set the output writer to null. ********************************************************************************/ /** * Set the output stream for console messages * If this is set to null, no messages will be written to the console * * @param outWriter output stream for console messages */ public void setLogWriter(PrintWriter outWriter) { // wrap the user-set outWriter with, autoflush to true. // this will ensure that messages to console will be // written out to the outWriter on a println. // DERBY-1466 if ( outWriter != null ) logWriter = new PrintWriter(outWriter,true); else logWriter = outWriter; } /** * Write an error message to console output stream * and throw an exception for this error * * @param msg error message * @exception Exception */ public void consoleError(String msg) throws Exception { consoleMessage(msg, true); throw new Exception(msg); } /** * Write an exception to console output stream, * but only if debugOutput is true. * * @param e exception */ public void consoleExceptionPrint(Exception e) { if (debugOutput == true) consoleExceptionPrintTrace(e); return; } /** * Write an exception (with trace) to console * output stream. * * @param e exception */ public void consoleExceptionPrintTrace(Throwable e) { consoleMessage(e.getMessage(), true); PrintWriter lw = logWriter; if (lw != null) { synchronized (lw) { e.printStackTrace(lw); } } else { e.printStackTrace(); } lw = cloudscapeLogWriter; if (lw != null) { synchronized(lw) { e.printStackTrace(lw); } } } /** * Write a message to console output stream * * @param msg message * @param printTimeStamp Whether to prepend a timestamp to the message or not */ public void consoleMessage(String msg, boolean printTimeStamp) { // print to console if we have one PrintWriter lw = logWriter; if (lw != null) { synchronized(lw) { if (printTimeStamp) { lw.println(getFormattedTimestamp() + " : " + msg); } else { lw.println(msg); } } } // always print to derby.log lw = cloudscapeLogWriter; if (lw != null) synchronized(lw) { if (printTimeStamp) { Monitor.logMessage(getFormattedTimestamp() + " : " + msg); } else { Monitor.logMessage(msg); } } } /** * Start a network server. Launches a separate thread with * DRDAServerStarter. Want to use Monitor.startModule, * so it can all get shutdown when Derby shuts down, but * can't get it working right now. * * @param consoleWriter PrintWriter to which server console will be * output. Null will disable console output. * * * @exception Exception throws an exception if an error occurs */ public void start(PrintWriter consoleWriter) throws Exception { DRDAServerStarter starter = new DRDAServerStarter(); starter.setStartInfo(hostAddress,portNumber,consoleWriter); this.setLogWriter(consoleWriter); startNetworkServer(); starter.boot(false,null); } /** * Create the right kind of server socket */ private ServerSocket createServerSocket() throws IOException { if (hostAddress == null) hostAddress = InetAddress.getByName(hostArg); // Make a list of valid // InetAddresses for NetworkServerControl // admin commands. buildLocalAddressList(hostAddress); // Create the right kind of socket switch (getSSLMode()) { case SSL_OFF: default: ServerSocketFactory sf = ServerSocketFactory.getDefault(); return sf.createServerSocket(portNumber ,0, hostAddress); case SSL_BASIC: SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); return (SSLServerSocket)ssf.createServerSocket(portNumber, 0, hostAddress); case SSL_PEER_AUTHENTICATION: SSLServerSocketFactory ssf2 = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); SSLServerSocket sss2= (SSLServerSocket)ssf2.createServerSocket(portNumber, 0, hostAddress); sss2.setNeedClientAuth(true); return sss2; } } /** * Start a network server * * @param consoleWriter PrintWriter to which server console will be * output. Null will disable console output. * * * @exception Exception throws an exception if an error occurs */ public void blockingStart(PrintWriter consoleWriter) throws Exception { startNetworkServer(); setLogWriter(consoleWriter); cloudscapeLogWriter = Monitor.getStream().getPrintWriter(); if (SanityManager.DEBUG && debugOutput) { memCheck.showmem(); mc = new memCheck(200000); mc.start(); } // Open a server socket listener try{ serverSocket = (ServerSocket) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return createServerSocket(); } }); } catch (PrivilegedActionException e) { Exception e1 = e.getException(); // Test for UnknownHostException first since it's a // subbclass of IOException (and consolePropertyMessage // throws an exception when the severity is S (or U). if (e1 instanceof UnknownHostException) { consolePropertyMessage("DRDA_UnknownHost.S", hostArg); } else if (e1 instanceof IOException) { consolePropertyMessage("DRDA_ListenPort.S", new String [] { Integer.toString(portNumber), hostArg, // Since SocketException // is used for a phletora // of situations, we need // to communicate the // underlying exception // string to the user. e1.toString()}); } else { throw e1; } } catch (Exception e) { // If we find other (unexpected) errors, we ultimately exit--so make // sure we print the error message before doing so (Beetle 5033). throwUnexpectedException(e); } switch (getSSLMode()) { default: case SSL_OFF: consolePropertyMessage("DRDA_Ready.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; case SSL_BASIC: consolePropertyMessage("DRDA_SSLReady.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; case SSL_PEER_AUTHENTICATION: consolePropertyMessage("DRDA_SSLClientAuthReady.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; } // We accept clients on a separate thread so we don't run into a problem // blocking on the accept when trying to process a shutdown final ClientThread clientThread = (ClientThread) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return new ClientThread(thisControl, serverSocket); } } ); clientThread.start(); // Now that we are up and running, register any MBeans ManagementService mgmtService = ((ManagementService) Monitor.getSystemModule(Module.JMX)); final Object versionMBean = mgmtService.registerMBean( new Version( getNetProductVersionHolder(), SystemPermission.SERVER), VersionMBean.class, "type=Version,jar=derbynet.jar"); final Object networkServerMBean = mgmtService.registerMBean( new NetworkServerMBeanImpl(this), NetworkServerMBean.class, "type=NetworkServer"); // wait until we are told to shutdown or someone sends an InterruptedException synchronized(shutdownSync) { try { shutdownSync.wait(); } catch (InterruptedException e) { shutdown = true; } } try { AccessController.doPrivileged( new PrivilegedAction() { public Object run() { // Need to interrupt the memcheck thread if it is sleeping. if (mc != null) mc.interrupt(); //interrupt client thread clientThread.interrupt(); return null; } }); } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } // Close out the sessions synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); try { session.close(); } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } } } synchronized (threadList) { //interupt any connection threads still active for (int i = 0; i < threadList.size(); i++) { try { final DRDAConnThread threadi = (DRDAConnThread)threadList.get(i); threadi.close(); AccessController.doPrivileged( new PrivilegedAction() { public Object run() { threadi.interrupt(); return null; } }); } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } } threadList.clear(); } // close the listener socket try{ serverSocket.close(); }catch(IOException e){ consolePropertyMessage("DRDA_ListenerClose.S", true); } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } // Wake up those waiting on sessions, so // they can close down try{ synchronized (runQueue) { runQueue.notifyAll(); } } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } // And now unregister any MBeans. try { mgmtService.unregisterMBean(versionMBean); mgmtService.unregisterMBean(networkServerMBean); } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } if (shutdownDatabasesOnShutdown) { // Shutdown Derby try { // tell driver to shutdown the engine if (cloudscapeDriver != null) { // DERBY-2109: pass user credentials for driver shutdown final Properties p = new Properties(); if (userArg != null) { p.setProperty("user", userArg); } if (passwordArg != null) { p.setProperty("password", passwordArg); } cloudscapeDriver.connect("jdbc:derby:;shutdown=true", p); } } catch (SQLException sqle) { // If we can't shutdown Derby, perhaps, authentication has // failed or System Privileges weren't granted. We will just // print a message to the console and proceed. String expectedState = StandardException.getSQLStateFromIdentifier( SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN); if (!expectedState.equals(sqle.getSQLState())) { consolePropertyMessage("DRDA_ShutdownWarning.I", sqle.getMessage()); } } catch (Exception exception) { + consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); - consoleExceptionPrintTrace(exception); } } consolePropertyMessage("DRDA_ShutdownSuccess.I", new String [] {att_srvclsnm, versionString}); } /** * Load Derby and save driver for future use. * We can't call Driver Manager when the client connects, * because they might be holding the DriverManager lock. * * */ protected void startNetworkServer() throws Exception { // we start the Derby server here. boolean restartCheck = this.restartFlag; synchronized (serverStartSync) { if (restartCheck == this.restartFlag) { // then we can go ahead and restart the server (odds // that some else has just done so are very slim (but not // impossible--however, even if it does happen, things // should still work correctly, just not as efficiently...)) try { if (cleanupOnStart) { // we're restarting the server (probably after a shutdown // exception), so we need to clean up first. // Close and remove sessions on runQueue. synchronized (runQueue) { for (int i = 0; i < runQueue.size(); i++) { Session s = (Session) runQueue.get(i); s.close(); removeFromSessionTable(s.getConnNum()); } runQueue.clear(); } // DERBY-1326: There could be active threads that // contain old/invalid sessions. These sessions won't // be cleaned up until there is some activity on // them. We could optimize this by going through // sessionTable and closing the sessions' socket // streams. // Unload driver, then restart the server. cloudscapeDriver = null; // so it gets collected. System.gc(); } // start the server. Class.forName(CLOUDSCAPE_DRIVER).newInstance(); cloudscapeDriver = DriverManager.getDriver(Attribute.PROTOCOL); } catch (Exception e) { this.consoleExceptionPrintTrace(e); consolePropertyMessage("DRDA_LoadException.S", e.getMessage()); } cleanupOnStart = true; this.restartFlag = !this.restartFlag; } // else, multiple threads hit this synchronize block at the same // time, but one of them already executed it--so all others just // return and do nothing (no need to restart the server multiple // times in a row). } } /** * Shutdown a network server * * @exception Exception throws an exception if an error occurs */ public void shutdown() throws Exception { // Wait up to 10 seconds for things to really shut down // need a quiet ping so temporarily disable the logwriter PrintWriter savWriter; int ntry; try { setUpSocket(); writeCommandHeader(COMMAND_SHUTDOWN); // DERBY-2109: transmit user credentials for System Privileges check writeLDString(userArg); writeLDString(passwordArg); send(); readResult(); savWriter = logWriter; // DERBY-1571: If logWriter is null, stack traces are printed to // System.err. Set logWriter to a silent stream to suppress stack // traces too. FilterOutputStream silentStream = new FilterOutputStream(null) { public void write(int b) { } public void flush() { } public void close() { } }; setLogWriter(new PrintWriter(silentStream)); for (ntry = 0; ntry < SHUTDOWN_CHECK_ATTEMPTS; ntry++) { Thread.sleep(SHUTDOWN_CHECK_INTERVAL); try { pingWithNoOpen(); } catch (Exception e) { // as soon as we can't ping return break; } } } finally { closeSocket(); } if (ntry == SHUTDOWN_CHECK_ATTEMPTS) consolePropertyMessage("DRDA_ShutdownError.S", new String [] { Integer.toString(portNumber), hostArg}); logWriter= savWriter; return; } /** * Authenticates the user and checks for shutdown System Privileges. * No Network communication needed. * * To perform this check the following policy grant is required * <ul> * <li> to run the encapsulated test: * permission javax.security.auth.AuthPermission "doAsPrivileged"; * </ul> * or a SQLException will be raised detailing the cause. * <p> * In addition, for the test to succeed * <ul> * <li> the given user needs to be covered by a grant: * principal org.apache.derby.authentication.SystemPrincipal "..." {} * <li> that lists a shutdown permission: * permission org.apache.derby.security.SystemPermission "shutdown"; * </ul> * or it will fail with a SQLException detailing the cause. * * @param user The user to be checked for shutdown privileges * @throws SQLException if the privileges check fails */ /** * @throws SQLException if authentication or privileges check fails */ public void checkShutdownPrivileges() throws SQLException { // get the system's authentication service final AuthenticationService auth = ((AuthenticationService) Monitor.findService(AuthenticationService.MODULE, "authentication")); // authenticate user if (auth != null) { final Properties finfo = new Properties(); if (userArg != null) { finfo.setProperty("user", userArg); } if (passwordArg != null) { finfo.setProperty("password", passwordArg); } if (!auth.authenticate((String)null, finfo)) { // not a valid user throw Util.generateCsSQLException( SQLState.NET_CONNECT_AUTH_FAILED, MessageService.getTextMessage(MessageId.AUTH_INVALID)); } } // approve action if not running under a security manager if (System.getSecurityManager() == null) { return; } // the check try { final Permission sp = new SystemPermission( SystemPermission.SERVER, SystemPermission.SHUTDOWN); // For porting the network server to J2ME/CDC, consider calling // abstract method InternalDriver.checkShutdownPrivileges(user) // instead of static SecurityUtil.checkUserHasPermission(). // SecurityUtil.checkUserHasPermission(userArg, sp); } catch (AccessControlException ace) { throw Util.generateCsSQLException( SQLState.AUTH_SHUTDOWN_MISSING_PERMISSION, userArg, (Object)ace); // overloaded method } } /* Shutdown the server directly (If you have the original object) No Network communication needed. */ public void directShutdown() throws SQLException { // DERBY-2109: the public shutdown method now checks privileges checkShutdownPrivileges(); directShutdownInternal(); } /* Shutdown the server directly (If you have the original object) No Network communication needed. */ void directShutdownInternal() { // DERBY-2109: the direct, unchecked shutdown is made private shutdown = true; synchronized(shutdownSync) { // wake up the server thread shutdownSync.notifyAll(); } } /** */ public boolean isServerStarted() throws Exception { try { ping(); } catch (Exception e) { return false; } return true; } /** * Ping opening an new socket and close it. * @throws Exception */ public void ping() throws Exception { try { setUpSocket(); pingWithNoOpen(); } finally { closeSocket(); } } /** * Ping the server using the client socket that is already open. */ private void pingWithNoOpen() throws Exception { // database no longer used, but don't change the protocol // in case we add // authorization later. String database = null; // no longer used but don't change the protocol String user = null; String password = null; writeCommandHeader(COMMAND_TESTCONNECTION); writeLDString(database); writeLDString(user); writeLDString(password); send(); readResult(); } /** * Turn tracing on or off for all sessions * * @param on true to turn tracing on, false to turn tracing off * * @exception Exception throws an exception if an error occurs */ public void trace(boolean on) throws Exception { trace(0, on); } /** * Turn tracing on or off for one session or all sessions * * @param connNum the connNum of the session, 0 if all sessions * @param on true to turn tracing on, false to turn tracing off * * @exception Exception throws an exception if an error occurs */ public void trace(int connNum, boolean on) throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_TRACE); commandOs.writeInt(connNum); writeByte(on ? 1 : 0); send(); readResult(); consoleTraceMessage(connNum, on); } finally { closeSocket(); } } /** * Print trace change message to console * * @param on true to print tracing on, false to print tracing off * * @exception Exception throws an exception if an error occurs */ private void consoleTraceMessage(int connNum, boolean on) throws Exception { if (connNum == 0) consolePropertyMessage("DRDA_TraceChangeAll.I", on ? "DRDA_ON.I" : "DRDA_OFF.I"); else { String[] args = new String[2]; args[0] = on ? "DRDA_ON.I" : "DRDA_OFF.I"; args[1] = new Integer(connNum).toString(); consolePropertyMessage("DRDA_TraceChangeOne.I", args); } } /** * Turn logging connections on or off. When logging is turned on a message is * written to derby.log each time a connection is made. * * @param on true to turn on, false to turn off * * @exception Exception throws an exception if an error occurs */ public void logConnections(boolean on) throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_LOGCONNECTIONS); writeByte(on ? 1 : 0); send(); readResult(); } finally { closeSocket(); } } /** *@see NetworkServerControl#setTraceDirectory */ public void sendSetTraceDirectory(String traceDirectory) throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_TRACEDIRECTORY); writeLDString(traceDirectory); send(); readResult(); } finally { closeSocket(); } } /** *@see NetworkServerControl#getSysinfo */ public String sysinfo() throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_SYSINFO); send(); return readStringReply("DRDA_SysInfoError.S"); } finally { closeSocket(); } } /** *@see NetworkServerControl#getRuntimeInfo */ public String runtimeInfo() throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_RUNTIME_INFO); send(); return readStringReply("DRDA_RuntimeInfoError.S"); } finally { closeSocket(); } } /** * Display usage information * */ public void usage() { try { for (int i = 1; i <= NO_USAGE_MSGS; i++) consolePropertyMessage("DRDA_Usage"+i+".I", false); } catch (Exception e) {} // ignore exceptions - there shouldn't be any } /** * Connect to network server and set connection maxthread parameter * * @param max maximum number of connections, if 0, connections * created when no free connection available * if -1, use default * * @exception Exception throws an exception if an error occurs */ public void netSetMaxThreads(int max) throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_MAXTHREADS); commandOs.writeInt(max); send(); readResult(); int newval = readInt(); consolePropertyMessage("DRDA_MaxThreadsChange.I", new Integer( newval).toString()); } finally { closeSocket(); } } /** * Set network server connection timeslice parameter * * @param timeslice amount of time given to each session before yielding to * another session, if 0, never yield. if -1, use default. * * @exception Exception throws an exception if an error occurs */ public void netSetTimeSlice(int timeslice) throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_TIMESLICE); commandOs.writeInt(timeslice); send(); readResult(); int newval = readInt(); consolePropertyMessage("DRDA_TimeSliceChange.I", new Integer(newval).toString()); } finally { closeSocket(); } } /** * Get current properties * * @return Properties object containing properties * @exception Exception throws an exception if an error occurs */ public Properties getCurrentProperties() throws Exception { try { setUpSocket(); writeCommandHeader(COMMAND_PROPERTIES); send(); byte[] val = readBytesReply("DRDA_PropertyError.S"); Properties p = new Properties(); try { ByteArrayInputStream bs = new ByteArrayInputStream(val); p.load(bs); } catch (IOException io) { consolePropertyMessage("DRDA_IOException.S", io.getMessage()); } return p; } finally { closeSocket(); } } /** * Set a thread name to be something that is both meaningful and unique (primarily * for debugging purposes). * * The received thread's name is set to a new string of the form * [newName + "_n"], where 'n' is a unique thread id originally generated * by the jvm Thread constructor. If the default name of the thread has * been changed before getting here, then nothing is done. * * @param thrd An instance of a Thread object that still has its default * thread name (as generated by the jvm Thread constructor). This should * always be of the form "Thread-N", where N is a unique thread id * generated by the jvm. Ex. "Thread-0", "Thread-1", etc. * **/ public static void setUniqueThreadName(Thread thrd, String newName) { // First, pull off the unique thread id already found in thrd's default name; // we do so by searching for the '-' character, and then counting everything // after it as a N. if (thrd.getName().indexOf("Thread-") == -1) { // default name has been changed; don't do anything. return; } else { String oldName = thrd.getName(); thrd.setName(newName + "_" + oldName.substring(oldName.indexOf("-")+1, oldName.length())); } // end else. return; } /*******************************************************************************/ /* Protected methods */ /*******************************************************************************/ /** * Remove session from session table * * @param sessionid id of session to be removed */ protected void removeFromSessionTable(int sessionid) { sessionTable.remove(new Integer(sessionid)); } /** * processCommands reads and processes NetworkServerControlImpl commands sent * to the network server over the socket. The protocol used is * 4 bytes - String CMD: * 2 bytes - Protocol version * 1 byte - length of locale (0 for default) * n bytes - locale * 1 byte - length of codeset (0 for default) * n bytes - codeset * 1 byte - command * n bytes - parameters for the command * The server returns * 4 bytes - String RPY: * for most commands * 1 byte - command result, 0 - OK, 1 - warning, 2 - error * if warning or error * 1 bytes - length of message key * n bytes - message key * 1 byte - number of parameters to message * {2 bytes - length of parameter * n bytes - parameter} for each parameter * for sysinfo * 1 byte - command result, 0 - OK, 1 - warning, 2 - error * if OK * 2 bytes - length of sysinfo * n bytes - sysinfo * * * Note, the 3rd byte of the command must not be 'D0' to distinquish it * from DSS structures. * The protocol for the parameters for each command follows: * * Command: trace <connection id> {on | off} * Protocol: * 4 bytes - connection id - connection id of 0 means all sessions * 1 byte - 0 off, 1 on * * Command: logConnections {on | off} * Protocol: * 1 byte - 0 off, 1 on * * Command: shutdown * // DERBY-2109: transmit user credentials for System Privileges check * 2 bytes - length of user name * n bytes - user name * 2 bytes - length of password * n bytes - password * * Command: sysinfo * No parameters * * Command: dbstart * Protocol: * 2 bytes - length of database name * n bytes - database name * 2 bytes - length of boot password * n bytes - boot password * 2 bytes - length of encryption algorithm * n bytes - encryption algorithm * 2 bytes - length of encryption provider * n bytes - encryption provider * 2 bytes - length of user name * n bytes - user name * 2 bytes - length of password * n bytes - password * * Command: dbshutdown * Protocol: * 2 bytes - length of database name * n bytes - database name * 2 bytes - length of user name * n bytes - user name * 2 bytes - length of password * n bytes - password * * Command: connpool * Protocol: * 2 bytes - length of database name, if 0, default for all databases * is set * n bytes - database name * 2 bytes - minimum number of connections, if 0, connection pool not used * if value is -1 use default * 2 bytes - maximum number of connections, if 0, connections are created * as needed, if value is -1 use default * * Command: maxthreads * Protocol: * 2 bytes - maximum number of threads * * Command: timeslice * Protocol: * 4 bytes - timeslice value * * Command: tracedirectory * Protocol: * 2 bytes - length of directory name * n bytes - directory name * * Command: test connection * Protocol: * 2 bytes - length of database name if 0, just the connection * to the network server is tested and user name and * password aren't sent * n bytes - database name * 2 bytes - length of user name (optional) * n bytes - user name * 2 bytes - length of password (optional) * n bytes - password * * The calling routine is synchronized so that multiple threads don't clobber each * other. This means that configuration commands will be serialized. * This shouldn't be a problem since they should be fairly rare. * * @param reader input reader for command * @param writer output writer for command * @param session session information * * @exception Throwable throws an exception if an error occurs */ protected synchronized void processCommands(DDMReader reader, DDMWriter writer, Session session) throws Throwable { try { String protocolStr = reader.readCmdString(4); String locale = DEFAULT_LOCALE; String codeset = null; // get the version int version = reader.readNetworkShort(); if (version <= 0 || version > PROTOCOL_VERSION) throw new Throwable(langUtil.getTextMessage("DRDA_UnknownProtocol.S", new Integer(version).toString())); int localeLen = reader.readByte(); if (localeLen > 0) { currentSession = session; locale = reader.readCmdString(localeLen); session.langUtil = new LocalizedResource(codeset,locale,DRDA_PROP_MESSAGES); } String notLocalMessage = null; // for now codesetLen is always 0 int codesetLen = reader.readByte(); int command = reader.readByte(); if (command != COMMAND_TESTCONNECTION) { try { checkAddressIsLocal(session.clientSocket.getInetAddress()); }catch (Exception e) { notLocalMessage = e.getMessage(); } } if (notLocalMessage != null) { sendMessage(writer, ERROR,notLocalMessage); session.langUtil = null; currentSession = null; return; } switch(command) { case COMMAND_SHUTDOWN: // DERBY-2109: receive user credentials for shutdown // System Privileges check userArg = reader.readCmdString(); passwordArg = reader.readCmdString(); try { checkShutdownPrivileges(); sendOK(writer); directShutdownInternal(); } catch (SQLException sqle) { sendSQLMessage(writer, sqle, SQLERROR); // also print a message to the console consolePropertyMessage("DRDA_ShutdownWarning.I", sqle.getMessage()); } break; case COMMAND_TRACE: sessionArg = reader.readNetworkInt(); boolean on = (reader.readByte() == 1); if (setTrace(on)) { sendOK(writer); } else { if (sessionArg != 0) sendMessage(writer, ERROR, localizeMessage("DRDA_SessionNotFound.U", (session.langUtil == null) ? langUtil : session.langUtil, new String [] {new Integer(sessionArg).toString()})); else sendMessage(writer, ERROR, localizeMessage("DRDA_ErrorStartingTracing.S",null)); } break; case COMMAND_TRACEDIRECTORY: setTraceDirectory(reader.readCmdString()); sendOK(writer); consolePropertyMessage("DRDA_TraceDirectoryChange.I", traceDirectory); break; case COMMAND_TESTCONNECTION: databaseArg = reader.readCmdString(); userArg = reader.readCmdString(); passwordArg = reader.readCmdString(); if (databaseArg != null) connectToDatabase(writer, databaseArg, userArg, passwordArg); else sendOK(writer); break; case COMMAND_LOGCONNECTIONS: boolean log = (reader.readByte() == 1); setLogConnections(log); sendOK(writer); consolePropertyMessage("DRDA_LogConnectionsChange.I", (log ? "DRDA_ON.I" : "DRDA_OFF.I")); break; case COMMAND_SYSINFO: sendSysInfo(writer); break; case COMMAND_PROPERTIES: sendPropInfo(writer); break; case COMMAND_RUNTIME_INFO: sendRuntimeInfo(writer); break; case COMMAND_MAXTHREADS: int max = reader.readNetworkInt(); try { setMaxThreads(max); }catch (Exception e) { sendMessage(writer, ERROR, e.getMessage()); return; } int newval = getMaxThreads(); sendOKInt(writer, newval); consolePropertyMessage("DRDA_MaxThreadsChange.I", new Integer(newval).toString()); break; case COMMAND_TIMESLICE: int timeslice = reader.readNetworkInt(); try { setTimeSlice(timeslice); }catch (Exception e) { sendMessage(writer, ERROR, e.getMessage()); return; } newval = getTimeSlice(); sendOKInt(writer, newval); consolePropertyMessage("DRDA_TimeSliceChange.I", new Integer(newval).toString()); break; } } catch (DRDAProtocolException e) { //we need to handle this since we aren't in DRDA land here consoleExceptionPrintTrace(e); } catch (Exception e) { consoleExceptionPrintTrace(e); } finally { session.langUtil = null; currentSession = null; } } /** * Get the next session for the thread to work on * Called from DRDAConnThread after session completes or timeslice * exceeded. * * If there is a waiting session, pick it up and put currentSession * at the back of the queue if there is one. * @param currentSession session thread is currently working on * * @return next session to work on, could be same as current session */ protected Session getNextSession(Session currentSession) { Session retval = null; if (shutdown == true) return retval; synchronized (runQueue) { try { // nobody waiting - go on with current session if (runQueue.size() == 0) { // no current session - wait for some work if (currentSession == null) { while (runQueue.size() == 0) { // This thread has nothing to do now so // we will add it to freeThreads freeThreads++; runQueue.wait(); if (shutdown == true) return null; freeThreads--; } } else return currentSession; } retval = (Session) runQueue.elementAt(0); runQueue.removeElementAt(0); if (currentSession != null) runQueueAdd(currentSession); } catch (InterruptedException e) { // If for whatever reason (ex. database shutdown) a waiting thread is // interrupted while in this method, that thread is going to be // closed down, so we need to decrement the number of threads // that will be available for use. freeThreads--; } } return retval; } /** * Get the stored application requester or store if we haven't seen it yet * * @param appRequester Application Requester to look for * * @return stored application requester */ protected AppRequester getAppRequester(AppRequester appRequester) { AppRequester s = null; if (SanityManager.DEBUG) { if (appRequester == null) SanityManager.THROWASSERT("null appRequester in getAppRequester"); } if (!appRequesterTable.isEmpty()) s = (AppRequester)appRequesterTable.get(appRequester.prdid); if (s == null) { appRequesterTable.put(appRequester.prdid, appRequester); return appRequester; } else { //compare just in case there are some differences //if they are different use the one we just read in if (s.equals(appRequester)) return s; else return appRequester; } } /** * Get the server manager level for a given manager * * @param manager codepoint for manager * @return manager level */ protected int getManagerLevel(int manager) { int mindex = CodePoint.getManagerIndex(manager); if (SanityManager.DEBUG) { if (mindex == CodePoint.UNKNOWN_MANAGER) SanityManager.THROWASSERT("manager out of bounds"); } return MGR_LEVELS[mindex]; } /** * Check whether a CCSID code page is supported * * @param ccsid CCSID to check * @return true if supported; false otherwise */ protected boolean supportsCCSID(int ccsid) { try { CharacterEncodings.getJavaEncoding(ccsid); } catch (Exception e) { return false; } return true; } /** * Put property message on console * * @param msgProp message property key * @param printTimeStamp whether to prepend a timestamp to the message * * @throws Exception if an error occurs */ protected void consolePropertyMessage(String msgProp, boolean printTimeStamp) throws Exception { consolePropertyMessageWork(msgProp, null, printTimeStamp); } /** * Put property message on console * * @param msgProp message property key * @param arg argument for message * * @throws Exception if an error occurs */ protected void consolePropertyMessage(String msgProp, String arg) throws Exception { consolePropertyMessageWork(msgProp, new String [] {arg}, true); } /** * Put property message on console * * @param msgProp message property key * @param args argument array for message * * @throws Exception if an error occurs */ protected void consolePropertyMessage(String msgProp, String [] args) throws Exception { consolePropertyMessageWork(msgProp, args, true); } /** * Is this the command protocol * * @param val */ protected static boolean isCmd(String val) { if (val.equals(COMMAND_HEADER)) return true; else return false; } /*******************************************************************************/ /* Private methods */ /*******************************************************************************/ /** * Write Command reply * * @param writer writer to use * * @throws Exception if a problem occurs sending OK */ private void writeCommandReplyHeader(DDMWriter writer) throws Exception { writer.setCMDProtocol(); writer.writeString(REPLY_HEADER); } /** * Send OK from server to client after processing a command * * @param writer writer to use for sending OK * * @throws Exception if a problem occurs sending OK */ private void sendOK(DDMWriter writer) throws Exception { writeCommandReplyHeader(writer); writer.writeByte(OK); writer.flush(); } /** * Send OK and int value * * @param writer writer to use for sending * @param val int val to send * * @throws Exception if a problem occurs */ private void sendOKInt(DDMWriter writer, int val) throws Exception { writeCommandReplyHeader(writer); writer.writeByte(OK); writer.writeNetworkInt(val); writer.flush(); } /** * Send Error or Warning from server to client after processing a command * * @param writer writer to use for sending message * @param messageType 1 for Warning, 2 for Error 3 for SQLError * @param message message * * @throws Exception if a problem occurs sending message */ private void sendMessage(DDMWriter writer, int messageType, String message) throws Exception { writeCommandReplyHeader(writer); writer.writeByte(messageType); writer.writeLDString(message); writer.flush(); } /** * Send SQL Exception from server to client after processing a command * * @param writer writer to use for sending message * @param se Derby exception * @param type type of exception, SQLERROR or SQLWARNING * * @throws Exception if a problem occurs sending message */ private void sendSQLMessage(DDMWriter writer, SQLException se, int type) throws Exception { StringBuffer locMsg = new StringBuffer(); //localize message if necessary while (se != null) { if (currentSession != null && currentSession.langUtil != null && se instanceof EmbedSQLException) { locMsg.append(se.getSQLState()+":"+ MessageService.getLocalizedMessage( currentSession.langUtil.getLocale(), ((EmbedSQLException)se).getMessageId(), ((EmbedSQLException)se).getArguments())); } else locMsg.append(se.getSQLState()+":"+se.getMessage()); se = se.getNextException(); if (se != null) locMsg.append("\n"); } sendMessage(writer, type, locMsg.toString()); } /** * Send SysInfo information from server to client * * @param writer writer to use for sending sysinfo * * @throws Exception if a problem occurs sending value */ private void sendSysInfo(DDMWriter writer) throws Exception { StringBuffer sysinfo = new StringBuffer(); sysinfo.append(getNetSysInfo()); sysinfo.append(getCLSSysInfo()); try { writeCommandReplyHeader(writer); writer.writeByte(0); //O.K. writer.writeLDString(sysinfo.toString()); } catch (DRDAProtocolException e) { consolePropertyMessage("DRDA_SysInfoWriteError.S", e.getMessage()); } writer.flush(); } /** * Send RuntimeInfo information from server to client * * @param writer writer to use for sending sysinfo * * @throws Exception if a problem occurs sending value */ private void sendRuntimeInfo(DDMWriter writer) throws Exception { try { writeCommandReplyHeader(writer); writer.writeByte(0); //O.K. writer.writeLDString(getRuntimeInfo()); } catch (DRDAProtocolException e) { consolePropertyMessage("DRDA_SysInfoWriteError.S", e.getMessage()); } writer.flush(); } /** * Send property information from server to client * * @param writer writer to use for sending sysinfo * * @throws Exception if a problem occurs sending value */ private void sendPropInfo(DDMWriter writer) throws Exception { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Properties p = getPropertyValues(); p.store(out, "NetworkServerControl properties"); try { writeCommandReplyHeader(writer); writer.writeByte(0); //O.K. writer.writeLDBytes(out.toByteArray()); } catch (DRDAProtocolException e) { consolePropertyMessage("DRDA_PropInfoWriteError.S", e.getMessage()); } writer.flush(); } catch (Exception e) { consoleExceptionPrintTrace(e); } } /** * Get Net Server information * * @return system information for the Network Server */ private String getNetSysInfo() { StringBuffer sysinfo = new StringBuffer(); LocalizedResource localLangUtil = langUtil; if (currentSession != null && currentSession.langUtil != null) localLangUtil = currentSession.langUtil; sysinfo.append(localLangUtil.getTextMessage("DRDA_SysInfoBanner.I")+ "\n"); sysinfo.append(localLangUtil.getTextMessage("DRDA_SysInfoVersion.I")+ " " + att_srvrlslv); sysinfo.append(" "); sysinfo.append(localLangUtil.getTextMessage("DRDA_SysInfoBuild.I")+ " " + buildNumber); sysinfo.append(" "); sysinfo.append(localLangUtil.getTextMessage("DRDA_SysInfoDrdaPRDID.I")+ " " + prdId); if (SanityManager.DEBUG) { sysinfo.append(" ** SANE BUILD **"); } sysinfo.append("\n"); // add property information Properties p = getPropertyValues(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bos); p.list(ps); sysinfo.append(bos.toString()); return sysinfo.toString(); } /** * @see NetworkServerControl#getRuntimeInfo */ private String getRuntimeInfo() { return buildRuntimeInfo(langUtil); } /** * Get Derby information * * @return system information for Derby * * @throws IOException if a problem occurs encoding string */ private String getCLSSysInfo() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); LocalizedResource localLangUtil = langUtil; if (currentSession != null && currentSession.langUtil != null) localLangUtil = currentSession.langUtil; LocalizedOutput aw = localLangUtil.getNewOutput(bos); org.apache.derby.impl.tools.sysinfo.Main.getMainInfo(aw, false); return bos.toString(); } /** * Parse the command-line arguments. As a side-effect, fills in various instance * fields. This method was carved out of executeWork() so that * NetworkServerControl can figure out whether to install a security manager * before the server actually comes up. This is part of the work for DERBY-2196. * * @param args array of arguments indicating command to be executed * * @return the command to be executed */ public int parseArgs(String args[]) throws Exception { // For convenience just use NetworkServerControlImpls log writer for user messages logWriter = makePrintWriter(System.out); int command = findCommand(args); if (command == COMMAND_UNKNOWN) { consolePropertyMessage("DRDA_NoCommand.U", true); } return command; } /** * Execute the command given on the command line * * @param command The command to execute. The command itself was determined by an earlier call to parseArgs(). * * @exception Exception throws an exception if an error occurs * see class comments for more information */ public void executeWork(int command) throws Exception { // if we didn't have a valid command just return - error already generated if (command == COMMAND_UNKNOWN) return; // check that we have the right number of required arguments if (commandArgs.size() != COMMAND_ARGS[command]) consolePropertyMessage("DRDA_InvalidNoArgs.U", COMMANDS[command]); int min; int max; switch (command) { case COMMAND_START: // the server was started from the command line, shutdown the // databases when the server is shutdown shutdownDatabasesOnShutdown = true; blockingStart(makePrintWriter(System.out)); break; case COMMAND_SHUTDOWN: shutdown(); consolePropertyMessage("DRDA_ShutdownSuccess.I", new String [] {att_srvclsnm, versionString}); break; case COMMAND_TRACE: { boolean on = isOn((String)commandArgs.elementAt(0)); trace(sessionArg, on); consoleTraceMessage(sessionArg, on); break; } case COMMAND_TRACEDIRECTORY: String directory = (String) commandArgs.elementAt(0); sendSetTraceDirectory(directory); consolePropertyMessage("DRDA_TraceDirectoryChange.I", directory); break; case COMMAND_TESTCONNECTION: ping(); consolePropertyMessage("DRDA_ConnectionTested.I", new String [] {hostArg, (new Integer(portNumber)).toString()}); break; case COMMAND_LOGCONNECTIONS: { boolean on = isOn((String)commandArgs.elementAt(0)); logConnections(on); consolePropertyMessage("DRDA_LogConnectionsChange.I", on ? "DRDA_ON.I" : "DRDA_OFF.I"); break; } case COMMAND_SYSINFO: { String info = sysinfo(); consoleMessage(info, false); break; } case COMMAND_MAXTHREADS: max = 0; try{ max = Integer.parseInt((String)commandArgs.elementAt(0)); }catch(NumberFormatException e){ consolePropertyMessage("DRDA_InvalidValue.U", new String [] {(String)commandArgs.elementAt(0), "maxthreads"}); } if (max < MIN_MAXTHREADS) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {new Integer(max).toString(), "maxthreads"}); netSetMaxThreads(max); break; case COMMAND_RUNTIME_INFO: String reply = runtimeInfo(); consoleMessage(reply, false); break; case COMMAND_TIMESLICE: int timeslice = 0; String timeSliceArg = (String)commandArgs.elementAt(0); try{ timeslice = Integer.parseInt(timeSliceArg); }catch(NumberFormatException e){ consolePropertyMessage("DRDA_InvalidValue.U", new String [] {(String)commandArgs.elementAt(0), "timeslice"}); } if (timeslice < MIN_TIMESLICE) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {new Integer(timeslice).toString(), "timeslice"}); netSetTimeSlice(timeslice); break; default: //shouldn't get here if (SanityManager.DEBUG) SanityManager.THROWASSERT("Invalid command in switch:"+ command); } } /** * Add session to the run queue * * @param clientSession session needing work */ private void runQueueAdd(Session clientSession) { synchronized(runQueue) { runQueue.addElement(clientSession); runQueue.notify(); } } /** * Go through the arguments and find the command and save the dash arguments * and arguments to the command. Only one command is allowed in the argument * list. * * @param args arguments to search * * @return command */ private int findCommand(String [] args) throws Exception { try { // process the dashArgs and pull out the command args int i = 0; int newpos = 0; while (i < args.length) { if (args[i].startsWith("-")) { newpos = processDashArg(i, args); if (newpos == i) commandArgs.addElement(args[i++]); else i = newpos; } else commandArgs.addElement(args[i++]); } // look up command if (commandArgs.size() > 0) { for (i = 0; i < COMMANDS.length; i++) { if (StringUtil.SQLEqualsIgnoreCase(COMMANDS[i], (String)commandArgs.firstElement())) { commandArgs.removeElementAt(0); return i; } } // didn't find command consolePropertyMessage("DRDA_UnknownCommand.U", (String) commandArgs.firstElement()); } } catch (Exception e) { if (e.getMessage().equals(NetworkServerControlImpl.UNEXPECTED_ERR)) throw e; //Ignore expected exceptions, they will have been //handled by the consolePropertyMessage routine } return COMMAND_UNKNOWN; } /** * Get the dash argument. Optional arguments are formated as -x value. * * @param pos starting point * @param args arguments to search * * @return command * * @exception Exception thrown if an error occurs */ private int processDashArg(int pos, String[] args) throws Exception { //check for a negative number char c = args[pos].charAt(1); if (c >= '0' && c <= '9') return pos; int dashArg = -1; for (int i = 0; i < DASHARGS.length; i++) { if (DASHARGS[i].equals(args[pos].substring(1))) { dashArg = i; if ( dashArg != DASHARG_UNSECURE ) { pos++ ; } break; } } if (dashArg == -1) consolePropertyMessage("DRDA_UnknownArgument.U", args[pos]); switch (dashArg) { case DASHARG_PORT: if (pos < args.length) { try{ portNumber = Integer.parseInt(args[pos]); }catch(NumberFormatException e){ consolePropertyMessage("DRDA_InvalidValue.U", new String [] {args[pos], "DRDA_PortNumber.I"}); } } else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_PortNumber.I"); break; case DASHARG_HOST: if (pos < args.length) { hostArg = args[pos]; } else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_Host.I"); break; case DASHARG_DATABASE: if (pos < args.length) databaseArg = args[pos]; else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_DatabaseDirectory.I"); break; case DASHARG_USER: if (pos < args.length) userArg = args[pos]; else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_User.I"); break; case DASHARG_PASSWORD: if (pos < args.length) passwordArg = args[pos]; else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_Password.I"); break; case DASHARG_ENCALG: if (pos < args.length) encAlgArg = args[pos]; else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_EncryptionAlgorithm.I"); break; case DASHARG_ENCPRV: if (pos < args.length) encPrvArg = args[pos]; else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_EncryptionProvider.I"); break; case DASHARG_LOADSYSIBM: break; case DASHARG_SESSION: if (pos < args.length) try{ sessionArg = Integer.parseInt(args[pos]); }catch(NumberFormatException e){ consolePropertyMessage("DRDA_InvalidValue.U", new String [] {args[pos], "DRDA_Session.I"}); } else consolePropertyMessage("DRDA_MissingValue.U", "DRDA_Session.I"); break; case DASHARG_UNSECURE: unsecureArg = true; break; case DASHARG_SSL: if (pos < args.length) { setSSLMode(getSSLModeValue(args[pos])); } else { setSSLMode(SSL_OFF); } break; default: //shouldn't get here } return pos+1; } /** * Is string "on" or "off" * * @param arg string to check * * @return true if string is "on", false if string is "off" * * @exception Exception thrown if string is not one of "on" or "off" */ private boolean isOn(String arg) throws Exception { if (StringUtil.SQLEqualsIgnoreCase(arg, "on")) return true; else if (!StringUtil.SQLEqualsIgnoreCase(arg, "off")) consolePropertyMessage("DRDA_OnOffValue.U", arg); return false; } /** * Close the resources associated with the opened socket. * @throws IOException */ private void closeSocket() throws IOException { try { if (clientIs != null) clientIs.close(); if (clientOs != null) clientOs.close(); if (clientSocket != null) clientSocket.close(); } finally { clientIs = null; clientOs = null; clientSocket = null; } } /** * Set up client socket to send a command to the network server * * @exception Exception thrown if exception encountered */ private void setUpSocket() throws Exception { try { clientSocket = (Socket) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws UnknownHostException, IOException, java.security.NoSuchAlgorithmException, java.security.KeyManagementException, java.security.NoSuchProviderException, java.security.KeyStoreException, java.security.UnrecoverableKeyException, java.security.cert.CertificateException { if (hostAddress == null) hostAddress = InetAddress.getByName(hostArg); switch(getSSLMode()) { case SSL_BASIC: SSLSocket s1 = (SSLSocket)NaiveTrustManager.getSocketFactory(). createSocket(hostAddress, portNumber); // Need to handshake now to get proper error reporting. s1.startHandshake(); return s1; case SSL_PEER_AUTHENTICATION: SSLSocket s2 = (SSLSocket)SSLSocketFactory.getDefault(). createSocket(hostAddress, portNumber); // Need to handshake now to get proper error reporting. s2.startHandshake(); return s2; case SSL_OFF: default: return SocketFactory.getDefault(). createSocket(hostAddress, portNumber); } } } ); } catch (PrivilegedActionException pae) { Exception e1 = pae.getException(); if (e1 instanceof UnknownHostException) { consolePropertyMessage("DRDA_UnknownHost.S", hostArg); } else if (e1 instanceof IOException) { consolePropertyMessage("DRDA_NoIO.S", new String [] {hostArg, (new Integer(portNumber)).toString(), e1.getMessage()}); } } catch (Exception e) { // If we find other (unexpected) errors, we ultimately exit--so make // sure we print the error message before doing so (Beetle 5033). throwUnexpectedException(e); } try { clientIs = clientSocket.getInputStream(); clientOs = clientSocket.getOutputStream(); } catch (IOException e) { consolePropertyMessage("DRDA_NoInputStream.I", true); throw e; } } private void checkAddressIsLocal(InetAddress inetAddr) throws UnknownHostException,Exception { for(int i = 0; i < localAddresses.size(); i++) { if (inetAddr.equals((InetAddress)localAddresses.get(i))) { return; } } consolePropertyMessage("DRDA_NeedLocalHost.S", new String[] {inetAddr.getHostName(),serverSocket.getInetAddress().getHostName()}); } /** * Build local address list to allow admin commands. * * @param bindAddr Address on which server was started * * Note: Some systems may not support localhost. * In that case a console message will print for the localhost entries, * but the server will continue to start. **/ private void buildLocalAddressList(InetAddress bindAddr) { localAddresses = new ArrayList(3); localAddresses.add(bindAddr); try { localAddresses.add(InetAddress.getLocalHost()); localAddresses.add(InetAddress.getByName("localhost")); }catch(UnknownHostException uhe) { try { consolePropertyMessage("DRDA_UnknownHostWarning.I",uhe.getMessage()); } catch (Exception e) { // just a warning shouldn't actually throw an exception } } } /** * Routines for writing commands for NetworkServerControlImpl being used as a client * to a server */ /** * Write command header consisting of command header string and protocol * version and command * * @param command command to be written * * @exception Exception throws an exception if an error occurs */ private void writeCommandHeader(int command) throws Exception { try { writeString(COMMAND_HEADER); commandOs.writeByte((byte)((PROTOCOL_VERSION & 0xf0) >> 8 )); commandOs.writeByte((byte)(PROTOCOL_VERSION & 0x0f)); if (clientLocale != null && clientLocale != DEFAULT_LOCALE) { commandOs.writeByte(clientLocale.length()); commandOs.writeBytes(clientLocale); } else commandOs.writeByte((byte) 0); commandOs.writeByte((byte) 0); commandOs.writeByte((byte) command); } catch (IOException e) { clientSocketError(e); } } /** * Write length delimited string string * * @param msg string to be written * * @exception Exception throws an exception if an error occurs */ private void writeLDString(String msg) throws Exception { try { if (msg == null) { commandOs.writeShort(0); } else { commandOs.writeShort(msg.length()); writeString(msg); } } catch (IOException e) { clientSocketError(e); } } /** Write string * * @param msg String to write */ protected void writeString(String msg) throws Exception { byte[] msgBytes = msg.getBytes(DEFAULT_ENCODING); commandOs.write(msgBytes,0,msgBytes.length); } /** * Write short * * @param value value to be written * * @exception Exception throws an exception if an error occurs */ private void writeShort(int value) throws Exception { try { commandOs.writeByte((byte)((value & 0xf0) >> 8 )); commandOs.writeByte((byte)(value & 0x0f)); } catch (IOException e) { clientSocketError(e); } } /** * Write byte * * @param value value to be written * * @exception Exception throws an exception if an error occurs */ private void writeByte(int value) throws Exception { try { commandOs.writeByte((byte)(value & 0x0f)); } catch (IOException e) { clientSocketError(e); } } /** * Send client message to server * * * @exception Exception throws an exception if an error occurs */ private void send() throws Exception { try { byteArrayOs.writeTo(clientOs); commandOs.flush(); byteArrayOs.reset(); //discard anything currently in the byte array } catch (IOException e) { clientSocketError(e); } } /** * Stream error writing to client socket */ private void clientSocketError(IOException e) throws IOException { try { consolePropertyMessage("DRDA_ClientSocketError.S", e.getMessage()); } catch (Exception ce) {} // catch the exception consolePropertyMessage will // throw since we also want to print a stack trace consoleExceptionPrintTrace(e); throw e; } /** * Read result from sending client message to server * * @exception Exception throws an exception if an error occurs */ private void readResult() throws Exception { fillReplyBuffer(); readCommandReplyHeader(); if (replyBufferPos >= replyBufferCount) consolePropertyMessage("DRDA_InvalidReplyTooShort.S", true); int messageType = replyBuffer[replyBufferPos++] & 0xFF; if (messageType == OK) // O.K. return; // get error and display and throw exception String message = readLDString(); if (messageType == SQLERROR) wrapSQLError(message); else if (messageType == SQLWARNING) wrapSQLWarning(message); else consolePropertyMessage(message, true); } /** * Ensure the reply buffer is at large enought to hold all the data; * don't just rely on OS level defaults * * * @param minimumBytesNeeded size of buffer required * @exception Exception throws an exception if a problem reading the reply */ private void ensureDataInBuffer(int minimumBytesNeeded) throws Exception { // make sure the buffer is large enough while ((replyBufferCount - replyBufferPos) < minimumBytesNeeded) { try { int bytesRead = clientIs.read(replyBuffer, replyBufferCount, replyBuffer.length - replyBufferCount); replyBufferCount += bytesRead; } catch (IOException e) { clientSocketError(e); } } } /** * Fill the reply buffer with the reply allocates a reply buffer if one doesn't * exist * * * @exception Exception throws an exception if a problem reading the reply */ private void fillReplyBuffer() throws Exception { if (replyBuffer == null) replyBuffer = new byte[MAXREPLY]; try { replyBufferCount = clientIs.read(replyBuffer); } catch (IOException e) { clientSocketError(e); } if (replyBufferCount == -1) consolePropertyMessage("DRDA_InvalidReplyTooShort.S", true); replyBufferPos = 0; } /** * Read the command reply header from the server * * @exception Exception throws an exception if an error occurs */ private void readCommandReplyHeader() throws Exception { ensureDataInBuffer(REPLY_HEADER_LENGTH); if (replyBufferCount < REPLY_HEADER_LENGTH) { consolePropertyMessage("DRDA_InvalidReplyHeader1.S", Integer.toString(replyBufferCount)); } String header = new String(replyBuffer, 0, REPLY_HEADER_LENGTH, DEFAULT_ENCODING); if (!header.equals(REPLY_HEADER)) { consolePropertyMessage("DRDA_InvalidReplyHeader2.S", header); } replyBufferPos += REPLY_HEADER_LENGTH; } /** * Read short from buffer * @exception Exception throws an exception if an error occurs */ private int readShort() throws Exception { ensureDataInBuffer(2); if (replyBufferPos + 2 > replyBufferCount) consolePropertyMessage("DRDA_InvalidReplyTooShort.S", true); return ((replyBuffer[replyBufferPos++] & 0xff) << 8) + (replyBuffer[replyBufferPos++] & 0xff); } /** * Read int from buffer * @exception Exception throws an exception if an error occurs */ private int readInt() throws Exception { ensureDataInBuffer(4); if (replyBufferPos + 4 > replyBufferCount) consolePropertyMessage("DRDA_InvalidReplyTooShort.S", true); return ((replyBuffer[replyBufferPos++] & 0xff) << 24) + ((replyBuffer[replyBufferPos++] & 0xff) << 16) + ((replyBuffer[replyBufferPos++] & 0xff) << 8) + (replyBuffer[replyBufferPos++] & 0xff); } /** * Read String reply * * @param msgKey error message key * @return string value or null * @exception Exception throws an error if problems reading reply */ private String readStringReply(String msgKey) throws Exception { fillReplyBuffer(); readCommandReplyHeader(); if (replyBuffer[replyBufferPos++] == 0) // O.K. return readLDString(); else consolePropertyMessage(msgKey, true); return null; } /** * Read length delimited string from a buffer * * @return string value from buffer * @exception Exception throws an error if problems reading reply */ private String readLDString() throws Exception { int strlen = readShort(); ensureDataInBuffer(strlen); if (replyBufferPos + strlen > replyBufferCount) consolePropertyMessage("DRDA_InvalidReplyTooShort.S", true); String retval= new String(replyBuffer, replyBufferPos, strlen, DEFAULT_ENCODING); replyBufferPos += strlen; return retval; } /** * Read Bytes reply * * @param msgKey error message key * @return string value or null * @exception Exception throws an error if problems reading reply */ private byte [] readBytesReply(String msgKey) throws Exception { fillReplyBuffer(); readCommandReplyHeader(); if (replyBuffer[replyBufferPos++] == 0) // O.K. return readLDBytes(); else consolePropertyMessage(msgKey, true); return null; } /** * Read length delimited bytes from a buffer * * @return byte array from buffer * @exception Exception throws an error if problems reading reply */ private byte[] readLDBytes() throws Exception { int len = readShort(); ensureDataInBuffer(len); if (replyBufferPos + len > replyBufferCount) consolePropertyMessage("DRDA_InvalidReplyTooShort.S", true); byte [] retval = new byte[len]; for (int i = 0; i < len; i++) retval[i] = replyBuffer[replyBufferPos++]; return retval; } /** * Initialize fields from system properties * */ private void getPropertyInfo() throws Exception { //set values according to properties String directory = PropertyUtil.getSystemProperty(Property.SYSTEM_HOME_PROPERTY); String propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_LOGCONNECTIONS); if (propval != null && StringUtil.SQLEqualsIgnoreCase(propval,"true")) setLogConnections(true); propval = PropertyUtil.getSystemProperty(Property.DRDA_PROP_TRACEALL); if (propval != null && StringUtil.SQLEqualsIgnoreCase(propval, "true")) setTraceAll(true); //If the derby.system.home property has been set, it is the default. //Otherwise, the default is the current directory. //If derby.system.home is not set, directory will be null and trace files will get //created in current directory. propval = PropertyUtil.getSystemProperty(Property.DRDA_PROP_TRACEDIRECTORY,directory); if(propval != null){ if(propval.equals("")) propval = directory; setTraceDirectory(propval); } //DERBY-375 If a system property is specified without any value, getProperty returns //an empty string. Use default values in such cases. propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_MINTHREADS); if (propval != null){ if(propval.equals("")) propval = "0"; setMinThreads(getIntPropVal(Property.DRDA_PROP_MINTHREADS, propval)); } propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_MAXTHREADS); if (propval != null){ if(propval.equals("")) propval = "0"; setMaxThreads(getIntPropVal(Property.DRDA_PROP_MAXTHREADS, propval)); } propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_TIMESLICE); if (propval != null){ if(propval.equals("")) propval = "0"; setTimeSlice(getIntPropVal(Property.DRDA_PROP_TIMESLICE, propval)); } propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_PORTNUMBER); if (propval != null){ if(propval.equals("")) propval = String.valueOf(NetworkServerControl.DEFAULT_PORTNUMBER); portNumber = getIntPropVal(Property.DRDA_PROP_PORTNUMBER, propval); } propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_SSL_MODE); setSSLMode(getSSLModeValue(propval)); propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_KEEPALIVE); if (propval != null && StringUtil.SQLEqualsIgnoreCase(propval,"false")) keepAlive = false; propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_HOSTNAME); if (propval != null){ if(propval.equals("")) hostArg = DEFAULT_HOST; else hostArg = propval; } propval = PropertyUtil.getSystemProperty( NetworkServerControlImpl.DRDA_PROP_DEBUG); if (propval != null && StringUtil.SQLEqualsIgnoreCase(propval, "true")) debugOutput = true; propval = PropertyUtil.getSystemProperty( Property.DRDA_PROP_SECURITYMECHANISM); if (propval != null){ setSecurityMechanism(propval); } } /** * Retrieve the SECMEC integer value from the * user friendly security mechanism name * @param s security mechanism name * @return integer value , return the SECMEC value for * the security mechanism as defined by DRDA spec * or INVALID_OR_NOTSET_SECURITYMECHANISM if 's' * passed is invalid or not supported security * mechanism */ private int getSecMecValue(String s) { int secmec = INVALID_OR_NOTSET_SECURITYMECHANISM; if( StringUtil.SQLEqualsIgnoreCase(s,"USER_ONLY_SECURITY")) secmec = CodePoint.SECMEC_USRIDONL; else if( StringUtil.SQLEqualsIgnoreCase(s,"CLEAR_TEXT_PASSWORD_SECURITY")) secmec = CodePoint.SECMEC_USRIDPWD; else if( StringUtil.SQLEqualsIgnoreCase(s,"ENCRYPTED_USER_AND_PASSWORD_SECURITY")) secmec = CodePoint.SECMEC_EUSRIDPWD; else if( StringUtil.SQLEqualsIgnoreCase(s,"STRONG_PASSWORD_SUBSTITUTE_SECURITY")) secmec = CodePoint.SECMEC_USRSSBPWD; return secmec; } /** * Retrieve the string name for the integer * secmec value * @param secmecVal secmec value * @return String - return the string name corresponding * to the secmec value if recognized else returns null */ private String getStringValueForSecMec(int secmecVal) { switch(secmecVal) { case CodePoint.SECMEC_USRIDONL: return "USER_ONLY_SECURITY"; case CodePoint.SECMEC_USRIDPWD: return "CLEAR_TEXT_PASSWORD_SECURITY"; case CodePoint.SECMEC_EUSRIDPWD: return "ENCRYPTED_USER_AND_PASSWORD_SECURITY"; case CodePoint.SECMEC_USRSSBPWD: return "STRONG_PASSWORD_SUBSTITUTE_SECURITY"; } return null; } /** * This method returns whether EUSRIDPWD security mechanism * is supported or not. See class static block for more * info. * @return true if EUSRIDPWD is supported, false otherwise */ boolean supportsEUSRIDPWD() { return SUPPORTS_EUSRIDPWD; } /** * Get the SSL-mode from a string. * @param s the SSL-mode string ("off"/"false", "on"/"true" or * "authenticate"/"auth" * @return SSL_OFF, SSL_BASIC or SSL_PEER_AUTHENTICATION. Will default to * SSL_OFF if the input does not match one of the four listed * above. **/ private int getSSLModeValue(String s) throws Exception { if (s != null){ if (StringUtil.SQLEqualsIgnoreCase(s,"off")) { return SSL_OFF; } else if (StringUtil.SQLEqualsIgnoreCase(s,"basic")) { return SSL_BASIC; } else if (StringUtil.SQLEqualsIgnoreCase(s,"peerAuthentication")) { return SSL_PEER_AUTHENTICATION; } else { // Unknown value consolePropertyMessage("DRDA_InvalidValue.U", new String [] {s, Property.DRDA_PROP_SSL_MODE}); return SSL_OFF; } } else { // Default return SSL_OFF; } } /** * Get the string value of the SSL-mode. This is the inverse of * getSSLModeValue. * @param i The SSL-mode value (SSL_OFF, SSL_BASIC or * SSL_PEER_AUTHENTICATION) * @return The string representation ("off","on" or * "autneticate"). Will default to SSL_OFF for other values than * those listed above. */ private String getSSLModeString(int i) { switch(i) { case SSL_OFF: return "off"; case SSL_BASIC: return "basic"; case SSL_PEER_AUTHENTICATION: return "peerAuthentication"; default: // Assumes no SSL encryption for faulty values Anyway, // this should not happen thince the input values are // strings... return "off"; } } /** * Get integer property values * * @param propName property name * @param propVal string property value * @return integer value * * @exception Exception if not a valid integer */ private int getIntPropVal(String propName, String propVal) throws Exception { int val = 0; try { val = (new Integer(propVal)).intValue(); } catch (Exception e) { consolePropertyMessage("DRDA_InvalidPropVal.S", new String [] {propName, propVal}); } return val; } /** * Handle console error message * - display on console and if it is a user error, display usage * - if user error or severe error, throw exception with message key and message * * @param messageKey message key * @param args arguments to message * @param printTimeStamp whether to prepend a timestamp to the message * * @throws Exception if an error occurs */ private void consolePropertyMessageWork(String messageKey, String [] args, boolean printTimeStamp) throws Exception { String locMsg = null; int type = getMessageType(messageKey); if (type == ERRTYPE_UNKNOWN) locMsg = messageKey; else locMsg = localizeMessage(messageKey, langUtil, args); //display on the console consoleMessage(locMsg, printTimeStamp); //if it is a user error display usage if (type == ERRTYPE_USER) usage(); //we may want to use a different locale for throwing the exception //since this can be sent to a browser with a different locale if (currentSession != null && currentSession.langUtil != null && type != ERRTYPE_UNKNOWN) locMsg = localizeMessage(messageKey, currentSession.langUtil, args); // throw an exception for severe and user errors if (type == ERRTYPE_SEVERE || type == ERRTYPE_USER) { if (messageKey.equals("DRDA_SQLException.S")) throwSQLException(args[0]); else if (messageKey.equals("DRDA_SQLWarning.I")) throwSQLWarning(args[0]); else throw new Exception(messageKey+":"+locMsg); } // throw an exception with just the message if the error type is // unknown if (type == ERRTYPE_UNKNOWN) throw new Exception(locMsg); return; } /** * Throw a SQL Exception which was sent over by a server * Format of the msg is SQLSTATE:localized message\nSQLSTATE:next localized message * * @param msg msg containing SQL Exception * * @throws SQLException */ private void throwSQLException(String msg) throws SQLException { SQLException se = null; SQLException ne; SQLException ce = null; StringBuffer strbuf = new StringBuffer(); StringTokenizer tokenizer = new StringTokenizer(msg, "\n"); String sqlstate = null; String str; while (tokenizer.hasMoreTokens()) { str = tokenizer.nextToken(); //start of the next message if (str.charAt(5) == ':') { if (strbuf.length() > 0) { if (se == null) { se = new SQLException(strbuf.toString(), sqlstate); ce = se; } else { ne = new SQLException(strbuf.toString(), sqlstate); ce.setNextException(ne); ce = ne; } strbuf = new StringBuffer(); } strbuf.append(str.substring(6)); sqlstate = str.substring(0,5); } else strbuf.append(str); } if (strbuf.length() > 0) { if (se == null) { se = new SQLException(strbuf.toString(), sqlstate); ce = se; } else { ne = new SQLException(strbuf.toString(), sqlstate); ce.setNextException(ne); ce = ne; } } throw se; } /** * Throw a SQL Warning which was sent over by a server * Format of the msg is SQLSTATE:localized message\nSQLSTATE:next localized message * * @param msg msg containing SQL Warning * * @throws SQLWarning */ private void throwSQLWarning(String msg) throws SQLWarning { SQLWarning se = null; SQLWarning ne; SQLWarning ce = null; StringBuffer strbuf = new StringBuffer(); StringTokenizer tokenizer = new StringTokenizer(msg, "\n"); String sqlstate = null; String str; while (tokenizer.hasMoreTokens()) { str = tokenizer.nextToken(); //start of the next message if (str.charAt(5) == ':') { if (strbuf.length() > 0) { if (se == null) { se = new SQLWarning(strbuf.toString(), sqlstate); ce = se; } else { ne = new SQLWarning(strbuf.toString(), sqlstate); ce.setNextException(ne); ce = ne; } strbuf = new StringBuffer(); } strbuf.append(str.substring(6)); sqlstate = str.substring(0,5); } else strbuf.append(str); } if (strbuf.length() > 0) { if (se == null) { se = new SQLWarning(strbuf.toString(), sqlstate); ce = se; } else { ne = new SQLWarning(strbuf.toString(), sqlstate); ce.setNextException(ne); ce = ne; } } throw se; } /** * Print a trace for the (unexpected) exception received, then * throw a generic exception indicating that 1) an unexpected * exception was thrown, and 2) we've already printed the trace * (so don't do it again). * * @param e An unexpected exception. * @throws Exception with message UNEXPECTED_ERR. */ private void throwUnexpectedException(Exception e) throws Exception { consoleExceptionPrintTrace(e); throw new Exception(UNEXPECTED_ERR); } /** * Convenience routine so that NetworkServerControl can localize messages. * * @param msgProp message key * @param args arguments to message * */ public String localizeMessage( String msgProp, String[] args ) { return localizeMessage( msgProp, langUtil, args ); } /** * Localize a message given a particular AppUI * * @param msgProp message key * @param localLangUtil LocalizedResource to use to localize message * @param args arguments to message * */ private String localizeMessage(String msgProp, LocalizedResource localLangUtil, String [] args) { String locMsg = null; //check if the argument is a property if (args != null) { String [] argMsg = new String[args.length]; for (int i = 0; i < args.length; i++) { if (isMsgProperty(args[i])) argMsg[i] = localLangUtil.getTextMessage(args[i]); else argMsg[i] = args[i]; } switch (args.length) { case 1: locMsg = localLangUtil.getTextMessage(msgProp, argMsg[0]); break; case 2: locMsg = localLangUtil.getTextMessage(msgProp, argMsg[0], argMsg[1]); break; case 3: locMsg = localLangUtil.getTextMessage(msgProp, argMsg[0], argMsg[1], argMsg[2]); break; case 4: locMsg = localLangUtil.getTextMessage(msgProp, argMsg[0], argMsg[1], argMsg[2], argMsg[3]); break; default: //shouldn't get here } } else locMsg = localLangUtil.getTextMessage(msgProp); return locMsg; } /** * Determine type of message * * @param msg message * * @return message type */ private int getMessageType(String msg) { //all property messages should start with DRDA_ if (!msg.startsWith(DRDA_MSG_PREFIX)) return ERRTYPE_UNKNOWN; int startpos = msg.indexOf('.')+1; if (startpos >= msg.length()) return ERRTYPE_UNKNOWN; if (msg.length() > (startpos + 1)) return ERRTYPE_UNKNOWN; char type = msg.charAt(startpos); if (type == 'S') return ERRTYPE_SEVERE; if (type == 'U') return ERRTYPE_USER; if (type == 'I') return ERRTYPE_INFO; return ERRTYPE_UNKNOWN; } /** * Determine whether string is a property key or not * property keys start with DRDA_MSG_PREFIX * * @param msg message * * @return true if it is a property key; false otherwise */ private boolean isMsgProperty(String msg) { if (msg.startsWith(DRDA_MSG_PREFIX)) return true; else return false; } /** * Get the current value of logging connections * * @return true if logging connections is on; false otherwise */ public boolean getLogConnections() { synchronized(logConnectionsSync) { return logConnections; } } /** * Set the current value of logging connections * * @param value true to turn logging connections on; false to turn it off */ private void setLogConnections(boolean value) { synchronized(logConnectionsSync) { logConnections = value; } // update the value in all the threads synchronized(threadList) { for (Enumeration e = threadList.elements(); e.hasMoreElements(); ) { DRDAConnThread thread = (DRDAConnThread)e.nextElement(); thread.setLogConnections(value); } } } /** * Set the security mechanism for derby.drda.securityMechanism * If this property is set, server will only allow connections * from client with this security mechanism. * This method will map the user friendly string representing * the security mechanism to the corresponding drda secmec value * @param s security mechanism string value * @throws Exception if value to set is invalid * @see Property#DRDA_PROP_SECURITYMECHANISM */ private void setSecurityMechanism(String s) throws Exception { allowOnlySecurityMechanism = getSecMecValue(s); // if server vm cannot support EUSRIDPWD, then do not allow // derby.drda.securityMechanism to be set to EUSRIDPWD security // mechanism if ((allowOnlySecurityMechanism == INVALID_OR_NOTSET_SECURITYMECHANISM) || (allowOnlySecurityMechanism == CodePoint.SECMEC_EUSRIDPWD && !SUPPORTS_EUSRIDPWD)) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {s, Property.DRDA_PROP_SECURITYMECHANISM}); } /** * get the security mechanism (secmec value) that the server * will accept connections from. * @return the securitymechanism value. It is value that * the derby.drda.securityMechanism was set to, if it is not set, then * it is equal to INVALID_OR_NOTSET_SECURITYMECHANISM * @see Property#DRDA_PROP_SECURITYMECHANISM */ protected int getSecurityMechanism() { return allowOnlySecurityMechanism; } /** * Set the trace on/off for all sessions, or one session, depending on * whether we got -s argument. * * @param on true to turn trace on; false to turn it off * @return true if set false if an error occurred */ private boolean setTrace(boolean on) { boolean setTraceSuccessful = true; if (sessionArg == 0) { synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); if (on) try { session.setTraceOn(traceDirectory,true); } catch (Exception te ) { consoleExceptionPrintTrace(te); setTraceSuccessful = false; session.setTraceOff(); } else session.setTraceOff(); } if (setTraceSuccessful) setTraceAll(on); } } else { Session session = (Session) sessionTable.get(new Integer(sessionArg)); if (session != null) { if (on) try { session.setTraceOn(traceDirectory,true); }catch (Exception te) { consoleExceptionPrintTrace(te); setTraceSuccessful = false; session.setTraceOff(); } else session.setTraceOff(); } else return false; } return setTraceSuccessful; } /** * Get the current value of the time slice * * @return time slice value */ protected int getTimeSlice() { return timeSlice; } /** * Set the current value of time slice * * @param value time slice value * @exception Exception if value is < 0 */ private void setTimeSlice(int value) throws Exception { if (value < MIN_TIMESLICE) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {new Integer(value).toString(), "timeslice"}); if (value == USE_DEFAULT) value = DEFAULT_TIMESLICE; synchronized(timeSliceSync) { timeSlice = value; } } /** * Get the current value of keepAlive to configure how long the server * should keep the socket alive for a disconnected client */ protected boolean getKeepAlive() { return keepAlive; } /** * Get the current value of minimum number of threads to create at start * * @return value of minimum number of threads */ private int getMinThreads() { synchronized(threadsSync) { return minThreads; } } /** * Set the current value of minimum number of threads to create at start * * @param value value of minimum number of threads */ private void setMinThreads(int value) { synchronized(threadsSync) { minThreads = value; } } /** * Get the current value of maximum number of threads to create * * @return value of maximum number of threads */ private int getMaxThreads() { synchronized(threadsSync) { return maxThreads; } } /** * Set the current value of maximum number of threads to create * * @param value value of maximum number of threads * @exception Exception if value is less than 0 */ private void setMaxThreads(int value) throws Exception { if (value < MIN_MAXTHREADS) consolePropertyMessage("DRDA_InvalidValue.U", new String [] {new Integer(value).toString(), "maxthreads"}); if (value == USE_DEFAULT) value = DEFAULT_MAXTHREADS; synchronized(threadsSync) { maxThreads = value; } } protected void setSSLMode(int mode) { sslMode = mode; } protected int getSSLMode() { return sslMode; } /** * Get the current value of whether to trace all the sessions * * @return true if tracing is on for all sessions; false otherwise */ protected boolean getTraceAll() { synchronized(traceAllSync) { return traceAll; } } /** * Set the current value of whether to trace all the sessions * * @param value true if tracing is on for all sessions; false otherwise */ private void setTraceAll(boolean value) { synchronized(traceAllSync) { traceAll = value; } } /** * Get the current value of trace directory * * @return trace directory */ protected String getTraceDirectory() { synchronized(traceDirectorySync) { return traceDirectory; } } /** * Set the current value of trace directory * * @param value trace directory */ private void setTraceDirectory(String value) { synchronized(traceDirectorySync) { traceDirectory = value; } } /** * Connect to a database to test whether a connection can be made * * @param writer connection to send message to * @param database database directory to connect to * @param user user to use * @param password password to use */ private void connectToDatabase(DDMWriter writer, String database, String user, String password) throws Exception { Properties p = new Properties(); if (user != null) p.put("user", user); if (password != null) p.put("password", password); try { Class.forName(CLOUDSCAPE_DRIVER); } catch (Exception e) { sendMessage(writer, ERROR, e.getMessage()); return; } try { //Note, we add database to the url so that we can allow additional //url attributes Connection conn = DriverManager.getConnection(Attribute.PROTOCOL+database, p); // send warnings SQLWarning warn = conn.getWarnings(); if (warn != null) sendSQLMessage(writer, warn, SQLWARNING); else sendOK(writer); conn.close(); return; } catch (SQLException se) { sendSQLMessage(writer, se, SQLERROR); } } /** * Wrap SQL Error - display to console and raise exception * * @param messageKey Derby SQL Exception message id * * @exception Exception raises exception for message */ private void wrapSQLError(String messageKey) throws Exception { consolePropertyMessage("DRDA_SQLException.S", messageKey); } /** * Wrap SQL Warning - display to console and raise exception * * @param messageKey Derby SQL Exception message id * * @exception Exception raises exception for message */ private void wrapSQLWarning(String messageKey) throws Exception { consolePropertyMessage("DRDA_SQLWarning.I", messageKey); } /** * <p> * Constructs an object containing network server related properties * and their values. Some properties are only included if set. Some * other properties are included with a default value if not set.</p> * <p> * This method is accessing the local JVM in which the network server * instance is actually running (i.e. no networking).</p> * <p> * This method is package private to allow access from relevant MBean * implementations in the same package.</p> * * @return a collection of network server properties and their current * values */ Properties getPropertyValues() { Properties retval = new Properties(); retval.put(Property.DRDA_PROP_PORTNUMBER, new Integer(portNumber).toString()); retval.put(Property.DRDA_PROP_HOSTNAME, hostArg); retval.put(Property.DRDA_PROP_KEEPALIVE, new Boolean(keepAlive).toString()); String tracedir = getTraceDirectory(); if (tracedir != null) retval.put(Property.DRDA_PROP_TRACEDIRECTORY, tracedir); retval.put(Property.DRDA_PROP_TRACEALL, new Boolean(getTraceAll()).toString()); retval.put(Property.DRDA_PROP_MINTHREADS, new Integer(getMinThreads()).toString()); retval.put(Property.DRDA_PROP_MAXTHREADS, new Integer(getMaxThreads()).toString()); retval.put(Property.DRDA_PROP_TIMESLICE, new Integer(getTimeSlice()).toString()); retval.put(Property.DRDA_PROP_TIMESLICE, new Integer(getTimeSlice()).toString()); retval.put(Property.DRDA_PROP_LOGCONNECTIONS, new Boolean(getLogConnections()).toString()); String startDRDA = PropertyUtil.getSystemProperty(Property.START_DRDA); //DERBY-375 If a system property is specified without any value, getProperty returns //an empty string. Use default values in such cases. if(startDRDA!=null && startDRDA.equals("")) startDRDA = "false"; retval.put(Property.START_DRDA, (startDRDA == null)? "false" : startDRDA); // DERBY-2108 SSL retval.put(Property.DRDA_PROP_SSL_MODE, getSSLModeString(getSSLMode())); // if Property.DRDA_PROP_SECURITYMECHANISM has been set on server // then put it in retval else the default behavior is as though // it is not set if ( getSecurityMechanism() != INVALID_OR_NOTSET_SECURITYMECHANISM ) retval.put( Property.DRDA_PROP_SECURITYMECHANISM, getStringValueForSecMec(getSecurityMechanism())); //get the trace value for each session if tracing for all is not set if (!getTraceAll()) { synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); if (session.isTraceOn()) retval.put(Property.DRDA_PROP_TRACE+"."+session.getConnNum(), "true"); } } } return retval; } /** * Add a session - for use by <code>ClientThread</code>. Put the session * into the session table and the run queue. Start a new * <code>DRDAConnThread</code> if there are more sessions waiting than * there are free threads, and the maximum number of threads is not * exceeded. * * <p><code>addSession()</code> should only be called from one thread at a * time. * * @param clientSocket the socket to read from and write to */ void addSession(Socket clientSocket) throws Exception { int connectionNumber = ++connNum; if (getLogConnections()) { consolePropertyMessage("DRDA_ConnNumber.I", Integer.toString(connectionNumber)); } // Note that we always re-fetch the tracing configuration because it // may have changed (there are administrative commands which allow // dynamic tracing reconfiguration). Session session = new Session(this,connectionNumber, clientSocket, getTraceDirectory(), getTraceAll()); sessionTable.put(new Integer(connectionNumber), session); // Check whether there are enough free threads to service all the // threads in the run queue in addition to the newly added session. boolean enoughThreads; synchronized (runQueue) { enoughThreads = (runQueue.size() < freeThreads); } // No need to hold the synchronization on runQueue any longer than // this. Since no other threads can make runQueue grow, and no other // threads will reduce the number of free threads without removing // sessions from runQueue, (runQueue.size() < freeThreads) cannot go // from true to false until addSession() returns. DRDAConnThread thread = null; // try to start a new thread if we don't have enough free threads if (!enoughThreads) { // Synchronize on threadsSync to ensure that the value of // maxThreads doesn't change until the new thread is added to // threadList. synchronized (threadsSync) { // only start a new thread if we have no maximum number of // threads or the maximum number of threads is not exceeded if ((maxThreads == 0) || (threadList.size() < maxThreads)) { thread = new DRDAConnThread(session, this, getTimeSlice(), getLogConnections()); threadList.add(thread); thread.start(); } } } // add the session to the run queue if we didn't start a new thread if (thread == null) { runQueueAdd(session); } } /** * Remove a thread from the thread list. Should be called when a * <code>DRDAConnThread</code> has been closed. * * @param thread the closed thread */ void removeThread(DRDAConnThread thread) { threadList.remove(thread); } protected Object getShutdownSync() { return shutdownSync; } protected boolean getShutdown() { return shutdown; } public String buildRuntimeInfo(LocalizedResource locallangUtil) { String s = locallangUtil.getTextMessage("DRDA_RuntimeInfoBanner.I")+ "\n"; int sessionCount = 0; s += locallangUtil.getTextMessage("DRDA_RuntimeInfoSessionBanner.I") + "\n"; for (int i = 0; i < threadList.size(); i++) { String sessionInfo = ((DRDAConnThread) threadList.get(i)).buildRuntimeInfo("",locallangUtil) ; if (!sessionInfo.equals("")) { sessionCount ++; s += sessionInfo + "\n"; } } int waitingSessions = 0; for (int i = 0; i < runQueue.size(); i++) { s += ((Session)runQueue.get(i)).buildRuntimeInfo("", locallangUtil); waitingSessions ++; } s+= "-------------------------------------------------------------\n"; s += locallangUtil.getTextMessage("DRDA_RuntimeInfoNumThreads.I") + threadList.size() + "\n"; s += locallangUtil.getTextMessage("DRDA_RuntimeInfoNumActiveSessions.I") + sessionCount +"\n"; s +=locallangUtil.getTextMessage("DRDA_RuntimeInfoNumWaitingSessions.I") + + waitingSessions + "\n\n"; Runtime rt = Runtime.getRuntime(); rt.gc(); long totalmem = rt.totalMemory(); long freemem = rt.freeMemory(); s += locallangUtil.getTextMessage("DRDA_RuntimeInfoTotalMemory.I") + + totalmem + "\t"; s += locallangUtil.getTextMessage("DRDA_RuntimeInfoFreeMemory.I") + + freemem + "\n\n"; return s; } long getBytesRead() { long count=0; for (int i = 0; i < threadList.size(); i++) { count += ((DRDAConnThread)threadList.get(i)).getBytesRead(); } return count; } long getBytesWritten() { long count=0; for (int i = 0; i < threadList.size(); i++) { count += ((DRDAConnThread)threadList.get(i)).getBytesWritten(); } return count; } int getActiveSessions() { int count=0; for (int i = 0; i < threadList.size(); i++) { if (((DRDAConnThread)threadList.get(i)).hasSession()) { count++; } } return count; } int getRunQueueSize() { return runQueue.size(); } int getThreadListSize() { return threadList.size(); } int getConnectionNumber() { return connNum; } protected void setClientLocale(String locale) { clientLocale = locale; } /** * Retrieve product version information * We need to make sure that this method gets the stream and passes it to * ProductVersionHolder, because it lives in the Network Server jar * and won't be readily available to ProductVersionHolder when running * under security manager. */ private ProductVersionHolder getNetProductVersionHolder() throws Exception { ProductVersionHolder myPVH= null; try { myPVH = (ProductVersionHolder) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws UnknownHostException,IOException { InputStream versionStream = getClass().getResourceAsStream(ProductGenusNames.NET_INFO); return ProductVersionHolder.getProductVersionHolderFromMyEnv(versionStream); } }); } catch(PrivilegedActionException e) { Exception e1 = e.getException(); consolePropertyMessage("DRDA_ProductVersionReadError.S", e1.getMessage()); } return myPVH; } /** * This method returns a timestamp to be used in the messages. * CheapDateFormatter class, which uses GMT, is used to format timestamps. * This is to keep the formatting consistent with Derby boot message since * network server messages and the boot message get written to derby.log. * * @return current timestamp formatted in GMT */ private String getFormattedTimestamp(){ long currentTime = System.currentTimeMillis(); return CheapDateFormatter.formatDate(currentTime); } }
false
true
public void blockingStart(PrintWriter consoleWriter) throws Exception { startNetworkServer(); setLogWriter(consoleWriter); cloudscapeLogWriter = Monitor.getStream().getPrintWriter(); if (SanityManager.DEBUG && debugOutput) { memCheck.showmem(); mc = new memCheck(200000); mc.start(); } // Open a server socket listener try{ serverSocket = (ServerSocket) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return createServerSocket(); } }); } catch (PrivilegedActionException e) { Exception e1 = e.getException(); // Test for UnknownHostException first since it's a // subbclass of IOException (and consolePropertyMessage // throws an exception when the severity is S (or U). if (e1 instanceof UnknownHostException) { consolePropertyMessage("DRDA_UnknownHost.S", hostArg); } else if (e1 instanceof IOException) { consolePropertyMessage("DRDA_ListenPort.S", new String [] { Integer.toString(portNumber), hostArg, // Since SocketException // is used for a phletora // of situations, we need // to communicate the // underlying exception // string to the user. e1.toString()}); } else { throw e1; } } catch (Exception e) { // If we find other (unexpected) errors, we ultimately exit--so make // sure we print the error message before doing so (Beetle 5033). throwUnexpectedException(e); } switch (getSSLMode()) { default: case SSL_OFF: consolePropertyMessage("DRDA_Ready.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; case SSL_BASIC: consolePropertyMessage("DRDA_SSLReady.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; case SSL_PEER_AUTHENTICATION: consolePropertyMessage("DRDA_SSLClientAuthReady.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; } // We accept clients on a separate thread so we don't run into a problem // blocking on the accept when trying to process a shutdown final ClientThread clientThread = (ClientThread) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return new ClientThread(thisControl, serverSocket); } } ); clientThread.start(); // Now that we are up and running, register any MBeans ManagementService mgmtService = ((ManagementService) Monitor.getSystemModule(Module.JMX)); final Object versionMBean = mgmtService.registerMBean( new Version( getNetProductVersionHolder(), SystemPermission.SERVER), VersionMBean.class, "type=Version,jar=derbynet.jar"); final Object networkServerMBean = mgmtService.registerMBean( new NetworkServerMBeanImpl(this), NetworkServerMBean.class, "type=NetworkServer"); // wait until we are told to shutdown or someone sends an InterruptedException synchronized(shutdownSync) { try { shutdownSync.wait(); } catch (InterruptedException e) { shutdown = true; } } try { AccessController.doPrivileged( new PrivilegedAction() { public Object run() { // Need to interrupt the memcheck thread if it is sleeping. if (mc != null) mc.interrupt(); //interrupt client thread clientThread.interrupt(); return null; } }); } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } // Close out the sessions synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); try { session.close(); } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } } } synchronized (threadList) { //interupt any connection threads still active for (int i = 0; i < threadList.size(); i++) { try { final DRDAConnThread threadi = (DRDAConnThread)threadList.get(i); threadi.close(); AccessController.doPrivileged( new PrivilegedAction() { public Object run() { threadi.interrupt(); return null; } }); } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } } threadList.clear(); } // close the listener socket try{ serverSocket.close(); }catch(IOException e){ consolePropertyMessage("DRDA_ListenerClose.S", true); } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } // Wake up those waiting on sessions, so // they can close down try{ synchronized (runQueue) { runQueue.notifyAll(); } } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } // And now unregister any MBeans. try { mgmtService.unregisterMBean(versionMBean); mgmtService.unregisterMBean(networkServerMBean); } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } if (shutdownDatabasesOnShutdown) { // Shutdown Derby try { // tell driver to shutdown the engine if (cloudscapeDriver != null) { // DERBY-2109: pass user credentials for driver shutdown final Properties p = new Properties(); if (userArg != null) { p.setProperty("user", userArg); } if (passwordArg != null) { p.setProperty("password", passwordArg); } cloudscapeDriver.connect("jdbc:derby:;shutdown=true", p); } } catch (SQLException sqle) { // If we can't shutdown Derby, perhaps, authentication has // failed or System Privileges weren't granted. We will just // print a message to the console and proceed. String expectedState = StandardException.getSQLStateFromIdentifier( SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN); if (!expectedState.equals(sqle.getSQLState())) { consolePropertyMessage("DRDA_ShutdownWarning.I", sqle.getMessage()); } } catch (Exception exception) { consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); consoleExceptionPrintTrace(exception); } } consolePropertyMessage("DRDA_ShutdownSuccess.I", new String [] {att_srvclsnm, versionString}); }
public void blockingStart(PrintWriter consoleWriter) throws Exception { startNetworkServer(); setLogWriter(consoleWriter); cloudscapeLogWriter = Monitor.getStream().getPrintWriter(); if (SanityManager.DEBUG && debugOutput) { memCheck.showmem(); mc = new memCheck(200000); mc.start(); } // Open a server socket listener try{ serverSocket = (ServerSocket) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return createServerSocket(); } }); } catch (PrivilegedActionException e) { Exception e1 = e.getException(); // Test for UnknownHostException first since it's a // subbclass of IOException (and consolePropertyMessage // throws an exception when the severity is S (or U). if (e1 instanceof UnknownHostException) { consolePropertyMessage("DRDA_UnknownHost.S", hostArg); } else if (e1 instanceof IOException) { consolePropertyMessage("DRDA_ListenPort.S", new String [] { Integer.toString(portNumber), hostArg, // Since SocketException // is used for a phletora // of situations, we need // to communicate the // underlying exception // string to the user. e1.toString()}); } else { throw e1; } } catch (Exception e) { // If we find other (unexpected) errors, we ultimately exit--so make // sure we print the error message before doing so (Beetle 5033). throwUnexpectedException(e); } switch (getSSLMode()) { default: case SSL_OFF: consolePropertyMessage("DRDA_Ready.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; case SSL_BASIC: consolePropertyMessage("DRDA_SSLReady.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; case SSL_PEER_AUTHENTICATION: consolePropertyMessage("DRDA_SSLClientAuthReady.I", new String [] {Integer.toString(portNumber), att_srvclsnm, versionString}); break; } // We accept clients on a separate thread so we don't run into a problem // blocking on the accept when trying to process a shutdown final ClientThread clientThread = (ClientThread) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return new ClientThread(thisControl, serverSocket); } } ); clientThread.start(); // Now that we are up and running, register any MBeans ManagementService mgmtService = ((ManagementService) Monitor.getSystemModule(Module.JMX)); final Object versionMBean = mgmtService.registerMBean( new Version( getNetProductVersionHolder(), SystemPermission.SERVER), VersionMBean.class, "type=Version,jar=derbynet.jar"); final Object networkServerMBean = mgmtService.registerMBean( new NetworkServerMBeanImpl(this), NetworkServerMBean.class, "type=NetworkServer"); // wait until we are told to shutdown or someone sends an InterruptedException synchronized(shutdownSync) { try { shutdownSync.wait(); } catch (InterruptedException e) { shutdown = true; } } try { AccessController.doPrivileged( new PrivilegedAction() { public Object run() { // Need to interrupt the memcheck thread if it is sleeping. if (mc != null) mc.interrupt(); //interrupt client thread clientThread.interrupt(); return null; } }); } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } // Close out the sessions synchronized(sessionTable) { for (Enumeration e = sessionTable.elements(); e.hasMoreElements(); ) { Session session = (Session) e.nextElement(); try { session.close(); } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } } } synchronized (threadList) { //interupt any connection threads still active for (int i = 0; i < threadList.size(); i++) { try { final DRDAConnThread threadi = (DRDAConnThread)threadList.get(i); threadi.close(); AccessController.doPrivileged( new PrivilegedAction() { public Object run() { threadi.interrupt(); return null; } }); } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } } threadList.clear(); } // close the listener socket try{ serverSocket.close(); }catch(IOException e){ consolePropertyMessage("DRDA_ListenerClose.S", true); } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } // Wake up those waiting on sessions, so // they can close down try{ synchronized (runQueue) { runQueue.notifyAll(); } } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } // And now unregister any MBeans. try { mgmtService.unregisterMBean(versionMBean); mgmtService.unregisterMBean(networkServerMBean); } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } if (shutdownDatabasesOnShutdown) { // Shutdown Derby try { // tell driver to shutdown the engine if (cloudscapeDriver != null) { // DERBY-2109: pass user credentials for driver shutdown final Properties p = new Properties(); if (userArg != null) { p.setProperty("user", userArg); } if (passwordArg != null) { p.setProperty("password", passwordArg); } cloudscapeDriver.connect("jdbc:derby:;shutdown=true", p); } } catch (SQLException sqle) { // If we can't shutdown Derby, perhaps, authentication has // failed or System Privileges weren't granted. We will just // print a message to the console and proceed. String expectedState = StandardException.getSQLStateFromIdentifier( SQLState.CLOUDSCAPE_SYSTEM_SHUTDOWN); if (!expectedState.equals(sqle.getSQLState())) { consolePropertyMessage("DRDA_ShutdownWarning.I", sqle.getMessage()); } } catch (Exception exception) { consoleExceptionPrintTrace(exception); consolePropertyMessage("DRDA_UnexpectedException.S", exception.getMessage()); } } consolePropertyMessage("DRDA_ShutdownSuccess.I", new String [] {att_srvclsnm, versionString}); }
diff --git a/src/main/java/com/eyeq/pivot4j/primefaces/ui/FilterHandler.java b/src/main/java/com/eyeq/pivot4j/primefaces/ui/FilterHandler.java index 496ddf6..7b64b33 100644 --- a/src/main/java/com/eyeq/pivot4j/primefaces/ui/FilterHandler.java +++ b/src/main/java/com/eyeq/pivot4j/primefaces/ui/FilterHandler.java @@ -1,578 +1,578 @@ package com.eyeq.pivot4j.primefaces.ui; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.el.ExpressionFactory; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.component.UIComponent; import javax.faces.component.UIParameter; import javax.faces.component.UIViewRoot; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.context.FacesContext; import org.olap4j.OlapException; import org.olap4j.metadata.Hierarchy; import org.olap4j.metadata.Level; import org.olap4j.metadata.Member; import org.olap4j.metadata.MetadataElement; import org.primefaces.component.commandbutton.CommandButton; import org.primefaces.component.commandlink.CommandLink; import org.primefaces.context.RequestContext; import org.primefaces.event.DragDropEvent; import org.primefaces.event.NodeSelectEvent; import org.primefaces.event.NodeUnselectEvent; import org.primefaces.model.DefaultTreeNode; import org.primefaces.model.TreeNode; import com.eyeq.pivot4j.ModelChangeEvent; import com.eyeq.pivot4j.ModelChangeListener; import com.eyeq.pivot4j.PivotModel; import com.eyeq.pivot4j.primefaces.ui.tree.HierarchyNode; import com.eyeq.pivot4j.primefaces.ui.tree.LevelNode; import com.eyeq.pivot4j.primefaces.ui.tree.MemberNode; import com.eyeq.pivot4j.primefaces.ui.tree.NodeFilter; import com.eyeq.pivot4j.transform.ChangeSlicer; import com.eyeq.pivot4j.util.MemberSelection; @ManagedBean(name = "filterHandler") @RequestScoped public class FilterHandler implements ModelChangeListener, NodeFilter { @ManagedProperty(value = "#{pivotStateManager.model}") private PivotModel model; @ManagedProperty(value = "#{navigatorHandler}") private NavigatorHandler navigator; private TreeNode filterNode; private TreeNode[] selection; private MemberSelection filterMembers; private UIComponent filterPanel; private CommandButton buttonApply; @PostConstruct protected void initialize() { if (model != null) { model.addModelChangeListener(this); } } @PreDestroy protected void destroy() { if (model != null) { model.removeModelChangeListener(this); } } /** * @return the model */ public PivotModel getModel() { return model; } /** * @param model * the model to set */ public void setModel(PivotModel model) { this.model = model; } /** * @return the navigator */ public NavigatorHandler getNavigator() { return navigator; } /** * @param navigator * the navigator to set */ public void setNavigator(NavigatorHandler navigator) { this.navigator = navigator; } protected MemberSelection getFilteredMembers() { if (filterMembers == null) { Hierarchy hierarchy = getHierarchy(); if (hierarchy != null) { ChangeSlicer transform = model.getTransform(ChangeSlicer.class); this.filterMembers = new MemberSelection( transform.getSlicer(hierarchy)); } } return filterMembers; } /** * @return the filterNode */ public TreeNode getFilterNode() { if (model != null && model.isInitialized()) { Hierarchy hierarchy = getHierarchy(); if (filterNode == null && hierarchy != null) { this.filterNode = new DefaultTreeNode(); List<Member> members; try { members = hierarchy.getRootMembers(); } catch (OlapException e) { throw new FacesException(e); } for (Member member : members) { MemberNode node = new MemberNode(member); node.setNodeFilter(this); node.setExpanded(true); node.setSelectable(true); node.setSelected(isSelected(member)); filterNode.getChildren().add(node); } } } else { this.filterNode = null; } return filterNode; } /** * @param filterNode * the filterNode to set */ public void setFilterNode(TreeNode filterNode) { this.filterNode = filterNode; } /** * @return the selection */ public TreeNode[] getSelection() { return selection; } /** * @param selection * the selection to set */ public void setSelection(TreeNode[] selection) { this.selection = selection; } /** * @return the filterPanel */ public UIComponent getFilterPanel() { return filterPanel; } /** * @param filterPanel * the filterPanel to set */ public void setFilterPanel(UIComponent filterPanel) { this.filterPanel = filterPanel; configureFilter(); } /** * @return the filteredHierarchy */ protected String getHierarchyName() { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot view = context.getViewRoot(); return (String) view.getAttributes().get("hierarchy"); } /** * @param hierarchyName */ protected void setHierarchyName(String hierarchyName) { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot view = context.getViewRoot(); if (hierarchyName == null) { view.getAttributes().remove("hierarchy"); } else { view.getAttributes().put("hierarchy", hierarchyName); } this.filterMembers = null; } protected Hierarchy getHierarchy() { String hierarchyName = getHierarchyName(); if (hierarchyName != null) { return model.getCube().getHierarchies().get(hierarchyName); } return null; } /** * @return the buttonApply */ public CommandButton getButtonApply() { return buttonApply; } /** * @param buttonApply * the buttonApply to set */ public void setButtonApply(CommandButton buttonApply) { this.buttonApply = buttonApply; } /** * @param id * @return */ protected List<Integer> getNodePath(String id) { // there should be a cleaner way to get data from the dropped component. // it's a limitation on PFs' side : // http://code.google.com/p/primefaces/issues/detail?id=2781 String[] segments = id.split(":"); String[] indexSegments = segments[segments.length - 2].split("_"); List<Integer> path = new ArrayList<Integer>(indexSegments.length); for (String index : indexSegments) { path.add(Integer.parseInt(index)); } return path; } /** * @param id * @return */ protected boolean isSourceNode(String id) { return id.startsWith("source-tree-form:cube-navigator"); } /** * @param e */ public void onNodeSelected(NodeSelectEvent e) { buttonApply.setDisabled(false); } /** * @param e */ public void onNodeUnselected(NodeUnselectEvent e) { buttonApply.setDisabled(false); } public void onClose() { setHierarchyName(null); } /** * @param e */ public void onDrop(DragDropEvent e) { List<Integer> sourcePath = getNodePath(e.getDragId()); Hierarchy hierarchy = null; if (isSourceNode(e.getDragId())) { TreeNode sourceNode = findNodeFromPath(navigator.getCubeNode(), sourcePath); if (sourceNode instanceof HierarchyNode) { HierarchyNode node = (HierarchyNode) sourceNode; hierarchy = node.getElement(); } else if (sourceNode instanceof LevelNode) { LevelNode node = (LevelNode) sourceNode; Level level = node.getElement(); hierarchy = level.getHierarchy(); } if (hierarchy == null) { return; } if (navigator.isSelected(hierarchy)) { String title = "Unable to filter hierarchy."; String message = "The specified hierarchy is already preresent on one of the axes."; FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage( FacesMessage.SEVERITY_WARN, title, message)); return; } UIComponent panel = createFilterItem(hierarchy); filterPanel.getChildren().add(panel); show(hierarchy.getName()); RequestContext.getCurrentInstance().execute("filterDialog.show();"); } } /** * @param axis * @param parent */ protected void configureFilter() { if (model != null && filterPanel != null) { filterPanel.getChildren().clear(); if (model.isInitialized()) { ChangeSlicer transform = model.getTransform(ChangeSlicer.class); List<Hierarchy> hierarchies = transform.getHierarchies(); for (Hierarchy hierarchy : hierarchies) { UIComponent panel = createFilterItem(hierarchy); filterPanel.getChildren().add(panel); } } } } /** * @param hierarchy * @return */ protected UIComponent createFilterItem(Hierarchy hierarchy) { String id = "filter-item-" + hierarchy.getName().replaceAll("[\\[\\]]", "") .replaceAll("[\\s\\.]", "_").toLowerCase(); HtmlPanelGroup panel = new HtmlPanelGroup(); panel.setId(id); panel.setLayout("block"); panel.setStyleClass("ui-widget-header filter-item"); CommandLink link = new CommandLink(); link.setId(id + "-link"); link.setValue(hierarchy.getCaption()); link.setTitle(hierarchy.getUniqueName()); FacesContext context = FacesContext.getCurrentInstance(); ExpressionFactory factory = context.getApplication() .getExpressionFactory(); link.setActionExpression(factory.createMethodExpression( context.getELContext(), "#{filterHandler.show}", Void.class, new Class<?>[0])); link.setUpdate(":filter-form"); link.setOncomplete("filterDialog.show();"); UIParameter parameter = new UIParameter(); parameter.setName("hierarchy"); parameter.setValue(hierarchy.getName()); link.getChildren().add(parameter); panel.getChildren().add(link); CommandButton closeButton = new CommandButton(); closeButton.setId(id + "-button"); closeButton.setIcon("ui-icon-close"); closeButton.setActionExpression(factory.createMethodExpression( context.getELContext(), "#{filterHandler.removeHierarchy}", Void.class, new Class<?>[0])); closeButton - .setUpdate(":filter-panel,:source-tree-form,:grid-form,:editor-form"); + .setUpdate(":filter-panel,:source-tree-form,:grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar"); UIParameter parameter2 = new UIParameter(); parameter2.setName("hierarchy"); parameter2.setValue(hierarchy.getName()); link.getChildren().add(parameter); panel.getChildren().add(closeButton); return panel; } public String getFilterItemId() { String hierarchyName = getHierarchyName(); if (hierarchyName == null) { return null; } return ":filter-item-" + hierarchyName.replaceAll("[\\[\\]]", "") .replaceAll("[\\s\\.]", "_").toLowerCase(); } public void show() { FacesContext context = FacesContext.getCurrentInstance(); Map<String, String> parameters = context.getExternalContext() .getRequestParameterMap(); String hierarchyName = parameters.get("hierarchy"); show(hierarchyName); } /** * @param hierarchyName */ public void show(String hierarchyName) { this.filterNode = null; setHierarchyName(hierarchyName); buttonApply.setDisabled(true); } public void apply() { List<Member> members = null; if (selection != null) { members = new ArrayList<Member>(selection.length); for (TreeNode node : selection) { MemberNode memberNode = (MemberNode) node; members.add(memberNode.getElement()); } } ChangeSlicer transform = model.getTransform(ChangeSlicer.class); transform.setSlicer(getHierarchy(), members); configureFilter(); } public void removeHierarchy() { FacesContext context = FacesContext.getCurrentInstance(); Map<String, String> parameters = context.getExternalContext() .getRequestParameterMap(); String hierarchyName = parameters.get("hierarchy"); removeHierarchy(hierarchyName); } /** * @param hierarchyName */ public void removeHierarchy(String hierarchyName) { Hierarchy hierarchy = model.getCube().getHierarchies() .get(hierarchyName); ChangeSlicer transform = model.getTransform(ChangeSlicer.class); transform.setSlicer(hierarchy, null); configureFilter(); } /** * @param parent * @param indexes * @return */ protected TreeNode findNodeFromPath(TreeNode parent, List<Integer> indexes) { if (indexes.size() > 1) { return findNodeFromPath(parent.getChildren().get(indexes.get(0)), indexes.subList(1, indexes.size())); } else { return parent.getChildren().get(indexes.get(0)); } } /** * @see com.eyeq.pivot4j.ModelChangeListener#modelInitialized(com.eyeq.pivot4j.ModelChangeEvent) */ @Override public void modelInitialized(ModelChangeEvent e) { } /** * @see com.eyeq.pivot4j.ModelChangeListener#modelDestroyed(com.eyeq.pivot4j.ModelChangeEvent) */ @Override public void modelDestroyed(ModelChangeEvent e) { } /** * @see com.eyeq.pivot4j.ModelChangeListener#modelChanged(com.eyeq.pivot4j.ModelChangeEvent) */ @Override public void modelChanged(ModelChangeEvent e) { } /** * @see com.eyeq.pivot4j.ModelChangeListener#structureChanged(com.eyeq.pivot4j.ModelChangeEvent) */ @Override public void structureChanged(ModelChangeEvent e) { configureFilter(); } /** * @param element * @return */ @Override public <T extends MetadataElement> boolean isSelected(T element) { return getFilteredMembers().isSelected((Member) element); } /** * @param element * @return */ @Override public <T extends MetadataElement> boolean isSelectable(T element) { return true; } /** * @see com.eyeq.pivot4j.primefaces.ui.tree.NodeFilter#isActive(org.olap4j.metadata.MetadataElement) */ @Override public <T extends MetadataElement> boolean isActive(T element) { return false; } /** * @see com.eyeq.pivot4j.primefaces.ui.tree.NodeFilter#isVisible(org.olap4j.metadata.MetadataElement) */ @Override public <T extends MetadataElement> boolean isVisible(T element) { return true; } /** * @see com.eyeq.pivot4j.primefaces.ui.tree.NodeFilter#isExpanded(org.olap4j.metadata.MetadataElement) */ @Override public <T extends MetadataElement> boolean isExpanded(T element) { return getFilteredMembers().findChild((Member) element) != null; } }
true
true
protected UIComponent createFilterItem(Hierarchy hierarchy) { String id = "filter-item-" + hierarchy.getName().replaceAll("[\\[\\]]", "") .replaceAll("[\\s\\.]", "_").toLowerCase(); HtmlPanelGroup panel = new HtmlPanelGroup(); panel.setId(id); panel.setLayout("block"); panel.setStyleClass("ui-widget-header filter-item"); CommandLink link = new CommandLink(); link.setId(id + "-link"); link.setValue(hierarchy.getCaption()); link.setTitle(hierarchy.getUniqueName()); FacesContext context = FacesContext.getCurrentInstance(); ExpressionFactory factory = context.getApplication() .getExpressionFactory(); link.setActionExpression(factory.createMethodExpression( context.getELContext(), "#{filterHandler.show}", Void.class, new Class<?>[0])); link.setUpdate(":filter-form"); link.setOncomplete("filterDialog.show();"); UIParameter parameter = new UIParameter(); parameter.setName("hierarchy"); parameter.setValue(hierarchy.getName()); link.getChildren().add(parameter); panel.getChildren().add(link); CommandButton closeButton = new CommandButton(); closeButton.setId(id + "-button"); closeButton.setIcon("ui-icon-close"); closeButton.setActionExpression(factory.createMethodExpression( context.getELContext(), "#{filterHandler.removeHierarchy}", Void.class, new Class<?>[0])); closeButton .setUpdate(":filter-panel,:source-tree-form,:grid-form,:editor-form"); UIParameter parameter2 = new UIParameter(); parameter2.setName("hierarchy"); parameter2.setValue(hierarchy.getName()); link.getChildren().add(parameter); panel.getChildren().add(closeButton); return panel; }
protected UIComponent createFilterItem(Hierarchy hierarchy) { String id = "filter-item-" + hierarchy.getName().replaceAll("[\\[\\]]", "") .replaceAll("[\\s\\.]", "_").toLowerCase(); HtmlPanelGroup panel = new HtmlPanelGroup(); panel.setId(id); panel.setLayout("block"); panel.setStyleClass("ui-widget-header filter-item"); CommandLink link = new CommandLink(); link.setId(id + "-link"); link.setValue(hierarchy.getCaption()); link.setTitle(hierarchy.getUniqueName()); FacesContext context = FacesContext.getCurrentInstance(); ExpressionFactory factory = context.getApplication() .getExpressionFactory(); link.setActionExpression(factory.createMethodExpression( context.getELContext(), "#{filterHandler.show}", Void.class, new Class<?>[0])); link.setUpdate(":filter-form"); link.setOncomplete("filterDialog.show();"); UIParameter parameter = new UIParameter(); parameter.setName("hierarchy"); parameter.setValue(hierarchy.getName()); link.getChildren().add(parameter); panel.getChildren().add(link); CommandButton closeButton = new CommandButton(); closeButton.setId(id + "-button"); closeButton.setIcon("ui-icon-close"); closeButton.setActionExpression(factory.createMethodExpression( context.getELContext(), "#{filterHandler.removeHierarchy}", Void.class, new Class<?>[0])); closeButton .setUpdate(":filter-panel,:source-tree-form,:grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar"); UIParameter parameter2 = new UIParameter(); parameter2.setName("hierarchy"); parameter2.setValue(hierarchy.getName()); link.getChildren().add(parameter); panel.getChildren().add(closeButton); return panel; }
diff --git a/src/main/java/net/praqma/ccanalyzer/AbstractClient.java b/src/main/java/net/praqma/ccanalyzer/AbstractClient.java index 49ae09f..a3bee92 100644 --- a/src/main/java/net/praqma/ccanalyzer/AbstractClient.java +++ b/src/main/java/net/praqma/ccanalyzer/AbstractClient.java @@ -1,84 +1,84 @@ package net.praqma.ccanalyzer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import net.praqma.monkit.MonKit; public abstract class AbstractClient { protected int port; protected String host; protected String clientName; protected MonKit monkit; public AbstractClient( int port, String host, String clientName, MonKit mk ) { this.port = port; this.host = host; this.clientName = clientName; this.monkit = mk; System.out.println( "CCAnalyzer client version " + Server.version ); } public void start( ConfigurationReader counters ) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; System.out.print( "Trying to connect to " + host ); try { socket = new Socket( host, port ); out = new PrintWriter( socket.getOutputStream(), true ); } catch( UnknownHostException e ) { System.out.println( "\rError, unkown host " + host + "\n" ); return; } catch( IOException e ) { System.out.println( "\rError, unable to connect to " + host + "\n" ); return; } in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); String line = ""; /* Super simple handshaking.... */ out.println( "version " + Server.version ); while( ( line = in.readLine() ) != null ) { break; } - if( !line.equals( Server.version ) ) { + if( !line.equals( Integer.toString( Server.version ) ) ) { System.out.println( "\rError, version mismatch at " + host + "\n" ); out.close(); in.close(); socket.close(); throw new CCAnalyzerException( "Version mismatch, got " + line + " expected " + Server.version ); } System.out.println( "\rSuccessfully connected to " + host ); /* Do the counting */ perform( counters, out, in ); out.println( "exit" ); out.close(); in.close(); socket.close(); System.out.println( "Disconnected\n" ); } protected abstract void perform( ConfigurationReader counters, PrintWriter out, BufferedReader in ) throws IOException; }
true
true
public void start( ConfigurationReader counters ) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; System.out.print( "Trying to connect to " + host ); try { socket = new Socket( host, port ); out = new PrintWriter( socket.getOutputStream(), true ); } catch( UnknownHostException e ) { System.out.println( "\rError, unkown host " + host + "\n" ); return; } catch( IOException e ) { System.out.println( "\rError, unable to connect to " + host + "\n" ); return; } in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); String line = ""; /* Super simple handshaking.... */ out.println( "version " + Server.version ); while( ( line = in.readLine() ) != null ) { break; } if( !line.equals( Server.version ) ) { System.out.println( "\rError, version mismatch at " + host + "\n" ); out.close(); in.close(); socket.close(); throw new CCAnalyzerException( "Version mismatch, got " + line + " expected " + Server.version ); } System.out.println( "\rSuccessfully connected to " + host ); /* Do the counting */ perform( counters, out, in ); out.println( "exit" ); out.close(); in.close(); socket.close(); System.out.println( "Disconnected\n" ); }
public void start( ConfigurationReader counters ) throws IOException { Socket socket = null; PrintWriter out = null; BufferedReader in = null; System.out.print( "Trying to connect to " + host ); try { socket = new Socket( host, port ); out = new PrintWriter( socket.getOutputStream(), true ); } catch( UnknownHostException e ) { System.out.println( "\rError, unkown host " + host + "\n" ); return; } catch( IOException e ) { System.out.println( "\rError, unable to connect to " + host + "\n" ); return; } in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); String line = ""; /* Super simple handshaking.... */ out.println( "version " + Server.version ); while( ( line = in.readLine() ) != null ) { break; } if( !line.equals( Integer.toString( Server.version ) ) ) { System.out.println( "\rError, version mismatch at " + host + "\n" ); out.close(); in.close(); socket.close(); throw new CCAnalyzerException( "Version mismatch, got " + line + " expected " + Server.version ); } System.out.println( "\rSuccessfully connected to " + host ); /* Do the counting */ perform( counters, out, in ); out.println( "exit" ); out.close(); in.close(); socket.close(); System.out.println( "Disconnected\n" ); }
diff --git a/src/neurohadoop/ConvolutionMapper.java b/src/neurohadoop/ConvolutionMapper.java index 90834cc..76e7737 100644 --- a/src/neurohadoop/ConvolutionMapper.java +++ b/src/neurohadoop/ConvolutionMapper.java @@ -1,210 +1,210 @@ package neurohadoop; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.util.HashMap; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.fs.Path; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; //import org.apache.log4j.Logger; /* * ConvolutionMapper */ public class ConvolutionMapper extends MapReduceBase implements Mapper<LongWritable, Text, NullWritable, RatWritable> { public static final String HDFS_KERNEL = "lookup/morlet-2000.dat"; public static final int SIGNAL_BUFFER_SIZE = 16777216; public static final int KERNEL_START_FREQ = 5; public static final int KERNEL_END_FREQ = 200; public static final int KERNEL_WINDOW_SIZE = 2001; static enum Parse_Counters { BAD_PARSE }; private String sessiondate; private final RatWritable out_value = new RatWritable(); private HashMap<Integer, String> kernelMap; private short[][] kernelStack = new short[KERNEL_END_FREQ + 1][KERNEL_WINDOW_SIZE]; private int n = 0; private float[] signal = new float[SIGNAL_BUFFER_SIZE]; private float[] kernel = new float[SIGNAL_BUFFER_SIZE]; private long[] timestamp = new long[SIGNAL_BUFFER_SIZE]; private OutputCollector<NullWritable, RatWritable> saveOutput; private RatInputFormat rec; private long lastTimestamp = 0; // private static final Logger logger = // Logger.getLogger(ConvolutionMapper.class); private long tempTime; @Override public void configure(JobConf conf) { tempTime = System.currentTimeMillis(); String fpath = conf.get("map.input.file"); String fname = new File(fpath).getName(); int indexBegin = 0; int indexEnd = fname.indexOf('-'); indexBegin = indexEnd + 1; indexEnd = fname.indexOf('-', indexBegin); sessiondate = fname.substring(indexBegin, indexEnd); indexBegin = indexEnd + 1; indexEnd = fname.indexOf('-', indexBegin); sessiondate = sessiondate + '-' + fname.substring(indexBegin, indexEnd); indexBegin = indexEnd + 1; indexEnd = fname.indexOf('-', indexBegin); sessiondate = sessiondate + '-' + fname.substring(indexBegin, indexEnd); indexBegin = indexEnd + 4; indexEnd = fname.indexOf('.', indexBegin); try { String kernelCacheName = new Path(HDFS_KERNEL).getName(); Path[] cacheFiles = DistributedCache.getLocalCacheFiles(conf); if (null != cacheFiles && cacheFiles.length > 0) { for (Path cachePath : cacheFiles) { if (cachePath.getName().equals(kernelCacheName)) { loadKernel(cachePath); break; } // if } // for for (int i = KERNEL_START_FREQ; i <= KERNEL_END_FREQ; i++) { kernelStack[i] = ConvertStringArrayToShortArray(kernelMap .get(i).split(",")); } // for } // if } catch (IOException ioe) { System.err.println("IOException reading from distributed cache"); System.err.println(ioe.toString()); } // try System.out.println("Load Kernel: " + (System.currentTimeMillis() - tempTime)); tempTime = System.currentTimeMillis(); } // configure public void loadKernel(Path cachePath) throws IOException { BufferedReader kernelReader = new BufferedReader(new FileReader( cachePath.toString())); try { String line = ""; int kernelFreq = KERNEL_START_FREQ; this.kernelMap = new HashMap<Integer, String>(); while ((line = kernelReader.readLine()) != null) { this.kernelMap.put(kernelFreq, line); kernelFreq++; } } finally { kernelReader.close(); } } // loadKernel public short[] ConvertStringArrayToShortArray(String[] stringArray) { short shortArray[] = new short[stringArray.length]; for (int i = 0; i < stringArray.length; i++) { shortArray[i] = Short.parseShort(stringArray[i]); } return shortArray; } // Convert @Override public void map(LongWritable inkey, Text value, OutputCollector<NullWritable, RatWritable> output, Reporter reporter) throws IOException { saveOutput = output; rec = RatInputFormat.parse(value.toString()); try { if (lastTimestamp > rec.getTimestamp()) { throw new IOException("Timestamp not sorted at: " + lastTimestamp + " and " + rec.getTimestamp()); } lastTimestamp = rec.getTimestamp(); timestamp[n] = lastTimestamp; signal[n] = rec.getVoltage(); n++; } catch (IOException ioe) { System.err.println(ioe.getMessage()); System.exit(0); } // catch } // map @Override public void close() throws IOException { FloatFFT_1D fft = new FloatFFT_1D(SIGNAL_BUFFER_SIZE / 2); try { for (int i = n; i < SIGNAL_BUFFER_SIZE / 2; i++) { signal[i] = 0; } System.out.println("Load Data: " + (System.currentTimeMillis() - tempTime)); tempTime = System.currentTimeMillis(); fft.realForwardFull(signal); System.out.println("Signal FFT: " + (System.currentTimeMillis() - tempTime)); - for (int k = KERNEL_START_FREQ; k <= KERNEL_END_FREQ; k++) { + for (short k = KERNEL_START_FREQ; k <= KERNEL_END_FREQ; k++) { // Kernel FFT tempTime = System.currentTimeMillis(); for (int j = 0; j < KERNEL_WINDOW_SIZE; j++) { kernel[j] = (float) kernelStack[k][j]; } for (int j = KERNEL_WINDOW_SIZE; j < SIGNAL_BUFFER_SIZE / 2; j++) { kernel[j] = 0; } fft.realForwardFull(kernel); System.out.println("Kernel FFT: " + (System.currentTimeMillis() - tempTime)); // Product tempTime = System.currentTimeMillis(); float temp; for (int i = 0; i < SIGNAL_BUFFER_SIZE; i = i + 2) { temp = kernel[i]; kernel[i] = kernel[i] * signal[i] - kernel[i + 1] * signal[i + 1]; kernel[i + 1] = -(temp * signal[i + 1] + kernel[i + 1] * signal[i]); } System.out.println("Product: " + (System.currentTimeMillis() - tempTime)); // Inverse FFT tempTime = System.currentTimeMillis(); fft.complexInverse(kernel, true); System.out.println("Inverse FFT: " + (System.currentTimeMillis() - tempTime)); // Output tempTime = System.currentTimeMillis(); int t = KERNEL_WINDOW_SIZE - 1; for (int i = (SIGNAL_BUFFER_SIZE / 2 - KERNEL_WINDOW_SIZE + 1) * 2; i > (SIGNAL_BUFFER_SIZE / 2 - n) * 2; i = i - 2) { out_value.timestamp = t; out_value.frequency = k; out_value.convolution = (float)Math.pow(kernel[i],2); saveOutput.collect(NullWritable.get(), out_value); t++; } System.out.println("Output Data: " + (System.currentTimeMillis() - tempTime)); } // for } catch (IOException ioe) { System.err.println(ioe.getMessage()); System.exit(0); } // try } }
true
true
public void close() throws IOException { FloatFFT_1D fft = new FloatFFT_1D(SIGNAL_BUFFER_SIZE / 2); try { for (int i = n; i < SIGNAL_BUFFER_SIZE / 2; i++) { signal[i] = 0; } System.out.println("Load Data: " + (System.currentTimeMillis() - tempTime)); tempTime = System.currentTimeMillis(); fft.realForwardFull(signal); System.out.println("Signal FFT: " + (System.currentTimeMillis() - tempTime)); for (int k = KERNEL_START_FREQ; k <= KERNEL_END_FREQ; k++) { // Kernel FFT tempTime = System.currentTimeMillis(); for (int j = 0; j < KERNEL_WINDOW_SIZE; j++) { kernel[j] = (float) kernelStack[k][j]; } for (int j = KERNEL_WINDOW_SIZE; j < SIGNAL_BUFFER_SIZE / 2; j++) { kernel[j] = 0; } fft.realForwardFull(kernel); System.out.println("Kernel FFT: " + (System.currentTimeMillis() - tempTime)); // Product tempTime = System.currentTimeMillis(); float temp; for (int i = 0; i < SIGNAL_BUFFER_SIZE; i = i + 2) { temp = kernel[i]; kernel[i] = kernel[i] * signal[i] - kernel[i + 1] * signal[i + 1]; kernel[i + 1] = -(temp * signal[i + 1] + kernel[i + 1] * signal[i]); } System.out.println("Product: " + (System.currentTimeMillis() - tempTime)); // Inverse FFT tempTime = System.currentTimeMillis(); fft.complexInverse(kernel, true); System.out.println("Inverse FFT: " + (System.currentTimeMillis() - tempTime)); // Output tempTime = System.currentTimeMillis(); int t = KERNEL_WINDOW_SIZE - 1; for (int i = (SIGNAL_BUFFER_SIZE / 2 - KERNEL_WINDOW_SIZE + 1) * 2; i > (SIGNAL_BUFFER_SIZE / 2 - n) * 2; i = i - 2) { out_value.timestamp = t; out_value.frequency = k; out_value.convolution = (float)Math.pow(kernel[i],2); saveOutput.collect(NullWritable.get(), out_value); t++; } System.out.println("Output Data: " + (System.currentTimeMillis() - tempTime)); } // for } catch (IOException ioe) { System.err.println(ioe.getMessage()); System.exit(0); } // try }
public void close() throws IOException { FloatFFT_1D fft = new FloatFFT_1D(SIGNAL_BUFFER_SIZE / 2); try { for (int i = n; i < SIGNAL_BUFFER_SIZE / 2; i++) { signal[i] = 0; } System.out.println("Load Data: " + (System.currentTimeMillis() - tempTime)); tempTime = System.currentTimeMillis(); fft.realForwardFull(signal); System.out.println("Signal FFT: " + (System.currentTimeMillis() - tempTime)); for (short k = KERNEL_START_FREQ; k <= KERNEL_END_FREQ; k++) { // Kernel FFT tempTime = System.currentTimeMillis(); for (int j = 0; j < KERNEL_WINDOW_SIZE; j++) { kernel[j] = (float) kernelStack[k][j]; } for (int j = KERNEL_WINDOW_SIZE; j < SIGNAL_BUFFER_SIZE / 2; j++) { kernel[j] = 0; } fft.realForwardFull(kernel); System.out.println("Kernel FFT: " + (System.currentTimeMillis() - tempTime)); // Product tempTime = System.currentTimeMillis(); float temp; for (int i = 0; i < SIGNAL_BUFFER_SIZE; i = i + 2) { temp = kernel[i]; kernel[i] = kernel[i] * signal[i] - kernel[i + 1] * signal[i + 1]; kernel[i + 1] = -(temp * signal[i + 1] + kernel[i + 1] * signal[i]); } System.out.println("Product: " + (System.currentTimeMillis() - tempTime)); // Inverse FFT tempTime = System.currentTimeMillis(); fft.complexInverse(kernel, true); System.out.println("Inverse FFT: " + (System.currentTimeMillis() - tempTime)); // Output tempTime = System.currentTimeMillis(); int t = KERNEL_WINDOW_SIZE - 1; for (int i = (SIGNAL_BUFFER_SIZE / 2 - KERNEL_WINDOW_SIZE + 1) * 2; i > (SIGNAL_BUFFER_SIZE / 2 - n) * 2; i = i - 2) { out_value.timestamp = t; out_value.frequency = k; out_value.convolution = (float)Math.pow(kernel[i],2); saveOutput.collect(NullWritable.get(), out_value); t++; } System.out.println("Output Data: " + (System.currentTimeMillis() - tempTime)); } // for } catch (IOException ioe) { System.err.println(ioe.getMessage()); System.exit(0); } // try }
diff --git a/src/net/channel/handler/AranComboHandler.java b/src/net/channel/handler/AranComboHandler.java index 5e76f37..ab9989c 100644 --- a/src/net/channel/handler/AranComboHandler.java +++ b/src/net/channel/handler/AranComboHandler.java @@ -1,60 +1,60 @@ /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <[email protected]> Matthias Butz <[email protected]> Jan Christian Meyer <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.channel.handler; import client.MapleCharacter; import client.MapleClient; import client.SkillFactory; import net.AbstractMaplePacketHandler; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; public class AranComboHandler extends AbstractMaplePacketHandler { public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { MapleCharacter player = c.getPlayer(); if (player.getJobType() == 2) { //Keep it this till Evan comes in Private Servers. - if ((System.currentTimeMillis() - player.getLastAttack()) > 3000) { + if (player.getComboCounter() > 0 && (System.currentTimeMillis() - player.getLastAttack() > 3000)) { player.setComboCounter(0); } else { int combo = player.getComboCounter() + 1; switch (combo) { case 10: case 20: case 30: case 40: case 50: case 60: case 70: case 80: case 90: case 100: SkillFactory.getSkill(21000000).getEffect(combo / 10).applyComboBuff(player, combo); break; } player.setLastAttack(System.currentTimeMillis()); player.setComboCounter(combo); - c.getSession().write(MaplePacketCreator.showCombo(player.getComboCounter())); + c.getSession().write(MaplePacketCreator.showCombo(combo)); } } } }
false
true
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { MapleCharacter player = c.getPlayer(); if (player.getJobType() == 2) { //Keep it this till Evan comes in Private Servers. if ((System.currentTimeMillis() - player.getLastAttack()) > 3000) { player.setComboCounter(0); } else { int combo = player.getComboCounter() + 1; switch (combo) { case 10: case 20: case 30: case 40: case 50: case 60: case 70: case 80: case 90: case 100: SkillFactory.getSkill(21000000).getEffect(combo / 10).applyComboBuff(player, combo); break; } player.setLastAttack(System.currentTimeMillis()); player.setComboCounter(combo); c.getSession().write(MaplePacketCreator.showCombo(player.getComboCounter())); } } }
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { MapleCharacter player = c.getPlayer(); if (player.getJobType() == 2) { //Keep it this till Evan comes in Private Servers. if (player.getComboCounter() > 0 && (System.currentTimeMillis() - player.getLastAttack() > 3000)) { player.setComboCounter(0); } else { int combo = player.getComboCounter() + 1; switch (combo) { case 10: case 20: case 30: case 40: case 50: case 60: case 70: case 80: case 90: case 100: SkillFactory.getSkill(21000000).getEffect(combo / 10).applyComboBuff(player, combo); break; } player.setLastAttack(System.currentTimeMillis()); player.setComboCounter(combo); c.getSession().write(MaplePacketCreator.showCombo(combo)); } } }
diff --git a/plugins/org.eclipse.acceleo.common/src/org/eclipse/acceleo/common/internal/utils/AcceleoLibrariesEclipseUtil.java b/plugins/org.eclipse.acceleo.common/src/org/eclipse/acceleo/common/internal/utils/AcceleoLibrariesEclipseUtil.java index 55a28d23..ae51cd87 100644 --- a/plugins/org.eclipse.acceleo.common/src/org/eclipse/acceleo/common/internal/utils/AcceleoLibrariesEclipseUtil.java +++ b/plugins/org.eclipse.acceleo.common/src/org/eclipse/acceleo/common/internal/utils/AcceleoLibrariesEclipseUtil.java @@ -1,77 +1,77 @@ /******************************************************************************* * Copyright (c) 2009 Obeo. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.acceleo.common.internal.utils; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Set; import org.eclipse.acceleo.common.library.connector.ILibrary; /** * Eclipse-specific utilities for Acceleo services. It will be initialized with all libraries that could be * parsed from the extension point if Eclipse is running and won't be used when outside of Eclipse. * * @author <a href="mailto:[email protected]">Laurent Goubet</a> */ public final class AcceleoLibrariesEclipseUtil { /** Keeps track of all connectors that are contributed to the libraries extension point. */ private static final Set<ILibrary> LIBRARIES = new LinkedHashSet<ILibrary>(); /** * Utility classes don't need a default constructor. */ private AcceleoLibrariesEclipseUtil() { // hides constructor } /** * Add a library to this registry. * * @param library * the library to add */ public static void addLibrary(ILibrary library) { LIBRARIES.add(library); } /** * Clears all registered extensions out of the eclipse registry. */ public static void clearRegistry() { LIBRARIES.clear(); } /** * Returns all registered library instances. * * @return All registered library instances. */ public static Set<ILibrary> getRegisteredLibraries() { AcceleoWorkspaceUtil.refreshContributions(); return new LinkedHashSet<ILibrary>(LIBRARIES); } /** * Removes a given libraries from the list of available ones. * * @param library * The filename of the library that is to be removed. */ public static void removeLibrary(String library) { for (ILibrary candidate : new ArrayList<ILibrary>(LIBRARIES)) { - if (library.equals(candidate.getURI())) { + if (candidate.getURI().toString().endsWith(library)) { LIBRARIES.remove(candidate); } } } }
true
true
public static void removeLibrary(String library) { for (ILibrary candidate : new ArrayList<ILibrary>(LIBRARIES)) { if (library.equals(candidate.getURI())) { LIBRARIES.remove(candidate); } } }
public static void removeLibrary(String library) { for (ILibrary candidate : new ArrayList<ILibrary>(LIBRARIES)) { if (candidate.getURI().toString().endsWith(library)) { LIBRARIES.remove(candidate); } } }
diff --git a/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/ConsumerResourceCreationTest.java b/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/ConsumerResourceCreationTest.java index 6d744581c..3f5015938 100644 --- a/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/ConsumerResourceCreationTest.java +++ b/proxy/src/test/java/org/fedoraproject/candlepin/resource/test/ConsumerResourceCreationTest.java @@ -1,177 +1,177 @@ /** * Copyright (c) 2009 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.fedoraproject.candlepin.resource.test; import java.util.Arrays; import java.util.EnumSet; import java.util.Locale; import static org.mockito.Mockito.any; import static org.mockito.Mockito.when; import org.fedoraproject.candlepin.audit.EventSink; import org.fedoraproject.candlepin.auth.Principal; import org.fedoraproject.candlepin.auth.Role; import org.fedoraproject.candlepin.auth.UserPrincipal; import org.fedoraproject.candlepin.exceptions.BadRequestException; import org.fedoraproject.candlepin.model.Consumer; import org.fedoraproject.candlepin.model.ConsumerCurator; import org.fedoraproject.candlepin.model.ConsumerType; import org.fedoraproject.candlepin.model.ConsumerTypeCurator; import org.fedoraproject.candlepin.model.IdentityCertificate; import org.fedoraproject.candlepin.model.NewRole; import org.fedoraproject.candlepin.model.Owner; import org.fedoraproject.candlepin.model.OwnerCurator; import org.fedoraproject.candlepin.model.Permission; import org.fedoraproject.candlepin.model.User; import org.fedoraproject.candlepin.resource.ConsumerResource; import org.fedoraproject.candlepin.service.IdentityCertServiceAdapter; import org.fedoraproject.candlepin.service.SubscriptionServiceAdapter; import org.fedoraproject.candlepin.service.UserServiceAdapter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.xnap.commons.i18n.I18n; import org.xnap.commons.i18n.I18nFactory; /** * */ @RunWith(MockitoJUnitRunner.class) public class ConsumerResourceCreationTest { private static final String USER = "testuser"; @Mock private UserServiceAdapter userService; @Mock private IdentityCertServiceAdapter idCertService; @Mock private SubscriptionServiceAdapter subscriptionService; @Mock private ConsumerCurator consumerCurator; @Mock private ConsumerTypeCurator consumerTypeCurator; @Mock private OwnerCurator ownerCurator; @Mock private EventSink sink; private I18n i18n; private ConsumerResource resource; private ConsumerType system; @Before public void init() throws Exception { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.resource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, null, null, null, this.userService, null, null, null, null, this.ownerCurator); this.system = new ConsumerType(ConsumerType.ConsumerTypeEnum.SYSTEM); Owner owner = new Owner("test_owner"); User user = new User(USER, ""); Permission p = new Permission(owner, EnumSet.of(Role.OWNER_ADMIN)); NewRole role = new NewRole(); role.addPermission(p); role.addUser(user); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(consumerTypeCurator.lookupByLabel(system.getLabel())).thenReturn(system); - when(userService.getOwners(USER)).thenReturn(Arrays.asList(new Owner[] {owner})); + when(userService.getRoles(USER)).thenReturn(Arrays.asList(new NewRole[] {role})); when(userService.findByLogin(USER)).thenReturn(user); when(idCertService.generateIdentityCert(any(Consumer.class))) .thenReturn(new IdentityCertificate()); when(ownerCurator.lookupByKey(owner.getKey())).thenReturn(owner); } private Consumer createConsumer(String consumerName) { Consumer consumer = new Consumer(consumerName, null, null, system); Principal principal = new UserPrincipal(USER, null); return this.resource.create(consumer, principal, USER, null); } @Test public void acceptedConsumerName() { Assert.assertNotNull(createConsumer("test_user")); } @Test public void camelCaseName() { Assert.assertNotNull(createConsumer("ConsumerTest32953")); } @Test public void startsWithUnderscore() { Assert.assertNotNull(createConsumer("__init__")); } @Test public void startsWithDash() { Assert.assertNotNull(createConsumer("-dash")); } @Test public void containsNumbers() { Assert.assertNotNull(createConsumer("testmachine99")); } @Test public void startsWithNumbers() { Assert.assertNotNull(createConsumer("001test7")); } @Test public void containsPeriods() { Assert.assertNotNull(createConsumer("test-system.resource.net")); } @Test public void containsUserServiceChars() { Assert.assertNotNull(createConsumer("{bob}'s_b!g_#boi.`?uestlove!x")); } @Test(expected = BadRequestException.class) public void startsWithPound() { createConsumer("#pound"); } @Test(expected = BadRequestException.class) public void emptyConsumerName() { createConsumer(""); } @Test(expected = BadRequestException.class) public void nullConsumerName() { createConsumer(null); } @Test(expected = BadRequestException.class) public void startsWithBadCharacter() { createConsumer("#foo"); } @Test(expected = BadRequestException.class) public void containsBadCharacter() { createConsumer("bar$%camp"); } }
true
true
public void init() throws Exception { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.resource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, null, null, null, this.userService, null, null, null, null, this.ownerCurator); this.system = new ConsumerType(ConsumerType.ConsumerTypeEnum.SYSTEM); Owner owner = new Owner("test_owner"); User user = new User(USER, ""); Permission p = new Permission(owner, EnumSet.of(Role.OWNER_ADMIN)); NewRole role = new NewRole(); role.addPermission(p); role.addUser(user); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(consumerTypeCurator.lookupByLabel(system.getLabel())).thenReturn(system); when(userService.getOwners(USER)).thenReturn(Arrays.asList(new Owner[] {owner})); when(userService.findByLogin(USER)).thenReturn(user); when(idCertService.generateIdentityCert(any(Consumer.class))) .thenReturn(new IdentityCertificate()); when(ownerCurator.lookupByKey(owner.getKey())).thenReturn(owner); }
public void init() throws Exception { this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.resource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, null, this.idCertService, null, this.i18n, this.sink, null, null, null, this.userService, null, null, null, null, this.ownerCurator); this.system = new ConsumerType(ConsumerType.ConsumerTypeEnum.SYSTEM); Owner owner = new Owner("test_owner"); User user = new User(USER, ""); Permission p = new Permission(owner, EnumSet.of(Role.OWNER_ADMIN)); NewRole role = new NewRole(); role.addPermission(p); role.addUser(user); when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArguments()[0]; } }); when(consumerTypeCurator.lookupByLabel(system.getLabel())).thenReturn(system); when(userService.getRoles(USER)).thenReturn(Arrays.asList(new NewRole[] {role})); when(userService.findByLogin(USER)).thenReturn(user); when(idCertService.generateIdentityCert(any(Consumer.class))) .thenReturn(new IdentityCertificate()); when(ownerCurator.lookupByKey(owner.getKey())).thenReturn(owner); }
diff --git a/graylog2-server/src/test/java/org/graylog2/ConfigurationTest.java b/graylog2-server/src/test/java/org/graylog2/ConfigurationTest.java index 38aa1c745..7c8e76eeb 100644 --- a/graylog2-server/src/test/java/org/graylog2/ConfigurationTest.java +++ b/graylog2-server/src/test/java/org/graylog2/ConfigurationTest.java @@ -1,234 +1,234 @@ package org.graylog2; import com.github.joschi.jadconfig.JadConfig; import com.github.joschi.jadconfig.RepositoryException; import com.github.joschi.jadconfig.ValidationException; import com.github.joschi.jadconfig.repositories.InMemoryRepository; import com.google.common.collect.Maps; import org.junit.Assert; import org.bson.types.ObjectId; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Map; /** * Unit tests for {@link Configuration} class * * @author Jochen Schalanda <[email protected]> */ public class ConfigurationTest { Map<String, String> validProperties; private File tempFile; @Before public void setUp() { validProperties = Maps.newHashMap(); try { tempFile = File.createTempFile("graylog", null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Required properties validProperties.put("password_secret", "ipNUnWxmBLCxTEzXcyamrdy0Q3G7HxdKsAvyg30R9SCof0JydiZFiA3dLSkRsbLF"); validProperties.put("elasticsearch_config_file", tempFile.getAbsolutePath()); validProperties.put("force_syslog_rdns", "false"); validProperties.put("syslog_listen_port", "514"); validProperties.put("syslog_protocol", "udp"); validProperties.put("mongodb_useauth", "true"); validProperties.put("mongodb_user", "user"); validProperties.put("mongodb_password", "pass"); validProperties.put("mongodb_database", "test"); validProperties.put("mongodb_host", "localhost"); validProperties.put("mongodb_port", "27017"); validProperties.put("use_gelf", "true"); validProperties.put("gelf_listen_port", "12201"); - validProperties.put("root_password_sha1", "d033e22ae348aeb5660fc2140aec35850c4da997"); // sha1 of admin + validProperties.put("root_password_sha2", "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"); // sha2 of admin // Additional numerical properties validProperties.put("mongodb_max_connections", "100"); validProperties.put("mongodb_threads_allowed_to_block_multiplier", "50"); validProperties.put("amqp_port", "5672"); validProperties.put("forwarder_loggly_timeout", "3"); } @After public void tearDown() { tempFile.delete(); } @Test(expected = ValidationException.class) public void testValidateMongoDbAuth() throws RepositoryException, ValidationException { validProperties.put("mongodb_useauth", "true"); validProperties.remove("mongodb_user"); validProperties.remove("mongodb_password"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); } @Test public void testGetElasticSearchIndexPrefix() throws RepositoryException, ValidationException { Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals("graylog2", configuration.getElasticSearchIndexPrefix()); } @Test public void testGetMaximumMongoDBConnections() throws RepositoryException, ValidationException { validProperties.put("mongodb_max_connections", "12345"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(12345, configuration.getMongoMaxConnections()); } @Test public void testGetMaximumMongoDBConnectionsDefault() throws RepositoryException, ValidationException { validProperties.remove("mongodb_max_connections"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(1000, configuration.getMongoMaxConnections()); } @Test public void testGetThreadsAllowedToBlockMultiplier() throws RepositoryException, ValidationException { validProperties.put("mongodb_threads_allowed_to_block_multiplier", "12345"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(12345, configuration.getMongoThreadsAllowedToBlockMultiplier()); } @Test public void testGetThreadsAllowedToBlockMultiplierDefault() throws RepositoryException, ValidationException { validProperties.remove("mongodb_threads_allowed_to_block_multiplier"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(5, configuration.getMongoThreadsAllowedToBlockMultiplier()); } /*@Test public void testGetAMQPSubscribedQueuesEmpty() throws RepositoryException, ValidationException { validProperties.put("amqp_subscribed_queues", ""); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNull(configuration.getAmqpSubscribedQueues()); } @Test public void testGetAMQPSubscribedQueuesMalformed() throws RepositoryException, ValidationException { validProperties.put("amqp_subscribed_queues", "queue-invalid"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNull(configuration.getAmqpSubscribedQueues()); } @Test public void testGetAMQPSubscribedQueuesInvalidQueueType() throws RepositoryException, ValidationException { validProperties.put("amqp_subscribed_queues", "queue1:gelf,queue2:invalid"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNull(configuration.getAmqpSubscribedQueues()); } @Test public void testGetAMQPSubscribedQueues() throws RepositoryException, ValidationException { validProperties.put("amqp_subscribed_queues", "queue1:gelf,queue2:syslog"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(2, configuration.getAmqpSubscribedQueues().size()); }*/ @Test public void testGetMongoDBReplicaSetServersEmpty() throws RepositoryException, ValidationException { validProperties.put("mongodb_replica_set", ""); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNull(configuration.getMongoReplicaSet()); } @Test public void testGetMongoDBReplicaSetServersMalformed() throws RepositoryException, ValidationException { validProperties.put("mongodb_replica_set", "malformed"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNull(configuration.getMongoReplicaSet()); } @Test public void testGetMongoDBReplicaSetServersUnknownHost() throws RepositoryException, ValidationException { validProperties.put("mongodb_replica_set", "this-host-hopefully-does-not-exist.:27017"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertNull(configuration.getMongoReplicaSet()); } @Test public void testGetMongoDBReplicaSetServers() throws RepositoryException, ValidationException { validProperties.put("mongodb_replica_set", "127.0.0.1:27017,127.0.0.1:27018"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(2, configuration.getMongoReplicaSet().size()); } @Test public void testGetLibratoMetricsStreamFilter() throws RepositoryException, ValidationException { ObjectId id1 = new ObjectId(); ObjectId id2 = new ObjectId(); ObjectId id3 = new ObjectId(); validProperties.put("libratometrics_stream_filter", id1.toString() + "," + id2.toString() + "," + id3.toString()); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals(3, configuration.getLibratoMetricsStreamFilter().size()); Assert.assertTrue(configuration.getLibratoMetricsStreamFilter().contains(id1.toString())); Assert.assertTrue(configuration.getLibratoMetricsStreamFilter().contains(id2.toString())); Assert.assertTrue(configuration.getLibratoMetricsStreamFilter().contains(id3.toString())); } @Test public void testGetLibratoMetricsPrefix() throws RepositoryException, ValidationException { validProperties.put("libratometrics_prefix", "lolwut"); Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals("lolwut", configuration.getLibratoMetricsPrefix()); } @Test public void testGetLibratoMetricsPrefixHasStandardValue() throws RepositoryException, ValidationException { // Nothing set. Configuration configuration = new Configuration(); new JadConfig(new InMemoryRepository(validProperties), configuration).process(); Assert.assertEquals("gl2-", configuration.getLibratoMetricsPrefix()); } }
true
true
public void setUp() { validProperties = Maps.newHashMap(); try { tempFile = File.createTempFile("graylog", null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Required properties validProperties.put("password_secret", "ipNUnWxmBLCxTEzXcyamrdy0Q3G7HxdKsAvyg30R9SCof0JydiZFiA3dLSkRsbLF"); validProperties.put("elasticsearch_config_file", tempFile.getAbsolutePath()); validProperties.put("force_syslog_rdns", "false"); validProperties.put("syslog_listen_port", "514"); validProperties.put("syslog_protocol", "udp"); validProperties.put("mongodb_useauth", "true"); validProperties.put("mongodb_user", "user"); validProperties.put("mongodb_password", "pass"); validProperties.put("mongodb_database", "test"); validProperties.put("mongodb_host", "localhost"); validProperties.put("mongodb_port", "27017"); validProperties.put("use_gelf", "true"); validProperties.put("gelf_listen_port", "12201"); validProperties.put("root_password_sha1", "d033e22ae348aeb5660fc2140aec35850c4da997"); // sha1 of admin // Additional numerical properties validProperties.put("mongodb_max_connections", "100"); validProperties.put("mongodb_threads_allowed_to_block_multiplier", "50"); validProperties.put("amqp_port", "5672"); validProperties.put("forwarder_loggly_timeout", "3"); }
public void setUp() { validProperties = Maps.newHashMap(); try { tempFile = File.createTempFile("graylog", null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Required properties validProperties.put("password_secret", "ipNUnWxmBLCxTEzXcyamrdy0Q3G7HxdKsAvyg30R9SCof0JydiZFiA3dLSkRsbLF"); validProperties.put("elasticsearch_config_file", tempFile.getAbsolutePath()); validProperties.put("force_syslog_rdns", "false"); validProperties.put("syslog_listen_port", "514"); validProperties.put("syslog_protocol", "udp"); validProperties.put("mongodb_useauth", "true"); validProperties.put("mongodb_user", "user"); validProperties.put("mongodb_password", "pass"); validProperties.put("mongodb_database", "test"); validProperties.put("mongodb_host", "localhost"); validProperties.put("mongodb_port", "27017"); validProperties.put("use_gelf", "true"); validProperties.put("gelf_listen_port", "12201"); validProperties.put("root_password_sha2", "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"); // sha2 of admin // Additional numerical properties validProperties.put("mongodb_max_connections", "100"); validProperties.put("mongodb_threads_allowed_to_block_multiplier", "50"); validProperties.put("amqp_port", "5672"); validProperties.put("forwarder_loggly_timeout", "3"); }
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/map/MidblockMatchState.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/map/MidblockMatchState.java index 33ad3437c..54ce74a6a 100644 --- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/map/MidblockMatchState.java +++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/map/MidblockMatchState.java @@ -1,248 +1,247 @@ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.graph_builder.impl.map; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.graph.Vertex; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.linearref.LinearLocation; import com.vividsolutions.jts.linearref.LocationIndexedLine; import com.vividsolutions.jts.util.AssertionFailedException; public class MidblockMatchState extends MatchState { private static final double MAX_ERROR = 300; private LinearLocation edgeIndex; public LinearLocation routeIndex; Geometry routeGeometry; private Geometry edgeGeometry; private LocationIndexedLine indexedEdge; public MidblockMatchState(MatchState parent, Geometry routeGeometry, Edge edge, LinearLocation routeIndex, LinearLocation edgeIndex, double error, double distanceAlongRoute) { super(parent, edge, distanceAlongRoute); this.routeGeometry = routeGeometry; this.routeIndex = routeIndex; this.edgeIndex = edgeIndex; edgeGeometry = edge.getGeometry(); indexedEdge = new LocationIndexedLine(edgeGeometry); currentError = error; } @Override public List<MatchState> getNextStates() { ArrayList<MatchState> nextStates = new ArrayList<MatchState>(); if (routeIndex.getSegmentIndex() == routeGeometry.getNumPoints() - 1) { // this has either hit the end, or gone off the end. It's not real clear which. // for now, let's assume it means that the ending is somewhere along this edge, // so we return an end state Coordinate pt = routeIndex.getCoordinate(routeGeometry); double error = distance(pt, edgeIndex.getCoordinate(edgeGeometry)); nextStates.add(new EndMatchState(this, error, 0)); return nextStates; } LinearIterator it = new LinearIterator(routeGeometry, routeIndex); if (it.hasNext()) { it.next(); LinearLocation routeSuccessor = it.getLocation(); // now we want to see where this new point is in terms of the edge's geometry Coordinate newRouteCoord = routeSuccessor.getCoordinate(routeGeometry); LinearLocation newEdgeIndex = indexedEdge.project(newRouteCoord); Coordinate edgeCoord = newEdgeIndex.getCoordinate(edgeGeometry); if (newEdgeIndex.compareTo(edgeIndex) <= 0) { // we must make forward progress along the edge... or go to the next edge /* this should not require the try/catch, but there is a bug in JTS */ try { LinearLocation projected2 = indexedEdge.indexOfAfter(edgeCoord, edgeIndex); //another bug in JTS if (Double.isNaN(projected2.getSegmentFraction())) { // we are probably moving backwards return Collections.emptyList(); } else { newEdgeIndex = projected2; if (newEdgeIndex.equals(edgeIndex)) { return Collections.emptyList(); } } edgeCoord = newEdgeIndex.getCoordinate(edgeGeometry); } catch (AssertionFailedException e) { // we are not making progress, so just return an empty list return Collections.emptyList(); } } if (newEdgeIndex.getSegmentIndex() == edgeGeometry.getNumPoints() - 1) { - // but we might also choose to continue from the end of the edge and a point mid-way + // we might choose to continue from the end of the edge and a point mid-way // along this route segment // find nearest point that makes progress along the route Vertex toVertex = edge.getToVertex(); Coordinate endCoord = toVertex.getCoordinate(); LocationIndexedLine indexedRoute = new LocationIndexedLine(routeGeometry); // FIXME: it would be better to do this project/indexOfAfter in one step // as the two-step version could snap to a bad place and be unable to escape. LinearLocation routeProjectedEndIndex = indexedRoute.project(endCoord); Coordinate routeProjectedEndCoord = routeProjectedEndIndex .getCoordinate(routeGeometry); if (routeProjectedEndIndex.compareTo(routeIndex) <= 0) { try { routeProjectedEndIndex = indexedRoute.indexOfAfter(routeProjectedEndCoord, routeIndex); if (Double.isNaN(routeProjectedEndIndex.getSegmentFraction())) { // can't go forward routeProjectedEndIndex = routeIndex; // this is bad, but not terrible // since we are advancing along the edge } } catch (AssertionFailedException e) { routeProjectedEndIndex = routeIndex; } routeProjectedEndCoord = routeProjectedEndIndex.getCoordinate(routeGeometry); } double positionError = distance(routeProjectedEndCoord, endCoord); double travelAlongRoute = distanceAlongGeometry(routeGeometry, routeIndex, routeProjectedEndIndex); double travelAlongEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, newEdgeIndex); double travelError = Math.abs(travelAlongEdge - travelAlongRoute); double error = positionError + travelError; if (error > MAX_ERROR) { // we're not going to bother with states which are // totally wrong return nextStates; } for (Edge e : getOutgoingMatchableEdges(toVertex)) { double cost = error + NEW_SEGMENT_PENALTY; if (!carsCanTraverse(e)) { cost += NO_TRAVERSE_PENALTY; } MatchState nextState = new MidblockMatchState(this, routeGeometry, e, routeProjectedEndIndex, new LinearLocation(), cost, travelAlongRoute); - distanceAlongGeometry(routeGeometry, routeIndex, routeProjectedEndIndex); nextStates.add(nextState); } } else { double travelAlongEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, newEdgeIndex); double travelAlongRoute = distanceAlongGeometry(routeGeometry, routeIndex, routeSuccessor); double travelError = Math.abs(travelAlongRoute - travelAlongEdge); double positionError = distance(edgeCoord, newRouteCoord); double error = travelError + positionError; MatchState nextState = new MidblockMatchState(this, routeGeometry, edge, routeSuccessor, newEdgeIndex, error, travelAlongRoute); nextStates.add(nextState); // it's also possible that, although we have not yet reached the end of this edge, // we are going to turn, because the route turns earlier than the edge. In that // case, we jump to the corner, and our error is the distance from the route point // and the corner Vertex toVertex = edge.getToVertex(); double travelAlongOldEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, null); for (Edge e : getOutgoingMatchableEdges(toVertex)) { Geometry newEdgeGeometry = e.getGeometry(); LocationIndexedLine newIndexedEdge = new LocationIndexedLine(newEdgeGeometry); newEdgeIndex = newIndexedEdge.project(newRouteCoord); Coordinate newEdgeCoord = newEdgeIndex.getCoordinate(newEdgeGeometry); - positionError = newEdgeCoord.distance(newRouteCoord); + positionError = distance(newEdgeCoord, newRouteCoord); travelAlongEdge = travelAlongOldEdge + distanceAlongGeometry(newEdgeGeometry, new LinearLocation(), newEdgeIndex); travelError = Math.abs(travelAlongRoute - travelAlongEdge); error = travelError + positionError; if (error > MAX_ERROR) { // we're not going to bother with states which are // totally wrong return nextStates; } double cost = error + NEW_SEGMENT_PENALTY; if (!carsCanTraverse(e)) { cost += NO_TRAVERSE_PENALTY; } nextState = new MidblockMatchState(this, routeGeometry, e, routeSuccessor, new LinearLocation(), cost, travelAlongRoute); nextStates.add(nextState); } } return nextStates; } else { Coordinate routeCoord = routeIndex.getCoordinate(routeGeometry); LinearLocation projected = indexedEdge.project(routeCoord); double locationError = distance(projected.getCoordinate(edgeGeometry), routeCoord); MatchState end = new EndMatchState(this, locationError, 0); return Arrays.asList(end); } } public String toString() { return "MidblockMatchState(" + edge + ", " + edgeIndex.getSegmentIndex() + ", " + edgeIndex.getSegmentFraction() + ") - " + currentError; } public int hashCode() { return (edge.hashCode() * 1337 + hashCode(edgeIndex)) * 1337 + hashCode(routeIndex); } private int hashCode(LinearLocation location) { return location.getComponentIndex() * 1000000 + location.getSegmentIndex() * 37 + new Double(location.getSegmentFraction()).hashCode(); } public boolean equals(Object o) { if (!(o instanceof MidblockMatchState)) { return false; } MidblockMatchState other = (MidblockMatchState) o; return other.edge == edge && other.edgeIndex.compareTo(edgeIndex) == 0 && other.routeIndex.compareTo(routeIndex) == 0; } }
false
true
public List<MatchState> getNextStates() { ArrayList<MatchState> nextStates = new ArrayList<MatchState>(); if (routeIndex.getSegmentIndex() == routeGeometry.getNumPoints() - 1) { // this has either hit the end, or gone off the end. It's not real clear which. // for now, let's assume it means that the ending is somewhere along this edge, // so we return an end state Coordinate pt = routeIndex.getCoordinate(routeGeometry); double error = distance(pt, edgeIndex.getCoordinate(edgeGeometry)); nextStates.add(new EndMatchState(this, error, 0)); return nextStates; } LinearIterator it = new LinearIterator(routeGeometry, routeIndex); if (it.hasNext()) { it.next(); LinearLocation routeSuccessor = it.getLocation(); // now we want to see where this new point is in terms of the edge's geometry Coordinate newRouteCoord = routeSuccessor.getCoordinate(routeGeometry); LinearLocation newEdgeIndex = indexedEdge.project(newRouteCoord); Coordinate edgeCoord = newEdgeIndex.getCoordinate(edgeGeometry); if (newEdgeIndex.compareTo(edgeIndex) <= 0) { // we must make forward progress along the edge... or go to the next edge /* this should not require the try/catch, but there is a bug in JTS */ try { LinearLocation projected2 = indexedEdge.indexOfAfter(edgeCoord, edgeIndex); //another bug in JTS if (Double.isNaN(projected2.getSegmentFraction())) { // we are probably moving backwards return Collections.emptyList(); } else { newEdgeIndex = projected2; if (newEdgeIndex.equals(edgeIndex)) { return Collections.emptyList(); } } edgeCoord = newEdgeIndex.getCoordinate(edgeGeometry); } catch (AssertionFailedException e) { // we are not making progress, so just return an empty list return Collections.emptyList(); } } if (newEdgeIndex.getSegmentIndex() == edgeGeometry.getNumPoints() - 1) { // but we might also choose to continue from the end of the edge and a point mid-way // along this route segment // find nearest point that makes progress along the route Vertex toVertex = edge.getToVertex(); Coordinate endCoord = toVertex.getCoordinate(); LocationIndexedLine indexedRoute = new LocationIndexedLine(routeGeometry); // FIXME: it would be better to do this project/indexOfAfter in one step // as the two-step version could snap to a bad place and be unable to escape. LinearLocation routeProjectedEndIndex = indexedRoute.project(endCoord); Coordinate routeProjectedEndCoord = routeProjectedEndIndex .getCoordinate(routeGeometry); if (routeProjectedEndIndex.compareTo(routeIndex) <= 0) { try { routeProjectedEndIndex = indexedRoute.indexOfAfter(routeProjectedEndCoord, routeIndex); if (Double.isNaN(routeProjectedEndIndex.getSegmentFraction())) { // can't go forward routeProjectedEndIndex = routeIndex; // this is bad, but not terrible // since we are advancing along the edge } } catch (AssertionFailedException e) { routeProjectedEndIndex = routeIndex; } routeProjectedEndCoord = routeProjectedEndIndex.getCoordinate(routeGeometry); } double positionError = distance(routeProjectedEndCoord, endCoord); double travelAlongRoute = distanceAlongGeometry(routeGeometry, routeIndex, routeProjectedEndIndex); double travelAlongEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, newEdgeIndex); double travelError = Math.abs(travelAlongEdge - travelAlongRoute); double error = positionError + travelError; if (error > MAX_ERROR) { // we're not going to bother with states which are // totally wrong return nextStates; } for (Edge e : getOutgoingMatchableEdges(toVertex)) { double cost = error + NEW_SEGMENT_PENALTY; if (!carsCanTraverse(e)) { cost += NO_TRAVERSE_PENALTY; } MatchState nextState = new MidblockMatchState(this, routeGeometry, e, routeProjectedEndIndex, new LinearLocation(), cost, travelAlongRoute); distanceAlongGeometry(routeGeometry, routeIndex, routeProjectedEndIndex); nextStates.add(nextState); } } else { double travelAlongEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, newEdgeIndex); double travelAlongRoute = distanceAlongGeometry(routeGeometry, routeIndex, routeSuccessor); double travelError = Math.abs(travelAlongRoute - travelAlongEdge); double positionError = distance(edgeCoord, newRouteCoord); double error = travelError + positionError; MatchState nextState = new MidblockMatchState(this, routeGeometry, edge, routeSuccessor, newEdgeIndex, error, travelAlongRoute); nextStates.add(nextState); // it's also possible that, although we have not yet reached the end of this edge, // we are going to turn, because the route turns earlier than the edge. In that // case, we jump to the corner, and our error is the distance from the route point // and the corner Vertex toVertex = edge.getToVertex(); double travelAlongOldEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, null); for (Edge e : getOutgoingMatchableEdges(toVertex)) { Geometry newEdgeGeometry = e.getGeometry(); LocationIndexedLine newIndexedEdge = new LocationIndexedLine(newEdgeGeometry); newEdgeIndex = newIndexedEdge.project(newRouteCoord); Coordinate newEdgeCoord = newEdgeIndex.getCoordinate(newEdgeGeometry); positionError = newEdgeCoord.distance(newRouteCoord); travelAlongEdge = travelAlongOldEdge + distanceAlongGeometry(newEdgeGeometry, new LinearLocation(), newEdgeIndex); travelError = Math.abs(travelAlongRoute - travelAlongEdge); error = travelError + positionError; if (error > MAX_ERROR) { // we're not going to bother with states which are // totally wrong return nextStates; } double cost = error + NEW_SEGMENT_PENALTY; if (!carsCanTraverse(e)) { cost += NO_TRAVERSE_PENALTY; } nextState = new MidblockMatchState(this, routeGeometry, e, routeSuccessor, new LinearLocation(), cost, travelAlongRoute); nextStates.add(nextState); } } return nextStates; } else { Coordinate routeCoord = routeIndex.getCoordinate(routeGeometry); LinearLocation projected = indexedEdge.project(routeCoord); double locationError = distance(projected.getCoordinate(edgeGeometry), routeCoord); MatchState end = new EndMatchState(this, locationError, 0); return Arrays.asList(end); } }
public List<MatchState> getNextStates() { ArrayList<MatchState> nextStates = new ArrayList<MatchState>(); if (routeIndex.getSegmentIndex() == routeGeometry.getNumPoints() - 1) { // this has either hit the end, or gone off the end. It's not real clear which. // for now, let's assume it means that the ending is somewhere along this edge, // so we return an end state Coordinate pt = routeIndex.getCoordinate(routeGeometry); double error = distance(pt, edgeIndex.getCoordinate(edgeGeometry)); nextStates.add(new EndMatchState(this, error, 0)); return nextStates; } LinearIterator it = new LinearIterator(routeGeometry, routeIndex); if (it.hasNext()) { it.next(); LinearLocation routeSuccessor = it.getLocation(); // now we want to see where this new point is in terms of the edge's geometry Coordinate newRouteCoord = routeSuccessor.getCoordinate(routeGeometry); LinearLocation newEdgeIndex = indexedEdge.project(newRouteCoord); Coordinate edgeCoord = newEdgeIndex.getCoordinate(edgeGeometry); if (newEdgeIndex.compareTo(edgeIndex) <= 0) { // we must make forward progress along the edge... or go to the next edge /* this should not require the try/catch, but there is a bug in JTS */ try { LinearLocation projected2 = indexedEdge.indexOfAfter(edgeCoord, edgeIndex); //another bug in JTS if (Double.isNaN(projected2.getSegmentFraction())) { // we are probably moving backwards return Collections.emptyList(); } else { newEdgeIndex = projected2; if (newEdgeIndex.equals(edgeIndex)) { return Collections.emptyList(); } } edgeCoord = newEdgeIndex.getCoordinate(edgeGeometry); } catch (AssertionFailedException e) { // we are not making progress, so just return an empty list return Collections.emptyList(); } } if (newEdgeIndex.getSegmentIndex() == edgeGeometry.getNumPoints() - 1) { // we might choose to continue from the end of the edge and a point mid-way // along this route segment // find nearest point that makes progress along the route Vertex toVertex = edge.getToVertex(); Coordinate endCoord = toVertex.getCoordinate(); LocationIndexedLine indexedRoute = new LocationIndexedLine(routeGeometry); // FIXME: it would be better to do this project/indexOfAfter in one step // as the two-step version could snap to a bad place and be unable to escape. LinearLocation routeProjectedEndIndex = indexedRoute.project(endCoord); Coordinate routeProjectedEndCoord = routeProjectedEndIndex .getCoordinate(routeGeometry); if (routeProjectedEndIndex.compareTo(routeIndex) <= 0) { try { routeProjectedEndIndex = indexedRoute.indexOfAfter(routeProjectedEndCoord, routeIndex); if (Double.isNaN(routeProjectedEndIndex.getSegmentFraction())) { // can't go forward routeProjectedEndIndex = routeIndex; // this is bad, but not terrible // since we are advancing along the edge } } catch (AssertionFailedException e) { routeProjectedEndIndex = routeIndex; } routeProjectedEndCoord = routeProjectedEndIndex.getCoordinate(routeGeometry); } double positionError = distance(routeProjectedEndCoord, endCoord); double travelAlongRoute = distanceAlongGeometry(routeGeometry, routeIndex, routeProjectedEndIndex); double travelAlongEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, newEdgeIndex); double travelError = Math.abs(travelAlongEdge - travelAlongRoute); double error = positionError + travelError; if (error > MAX_ERROR) { // we're not going to bother with states which are // totally wrong return nextStates; } for (Edge e : getOutgoingMatchableEdges(toVertex)) { double cost = error + NEW_SEGMENT_PENALTY; if (!carsCanTraverse(e)) { cost += NO_TRAVERSE_PENALTY; } MatchState nextState = new MidblockMatchState(this, routeGeometry, e, routeProjectedEndIndex, new LinearLocation(), cost, travelAlongRoute); nextStates.add(nextState); } } else { double travelAlongEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, newEdgeIndex); double travelAlongRoute = distanceAlongGeometry(routeGeometry, routeIndex, routeSuccessor); double travelError = Math.abs(travelAlongRoute - travelAlongEdge); double positionError = distance(edgeCoord, newRouteCoord); double error = travelError + positionError; MatchState nextState = new MidblockMatchState(this, routeGeometry, edge, routeSuccessor, newEdgeIndex, error, travelAlongRoute); nextStates.add(nextState); // it's also possible that, although we have not yet reached the end of this edge, // we are going to turn, because the route turns earlier than the edge. In that // case, we jump to the corner, and our error is the distance from the route point // and the corner Vertex toVertex = edge.getToVertex(); double travelAlongOldEdge = distanceAlongGeometry(edgeGeometry, edgeIndex, null); for (Edge e : getOutgoingMatchableEdges(toVertex)) { Geometry newEdgeGeometry = e.getGeometry(); LocationIndexedLine newIndexedEdge = new LocationIndexedLine(newEdgeGeometry); newEdgeIndex = newIndexedEdge.project(newRouteCoord); Coordinate newEdgeCoord = newEdgeIndex.getCoordinate(newEdgeGeometry); positionError = distance(newEdgeCoord, newRouteCoord); travelAlongEdge = travelAlongOldEdge + distanceAlongGeometry(newEdgeGeometry, new LinearLocation(), newEdgeIndex); travelError = Math.abs(travelAlongRoute - travelAlongEdge); error = travelError + positionError; if (error > MAX_ERROR) { // we're not going to bother with states which are // totally wrong return nextStates; } double cost = error + NEW_SEGMENT_PENALTY; if (!carsCanTraverse(e)) { cost += NO_TRAVERSE_PENALTY; } nextState = new MidblockMatchState(this, routeGeometry, e, routeSuccessor, new LinearLocation(), cost, travelAlongRoute); nextStates.add(nextState); } } return nextStates; } else { Coordinate routeCoord = routeIndex.getCoordinate(routeGeometry); LinearLocation projected = indexedEdge.project(routeCoord); double locationError = distance(projected.getCoordinate(edgeGeometry), routeCoord); MatchState end = new EndMatchState(this, locationError, 0); return Arrays.asList(end); } }
diff --git a/melaza-core/src/main/java/com/mentorgen/tools/profile/instrument/Transformer.java b/melaza-core/src/main/java/com/mentorgen/tools/profile/instrument/Transformer.java index 051760b..7cc6905 100755 --- a/melaza-core/src/main/java/com/mentorgen/tools/profile/instrument/Transformer.java +++ b/melaza-core/src/main/java/com/mentorgen/tools/profile/instrument/Transformer.java @@ -1,155 +1,155 @@ /* Copyright (c) 2005, MentorGen, LLC 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 MentorGen LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mentorgen.tools.profile.instrument; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mentorgen.tools.profile.Controller; /** * This class determines if a given class should be instrumented * with profiling code or not. The property <code>debug</code>, when * set to <code>on</code>, will show you which classes are being instrumented * and what ones are not. * * @author Andrew Wilcox * @author Patrick Mahoney * @see java.lang.instrument.ClassFileTransformer */ public class Transformer implements ClassFileTransformer { private static final Logger logger = LoggerFactory.getLogger(Transformer.class); private final String[] internalPackages = new String[] { "com/mentorgen/tools/profile", "net/sourceforge/jiprof", "org/polycrystal/melaza", "melaza/deps" }; private final String[] javaPackages = new String[] { "java/", "sun/" }; private boolean matchesPrefix(String str, String[] prefixes) { for (String prefix : prefixes) { if (str.startsWith(prefix)) { return true; } } return false; } private boolean isInternalClass(String className) { return matchesPrefix(className, internalPackages); } private boolean isJavaClass(String className) { return matchesPrefix(className, javaPackages); } public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // can't profile yourself // if (isInternalClass(className)) { logger.debug("skip {} [{}] (internal)", className, loader); return null; } if (isJavaClass(className)) { // FIXME: make some sort of canned exclude lists that might // be opted out of logger.debug("skip {} [{}] (java)", className, loader); return null; } // include // if (Controller._includeList.length > 0) { boolean toInclude = false; for (String include: Controller._includeList) { if (className.startsWith(include)) { toInclude = true; break; } } if (!toInclude) { logger.debug("skip {} [{}] (class not in include list)", className, loader); return null; } } if (!Controller._filter.accept(loader)){ logger.debug("skip {} [{}] (loader not accepted by filter)", className, loader); return null; } // exclude // for (String exclude: Controller._excludeList) { if (className.startsWith(exclude)) { logger.debug("skip {} [{}] (class in exclude list)", className, loader); return null; } } try { logger.debug("INST {} [{}]", className, loader); Controller._instrumentCount++; ClassReader reader = new ClassReader(classfileBuffer); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor adapter = new PerfClassAdapter(writer, className); - reader.accept(adapter, ClassReader.SKIP_DEBUG); + reader.accept(adapter, 0); return writer.toByteArray(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } } }
true
true
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // can't profile yourself // if (isInternalClass(className)) { logger.debug("skip {} [{}] (internal)", className, loader); return null; } if (isJavaClass(className)) { // FIXME: make some sort of canned exclude lists that might // be opted out of logger.debug("skip {} [{}] (java)", className, loader); return null; } // include // if (Controller._includeList.length > 0) { boolean toInclude = false; for (String include: Controller._includeList) { if (className.startsWith(include)) { toInclude = true; break; } } if (!toInclude) { logger.debug("skip {} [{}] (class not in include list)", className, loader); return null; } } if (!Controller._filter.accept(loader)){ logger.debug("skip {} [{}] (loader not accepted by filter)", className, loader); return null; } // exclude // for (String exclude: Controller._excludeList) { if (className.startsWith(exclude)) { logger.debug("skip {} [{}] (class in exclude list)", className, loader); return null; } } try { logger.debug("INST {} [{}]", className, loader); Controller._instrumentCount++; ClassReader reader = new ClassReader(classfileBuffer); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor adapter = new PerfClassAdapter(writer, className); reader.accept(adapter, ClassReader.SKIP_DEBUG); return writer.toByteArray(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } }
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // can't profile yourself // if (isInternalClass(className)) { logger.debug("skip {} [{}] (internal)", className, loader); return null; } if (isJavaClass(className)) { // FIXME: make some sort of canned exclude lists that might // be opted out of logger.debug("skip {} [{}] (java)", className, loader); return null; } // include // if (Controller._includeList.length > 0) { boolean toInclude = false; for (String include: Controller._includeList) { if (className.startsWith(include)) { toInclude = true; break; } } if (!toInclude) { logger.debug("skip {} [{}] (class not in include list)", className, loader); return null; } } if (!Controller._filter.accept(loader)){ logger.debug("skip {} [{}] (loader not accepted by filter)", className, loader); return null; } // exclude // for (String exclude: Controller._excludeList) { if (className.startsWith(exclude)) { logger.debug("skip {} [{}] (class in exclude list)", className, loader); return null; } } try { logger.debug("INST {} [{}]", className, loader); Controller._instrumentCount++; ClassReader reader = new ClassReader(classfileBuffer); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor adapter = new PerfClassAdapter(writer, className); reader.accept(adapter, 0); return writer.toByteArray(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } }
diff --git a/com.mobilesorcery.sdk.builder.java/src/com/mobilesorcery/sdk/builder/java/JavaPackager.java b/com.mobilesorcery.sdk.builder.java/src/com/mobilesorcery/sdk/builder/java/JavaPackager.java index aecf69bf..de06bbaf 100644 --- a/com.mobilesorcery.sdk.builder.java/src/com/mobilesorcery/sdk/builder/java/JavaPackager.java +++ b/com.mobilesorcery.sdk.builder.java/src/com/mobilesorcery/sdk/builder/java/JavaPackager.java @@ -1,259 +1,259 @@ /* Copyright (C) 2009 Mobile Sorcery AB This program is free software; you can redistribute it and/or modify it under the terms of the Eclipse Public License v1.0. 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 Eclipse Public License v1.0 for more details. You should have received a copy of the Eclipse Public License v1.0 along with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html */ package com.mobilesorcery.sdk.builder.java; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.Map.Entry; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import com.mobilesorcery.sdk.core.AbstractPackager; import com.mobilesorcery.sdk.core.DefaultPackager; import com.mobilesorcery.sdk.core.IBuildResult; import com.mobilesorcery.sdk.core.IBuildVariant; import com.mobilesorcery.sdk.core.MoSyncProject; import com.mobilesorcery.sdk.core.MoSyncTool; import com.mobilesorcery.sdk.core.Util; import com.mobilesorcery.sdk.core.Version; import com.mobilesorcery.sdk.core.security.IApplicationPermissions; import com.mobilesorcery.sdk.internal.builder.MoSyncIconBuilderVisitor; import com.mobilesorcery.sdk.profiles.IProfile; public class JavaPackager extends AbstractPackager { private String m_zipLoc; private String m_iconInjectorLoc; public JavaPackager() { MoSyncTool tool = MoSyncTool.getDefault(); m_zipLoc = tool.getBinary("zip").toOSString(); m_iconInjectorLoc = tool.getBinary("icon-injector").toOSString(); } public void createPackage(MoSyncProject project, IBuildVariant variant, IBuildResult buildResult) throws CoreException { DefaultPackager internal = new DefaultPackager(project, variant); IProfile targetProfile = variant.getProfile(); File runtimeDir = new File(internal.resolve("%runtime-dir%")); File compileOut = new File(internal.resolve("%compile-output-dir%")); internal.setParameters(getParameters()); internal.setParameter("D", shouldUseDebugRuntimes() ? "D" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { File packageOutputDir = internal.resolveFile("%package-output-dir%"); //$NON-NLS-1$ packageOutputDir.mkdirs(); Version appVersion = new Version(internal.getParameters().get(DefaultPackager.APP_VERSION)); IApplicationPermissions permissions = project.getPermissions(); File projectJar = new File(internal.resolve("%package-output-dir%/%app-name%.jar")); //$NON-NLS-1$ File projectJad = new File(internal.resolve("%package-output-dir%/%app-name%.jad")); //$NON-NLS-1$ projectJar.delete(); projectJad.delete(); String appVendorName = internal.getParameters().get(DefaultPackager.APP_VENDOR_NAME); String appName = internal.getParameters().get(DefaultPackager.APP_NAME); - File manifest = new File(internal.resolve("%compile-output-dir%/META-INF/manifest.mf")); //$NON-NLS-1$ + File manifest = new File("%compile-output-dir%/META-INF/MANIFEST.MF"); //$NON-NLS-1$ createManifest(variant, appName, appVendorName, permissions, appVersion, manifest); // Need to set execution dir, o/w zip will not understand what we // really want. internal.getExecutor().setExecutionDirectory(manifest.getParentFile().getParent()); { String runtime = internal.resolve("MoSyncRuntime%D%.jar"); Util.copyFile(new NullProgressMonitor(), new File(runtimeDir, runtime), projectJar); } Util.copyFile(new NullProgressMonitor(), new File(runtimeDir, "config.h"), new File(packageOutputDir, "config.h")); internal.runCommandLine(m_zipLoc, "-j", "-9", projectJar.getAbsolutePath(), new File(compileOut, "program").getAbsolutePath()); internal.runCommandLine(m_zipLoc, "-r", "-9", projectJar.getAbsolutePath(), "META-INF"); File resources = new File(compileOut, "resources"); //$NON-NLS-1$ if (resources.exists()) { internal.runCommandLine(m_zipLoc, "-j", "-9", projectJar.getAbsolutePath(), resources.getAbsolutePath()); } createJAD(variant, appName, appVendorName, permissions, appVersion, projectJad, projectJar); MoSyncIconBuilderVisitor visitor = new MoSyncIconBuilderVisitor(); visitor.setProject(project.getWrappedProject()); IResource[] iconFiles = visitor.getIconFiles(); if (iconFiles.length > 0) { Object xObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_X"); //$NON-NLS-1$ Object yObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_Y"); //$NON-NLS-1$ if (xObj != null && yObj != null) { String sizeStr = ((Long) xObj) + "x" + ((Long) yObj); //$NON-NLS-1$ internal.runCommandLine(m_iconInjectorLoc, "-src", iconFiles[0].getLocation().toOSString(), "-size", sizeStr, "-platform", "j2me", "-dst", projectJar.getAbsolutePath()); } } signPackage(internal, project, projectJad, projectJar); buildResult.setBuildResult(projectJar); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, "com.mobilesorcery.sdk.builder.java", Messages.JavaPackager_PackageError, e)); //$NON-NLS-1$ } } private void signPackage(DefaultPackager internal, MoSyncProject project, File projectJad, File projectJar) throws IOException { List<KeystoreCertificateInfo> keystoreCertInfos = KeystoreCertificateInfo .parseList(project.getProperty(PropertyInitializer.JAVAME_KEYSTORE_CERT_INFOS)); // sign jar file using jarSigner File mosyncBinDir = internal.resolveFile("%mosync-bin%"); // File unsignedProjectJar = new File(projectJar.getParentFile(), // Util.getNameWithoutExtension(projectJar) + "_unsigned.jar"); for (KeystoreCertificateInfo keystoreCertInfo : keystoreCertInfos) { String keystore = keystoreCertInfo.getKeystoreLocation(); String alias = keystoreCertInfo.getAlias(); String storepass = keystoreCertInfo.getKeystorePassword(); if (Util.isEmpty(storepass)) { throw new IllegalArgumentException("Keystore password missing"); } String keypass = keystoreCertInfo.getKeyPassword(); if (Util.isEmpty(keypass)) { throw new IllegalArgumentException("Keystore password missing"); } // Util.copyFile(new NullProgressMonitor(), projectJar, // unsignedProjectJar); /* * String[] jarSignerCommandLine = new String[] { "java", "-jar", * new File( mosyncBinDir, "android/tools-stripped.jar" * ).getAbsolutePath( ), "-keystore", keystore, "-storepass", * storepass, "-keypass", keypass, "-signedjar", * projectJar.getAbsolutePath( ), * unsignedProjectJar.getAbsolutePath( ), alias }; * * internal.runCommandLine(jarSignerCommandLine, * "*** COMMAND LINE WITHHELD, CONTAINS PASSWORDS ***"); */ String[] addCertCommandLine = new String[] { "java", "-classpath", new File(mosyncBinDir, "javame/JadTool.jar").getAbsolutePath() + File.pathSeparatorChar + new File(mosyncBinDir, "javame/core__environment.jar").getAbsolutePath() + File.pathSeparatorChar + new File(mosyncBinDir, "javame/core__properties.jar").getAbsolutePath(), "com.sun.midp.jadtool.JadTool", "-addcert", "-keystore", keystore, "-alias", alias, "-inputjad", projectJad.getAbsolutePath(), "-outputjad", projectJad.getAbsolutePath() }; assertOk(internal.runCommandLine(addCertCommandLine, "*** COMMAND LINE WITHHELD, CONTAINS PASSWORDS ***")); String[] addJarSigCommandLine = new String[] { "java", "-classpath", new File(mosyncBinDir, "javame/JadTool.jar").getAbsolutePath() + File.pathSeparatorChar + new File(mosyncBinDir, "javame/core__environment.jar").getAbsolutePath() + File.pathSeparatorChar + new File(mosyncBinDir, "javame/core__properties.jar").getAbsolutePath(), "com.sun.midp.jadtool.JadTool", "-addjarsig", "-keystore", keystore, "-keypass", keypass, "-alias", alias, "-jarfile", projectJar.getAbsolutePath(), "-inputjad", projectJad.getAbsolutePath(), "-outputjad", projectJad.getAbsolutePath() }; assertOk(internal.runCommandLine(addJarSigCommandLine, "*** COMMAND LINE WITHHELD, CONTAINS PASSWORDS ***")); } } private void assertOk(int errorCode) { if (errorCode != 0) { throw new IllegalArgumentException("Tool execution failed"); } } private void createManifest(IBuildVariant variant, String appName, String vendorName, IApplicationPermissions permissions, Version version, File manifestFile) throws IOException { manifestFile.getParentFile().mkdirs(); Manifest manifest = getManifest(variant, null, appName, vendorName, permissions, version, false); FileOutputStream manifestOutput = new FileOutputStream(manifestFile); try { manifest.write(manifestOutput); } finally { Util.safeClose(manifestOutput); } } private void createJAD(IBuildVariant variant, String projectName, String vendorName, IApplicationPermissions permissions, Version version, File jadFile, File jar) throws IOException { Manifest jad = getManifest(variant, jar, projectName, vendorName, permissions, version, true); Set<Entry<Object, Object>> entries = jad.getMainAttributes().entrySet(); FileWriter jadOutput = new FileWriter(jadFile); try { for (Entry entry : entries) { // JAD format: key COLON SPACE value NEWLINE String key = entry.getKey().toString(); String value = entry.getValue().toString(); jadOutput.write(key + ": " + value + "\n"); } } finally { Util.safeClose(jadOutput); } } private Manifest getManifest(IBuildVariant variant, File jar, String appName, String vendorName, IApplicationPermissions permissions, Version version, boolean isJad) throws IOException { IProfile profile = variant.getProfile(); boolean isCLDC_10 = profile != null && Boolean.TRUE.equals(profile.getProperties().get("MA_PROF_SUPPORT_CLDC_10")); Manifest result = new Manifest(); Attributes mainAttr = result.getMainAttributes(); if (!isJad) { mainAttr.putValue("Manifest-Version", "1.0"); } mainAttr.putValue("MIDlet-Vendor", vendorName); mainAttr.putValue("MIDlet-Name", appName); mainAttr.putValue("MIDlet-1", appName + ", " + appName + ".png" + ", MAMidlet"); String[] midletPermissions = getMIDletPermissions(permissions, false); String[] midletOptPermissions = getMIDletPermissions(permissions, true); if (midletPermissions.length > 0) { mainAttr.putValue("MIDlet-Permissions", Util.join(midletPermissions, ", ")); } if (midletOptPermissions.length > 0) { mainAttr.putValue("MIDlet-Permissions-Opt", Util.join(midletOptPermissions, ", ")); } mainAttr.putValue("MIDlet-Version", version.asCanonicalString(Version.MICRO)); mainAttr.putValue("MicroEdition-Configuration", isCLDC_10 ? "CLDC-1.0" : "CLDC-1.1"); mainAttr.putValue("MicroEdition-Profile", "MIDP-2.0"); if (isJad) { long jarSize = jar.length(); String jarName = jar.getName(); mainAttr.putValue("MIDlet-Jar-Size", Long.toString(jarSize)); mainAttr.putValue("MIDlet-Jar-URL", jarName); } return result; } private String[] getMIDletPermissions(IApplicationPermissions permissions, boolean isOptional) { ArrayList<String> result = new ArrayList<String>(); TreeSet<String> reqPermissions = new TreeSet<String>(); TreeSet<String> optPermissions = new TreeSet<String>(); MIDletPermissions.toMIDletPermissions(permissions, reqPermissions, optPermissions); result.addAll(isOptional ? optPermissions : reqPermissions); return result.toArray(new String[result.size()]); } }
true
true
public void createPackage(MoSyncProject project, IBuildVariant variant, IBuildResult buildResult) throws CoreException { DefaultPackager internal = new DefaultPackager(project, variant); IProfile targetProfile = variant.getProfile(); File runtimeDir = new File(internal.resolve("%runtime-dir%")); File compileOut = new File(internal.resolve("%compile-output-dir%")); internal.setParameters(getParameters()); internal.setParameter("D", shouldUseDebugRuntimes() ? "D" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { File packageOutputDir = internal.resolveFile("%package-output-dir%"); //$NON-NLS-1$ packageOutputDir.mkdirs(); Version appVersion = new Version(internal.getParameters().get(DefaultPackager.APP_VERSION)); IApplicationPermissions permissions = project.getPermissions(); File projectJar = new File(internal.resolve("%package-output-dir%/%app-name%.jar")); //$NON-NLS-1$ File projectJad = new File(internal.resolve("%package-output-dir%/%app-name%.jad")); //$NON-NLS-1$ projectJar.delete(); projectJad.delete(); String appVendorName = internal.getParameters().get(DefaultPackager.APP_VENDOR_NAME); String appName = internal.getParameters().get(DefaultPackager.APP_NAME); File manifest = new File(internal.resolve("%compile-output-dir%/META-INF/manifest.mf")); //$NON-NLS-1$ createManifest(variant, appName, appVendorName, permissions, appVersion, manifest); // Need to set execution dir, o/w zip will not understand what we // really want. internal.getExecutor().setExecutionDirectory(manifest.getParentFile().getParent()); { String runtime = internal.resolve("MoSyncRuntime%D%.jar"); Util.copyFile(new NullProgressMonitor(), new File(runtimeDir, runtime), projectJar); } Util.copyFile(new NullProgressMonitor(), new File(runtimeDir, "config.h"), new File(packageOutputDir, "config.h")); internal.runCommandLine(m_zipLoc, "-j", "-9", projectJar.getAbsolutePath(), new File(compileOut, "program").getAbsolutePath()); internal.runCommandLine(m_zipLoc, "-r", "-9", projectJar.getAbsolutePath(), "META-INF"); File resources = new File(compileOut, "resources"); //$NON-NLS-1$ if (resources.exists()) { internal.runCommandLine(m_zipLoc, "-j", "-9", projectJar.getAbsolutePath(), resources.getAbsolutePath()); } createJAD(variant, appName, appVendorName, permissions, appVersion, projectJad, projectJar); MoSyncIconBuilderVisitor visitor = new MoSyncIconBuilderVisitor(); visitor.setProject(project.getWrappedProject()); IResource[] iconFiles = visitor.getIconFiles(); if (iconFiles.length > 0) { Object xObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_X"); //$NON-NLS-1$ Object yObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_Y"); //$NON-NLS-1$ if (xObj != null && yObj != null) { String sizeStr = ((Long) xObj) + "x" + ((Long) yObj); //$NON-NLS-1$ internal.runCommandLine(m_iconInjectorLoc, "-src", iconFiles[0].getLocation().toOSString(), "-size", sizeStr, "-platform", "j2me", "-dst", projectJar.getAbsolutePath()); } } signPackage(internal, project, projectJad, projectJar); buildResult.setBuildResult(projectJar); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, "com.mobilesorcery.sdk.builder.java", Messages.JavaPackager_PackageError, e)); //$NON-NLS-1$ } }
public void createPackage(MoSyncProject project, IBuildVariant variant, IBuildResult buildResult) throws CoreException { DefaultPackager internal = new DefaultPackager(project, variant); IProfile targetProfile = variant.getProfile(); File runtimeDir = new File(internal.resolve("%runtime-dir%")); File compileOut = new File(internal.resolve("%compile-output-dir%")); internal.setParameters(getParameters()); internal.setParameter("D", shouldUseDebugRuntimes() ? "D" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { File packageOutputDir = internal.resolveFile("%package-output-dir%"); //$NON-NLS-1$ packageOutputDir.mkdirs(); Version appVersion = new Version(internal.getParameters().get(DefaultPackager.APP_VERSION)); IApplicationPermissions permissions = project.getPermissions(); File projectJar = new File(internal.resolve("%package-output-dir%/%app-name%.jar")); //$NON-NLS-1$ File projectJad = new File(internal.resolve("%package-output-dir%/%app-name%.jad")); //$NON-NLS-1$ projectJar.delete(); projectJad.delete(); String appVendorName = internal.getParameters().get(DefaultPackager.APP_VENDOR_NAME); String appName = internal.getParameters().get(DefaultPackager.APP_NAME); File manifest = new File("%compile-output-dir%/META-INF/MANIFEST.MF"); //$NON-NLS-1$ createManifest(variant, appName, appVendorName, permissions, appVersion, manifest); // Need to set execution dir, o/w zip will not understand what we // really want. internal.getExecutor().setExecutionDirectory(manifest.getParentFile().getParent()); { String runtime = internal.resolve("MoSyncRuntime%D%.jar"); Util.copyFile(new NullProgressMonitor(), new File(runtimeDir, runtime), projectJar); } Util.copyFile(new NullProgressMonitor(), new File(runtimeDir, "config.h"), new File(packageOutputDir, "config.h")); internal.runCommandLine(m_zipLoc, "-j", "-9", projectJar.getAbsolutePath(), new File(compileOut, "program").getAbsolutePath()); internal.runCommandLine(m_zipLoc, "-r", "-9", projectJar.getAbsolutePath(), "META-INF"); File resources = new File(compileOut, "resources"); //$NON-NLS-1$ if (resources.exists()) { internal.runCommandLine(m_zipLoc, "-j", "-9", projectJar.getAbsolutePath(), resources.getAbsolutePath()); } createJAD(variant, appName, appVendorName, permissions, appVersion, projectJad, projectJar); MoSyncIconBuilderVisitor visitor = new MoSyncIconBuilderVisitor(); visitor.setProject(project.getWrappedProject()); IResource[] iconFiles = visitor.getIconFiles(); if (iconFiles.length > 0) { Object xObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_X"); //$NON-NLS-1$ Object yObj = targetProfile.getProperties().get("MA_PROF_CONST_ICONSIZE_Y"); //$NON-NLS-1$ if (xObj != null && yObj != null) { String sizeStr = ((Long) xObj) + "x" + ((Long) yObj); //$NON-NLS-1$ internal.runCommandLine(m_iconInjectorLoc, "-src", iconFiles[0].getLocation().toOSString(), "-size", sizeStr, "-platform", "j2me", "-dst", projectJar.getAbsolutePath()); } } signPackage(internal, project, projectJad, projectJar); buildResult.setBuildResult(projectJar); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, "com.mobilesorcery.sdk.builder.java", Messages.JavaPackager_PackageError, e)); //$NON-NLS-1$ } }
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/DexMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/DexMojo.java index 365b9aab..8fd966ab 100644 --- a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/DexMojo.java +++ b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/DexMojo.java @@ -1,142 +1,142 @@ /* * Copyright (C) 2009 Jayway AB * Copyright (C) 2007-2008 JVending Masa * * 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.jayway.maven.plugins.android.phase04processclasses; import com.jayway.maven.plugins.android.AbstractAndroidMojo; import com.jayway.maven.plugins.android.CommandExecutor; import com.jayway.maven.plugins.android.ExecutionException; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.util.IOUtil; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.InputStream; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Converts compiled Java classes to the Android dex format. * @goal dex * @phase process-classes * @author [email protected] */ public class DexMojo extends AbstractAndroidMojo { /** * Extra JVM Arguments * * @parameter * @optional */ private String[] jvmArguments; public void execute() throws MojoExecutionException, MojoFailureException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); File outputFile = new File(project.getBuild().getDirectory() + File.separator + "classes.dex"); File inputFile = new File(project.getBuild().getDirectory() + File.separator + project.getBuild().getFinalName() + ".jar"); - //Unpackage all dependent and main classes + // Unpack all dependent and main classes File outputDirectory = new File(project.getBuild().getDirectory(), "android-classes"); for (Artifact artifact : (List<Artifact>) project.getCompileArtifacts()) { if (artifact.getGroupId().equals("android")) { continue; } if(artifact.getFile().isDirectory()) { throw new MojoExecutionException("Dependent artifact is directory: Directory = " + artifact.getFile().getAbsolutePath()); } try { unjar(new JarFile(artifact.getFile()), outputDirectory); } catch (IOException e) { throw new MojoExecutionException("Unable to jar file: File = " + artifact.getFile().getAbsolutePath(), e); } } try { unjar(new JarFile(inputFile), outputDirectory); } catch (IOException e) { - throw new MojoExecutionException("", e); + throw new MojoExecutionException("IOException while unjarring " + inputFile + " into " + outputDirectory, e); } List<String> commands = new ArrayList<String>(); if (jvmArguments != null){ for (String jvmArgument : jvmArguments) { if (jvmArgument != null){ if (jvmArgument.startsWith("-")){ jvmArgument = jvmArgument.substring(1); } commands.add("-J" + jvmArgument); } } } commands.add("--dex"); commands.add("--output=" + outputFile.getAbsolutePath()); commands.add(outputDirectory.getAbsolutePath()); getLog().info(getAndroidSdk().getPathForTool("dx") + " " + commands.toString()); try { executor.executeCommand(getAndroidSdk().getPathForTool("dx"), commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } projectHelper.attachArtifact(project, "jar", project.getArtifact().getClassifier(), inputFile); } private void unjar(JarFile jarFile, File outputDirectory) throws IOException { for (Enumeration en = jarFile.entries(); en.hasMoreElements();) { JarEntry entry = (JarEntry) en.nextElement(); File entryFile = new File(outputDirectory, entry.getName()); if (!entryFile.getParentFile().exists() && !entry.getName().startsWith("META-INF")) { entryFile.getParentFile().mkdirs(); } if (!entry.isDirectory() && entry.getName().endsWith(".class")) { final InputStream in = jarFile.getInputStream(entry); try { final OutputStream out = new FileOutputStream(entryFile); try { IOUtil.copy(in, out); } finally { closeQuietly(out); } } finally { closeQuietly(in); } } } } private void closeQuietly(final Closeable c) { try { c.close(); } catch (Exception ex) { getLog().warn("Failed to close closeable " + c, ex); } } }
false
true
public void execute() throws MojoExecutionException, MojoFailureException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); File outputFile = new File(project.getBuild().getDirectory() + File.separator + "classes.dex"); File inputFile = new File(project.getBuild().getDirectory() + File.separator + project.getBuild().getFinalName() + ".jar"); //Unpackage all dependent and main classes File outputDirectory = new File(project.getBuild().getDirectory(), "android-classes"); for (Artifact artifact : (List<Artifact>) project.getCompileArtifacts()) { if (artifact.getGroupId().equals("android")) { continue; } if(artifact.getFile().isDirectory()) { throw new MojoExecutionException("Dependent artifact is directory: Directory = " + artifact.getFile().getAbsolutePath()); } try { unjar(new JarFile(artifact.getFile()), outputDirectory); } catch (IOException e) { throw new MojoExecutionException("Unable to jar file: File = " + artifact.getFile().getAbsolutePath(), e); } } try { unjar(new JarFile(inputFile), outputDirectory); } catch (IOException e) { throw new MojoExecutionException("", e); } List<String> commands = new ArrayList<String>(); if (jvmArguments != null){ for (String jvmArgument : jvmArguments) { if (jvmArgument != null){ if (jvmArgument.startsWith("-")){ jvmArgument = jvmArgument.substring(1); } commands.add("-J" + jvmArgument); } } } commands.add("--dex"); commands.add("--output=" + outputFile.getAbsolutePath()); commands.add(outputDirectory.getAbsolutePath()); getLog().info(getAndroidSdk().getPathForTool("dx") + " " + commands.toString()); try { executor.executeCommand(getAndroidSdk().getPathForTool("dx"), commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } projectHelper.attachArtifact(project, "jar", project.getArtifact().getClassifier(), inputFile); }
public void execute() throws MojoExecutionException, MojoFailureException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); File outputFile = new File(project.getBuild().getDirectory() + File.separator + "classes.dex"); File inputFile = new File(project.getBuild().getDirectory() + File.separator + project.getBuild().getFinalName() + ".jar"); // Unpack all dependent and main classes File outputDirectory = new File(project.getBuild().getDirectory(), "android-classes"); for (Artifact artifact : (List<Artifact>) project.getCompileArtifacts()) { if (artifact.getGroupId().equals("android")) { continue; } if(artifact.getFile().isDirectory()) { throw new MojoExecutionException("Dependent artifact is directory: Directory = " + artifact.getFile().getAbsolutePath()); } try { unjar(new JarFile(artifact.getFile()), outputDirectory); } catch (IOException e) { throw new MojoExecutionException("Unable to jar file: File = " + artifact.getFile().getAbsolutePath(), e); } } try { unjar(new JarFile(inputFile), outputDirectory); } catch (IOException e) { throw new MojoExecutionException("IOException while unjarring " + inputFile + " into " + outputDirectory, e); } List<String> commands = new ArrayList<String>(); if (jvmArguments != null){ for (String jvmArgument : jvmArguments) { if (jvmArgument != null){ if (jvmArgument.startsWith("-")){ jvmArgument = jvmArgument.substring(1); } commands.add("-J" + jvmArgument); } } } commands.add("--dex"); commands.add("--output=" + outputFile.getAbsolutePath()); commands.add(outputDirectory.getAbsolutePath()); getLog().info(getAndroidSdk().getPathForTool("dx") + " " + commands.toString()); try { executor.executeCommand(getAndroidSdk().getPathForTool("dx"), commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } projectHelper.attachArtifact(project, "jar", project.getArtifact().getClassifier(), inputFile); }
diff --git a/src/de/enough/glaze/style/property/background/MaskBackground.java b/src/de/enough/glaze/style/property/background/MaskBackground.java index 40501ad..301a590 100644 --- a/src/de/enough/glaze/style/property/background/MaskBackground.java +++ b/src/de/enough/glaze/style/property/background/MaskBackground.java @@ -1,134 +1,139 @@ package de.enough.glaze.style.property.background; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.XYRect; public class MaskBackground extends GzCachedBackground { private final GzBackground mask, background; public MaskBackground(GzBackground mask, GzBackground background) { this.mask = mask; this.background = background; } /* * (non-Javadoc) * * @see de.enough.glaze.style.background.GzCachedBackground#create(int, int) */ public int[] create(int width, int height) { Bitmap maskBitmap = new Bitmap(width, height); Graphics maskBuffer = new Graphics(maskBitmap); Bitmap backgroundBitmap = new Bitmap(width, height); Graphics backgroundBuffer = new Graphics(backgroundBitmap); this.background.draw(backgroundBuffer, new XYRect(0, 0, width, height)); int bgColorBlack = 0x0; maskBuffer.setColor(bgColorBlack); maskBuffer.fillRect(0, 0, width, height); int[] transparentColorRgb = new int[1]; maskBitmap.getARGB(transparentColorRgb, 0, 1, 0, 0, 1, 1); bgColorBlack = transparentColorRgb[0]; this.mask.draw(maskBuffer, new XYRect(0, 0, width, height)); int[] dataBlack = new int[width * height]; maskBitmap.getARGB(dataBlack, 0, width, 0, 0, width, height); int bgColorWhite = 0xffffff; maskBuffer.setColor(bgColorWhite); maskBuffer.fillRect(0, 0, width, height); maskBitmap.getARGB(transparentColorRgb, 0, 1, 0, 0, 1, 1); bgColorWhite = transparentColorRgb[0]; this.mask.draw(maskBuffer, new XYRect(0, 0, width, height)); int[] dataWhite = new int[width * height]; maskBitmap.getARGB(dataWhite, 0, width, 0, 0, width, height); int rgbOpacity = (255 << 24); int[] resultMask = new int[dataBlack.length]; int lastPixelWhite = 0; int lastPixelBlack = 0; int lastPixelResult = 0; // ensure transparent parts are indeed transparent for (int i = 0; i < dataBlack.length; i++) { int pixelBlack = dataBlack[i]; int pixelWhite = dataWhite[i]; if (pixelBlack == pixelWhite) { resultMask[i] = pixelBlack & rgbOpacity; } else if (pixelBlack != bgColorBlack || pixelWhite != bgColorWhite) { if (pixelBlack == lastPixelBlack && pixelWhite == lastPixelWhite) { resultMask[i] = lastPixelResult; } else { // this pixel contains translucency: int redBlack = (pixelBlack & 0xff0000) >> 16; int greenBlack = (pixelBlack & 0xff00) >> 8; int blueBlack = (pixelBlack & 0xff); int redWhite = (pixelWhite & 0xff0000) >> 16; int greenWhite = (pixelWhite & 0xff00) >> 8; int blueWhite = (pixelWhite & 0xff); int originalAlpha = 0; int originalRed; if (redBlack == 0 && redWhite == 255) { originalRed = 0; } else { if (redBlack == 0) { redBlack = 1; } else if (redWhite == 255) { redWhite = 254; } originalRed = (255 * redBlack) / (redBlack - redWhite + 255); originalAlpha = redBlack - redWhite + 255; } int originalGreen; if (greenBlack == 0 && greenWhite == 255) { originalGreen = 0; } else { if (greenBlack == 0) { greenBlack = 1; } else if (greenWhite == 255) { greenWhite = 254; } originalGreen = (255 * greenBlack) / (greenBlack - greenWhite + 255); originalAlpha = greenBlack - greenWhite + 255; } int originalBlue; if (blueBlack == 0 && blueWhite == 255) { originalBlue = 0; } else { if (blueBlack == 0) { blueBlack = 1; } else if (blueWhite == 255) { blueWhite = 254; } originalBlue = (255 * blueBlack) / (blueBlack - blueWhite + 255); originalAlpha = blueBlack - blueWhite + 255; } + if ( originalAlpha > 255) { + originalAlpha = 255; + } else if ( originalAlpha < 0 ) { + originalAlpha = 0; + } lastPixelWhite = pixelWhite; lastPixelBlack = pixelBlack; lastPixelResult = ((originalAlpha << 24) | (originalRed << 16) | (originalGreen << 8) | originalBlue) & rgbOpacity; resultMask[i] = lastPixelResult; } } } int[] backgroundData = new int[width * height]; backgroundBitmap.getARGB(backgroundData, 0, width, 0, 0, width, height); for (int i = 0; i < resultMask.length; i++) { backgroundData[i] = (backgroundData[i] & 0x00FFFFFF) | (resultMask[i] & 0xFF000000); } return backgroundData; } }
true
true
public int[] create(int width, int height) { Bitmap maskBitmap = new Bitmap(width, height); Graphics maskBuffer = new Graphics(maskBitmap); Bitmap backgroundBitmap = new Bitmap(width, height); Graphics backgroundBuffer = new Graphics(backgroundBitmap); this.background.draw(backgroundBuffer, new XYRect(0, 0, width, height)); int bgColorBlack = 0x0; maskBuffer.setColor(bgColorBlack); maskBuffer.fillRect(0, 0, width, height); int[] transparentColorRgb = new int[1]; maskBitmap.getARGB(transparentColorRgb, 0, 1, 0, 0, 1, 1); bgColorBlack = transparentColorRgb[0]; this.mask.draw(maskBuffer, new XYRect(0, 0, width, height)); int[] dataBlack = new int[width * height]; maskBitmap.getARGB(dataBlack, 0, width, 0, 0, width, height); int bgColorWhite = 0xffffff; maskBuffer.setColor(bgColorWhite); maskBuffer.fillRect(0, 0, width, height); maskBitmap.getARGB(transparentColorRgb, 0, 1, 0, 0, 1, 1); bgColorWhite = transparentColorRgb[0]; this.mask.draw(maskBuffer, new XYRect(0, 0, width, height)); int[] dataWhite = new int[width * height]; maskBitmap.getARGB(dataWhite, 0, width, 0, 0, width, height); int rgbOpacity = (255 << 24); int[] resultMask = new int[dataBlack.length]; int lastPixelWhite = 0; int lastPixelBlack = 0; int lastPixelResult = 0; // ensure transparent parts are indeed transparent for (int i = 0; i < dataBlack.length; i++) { int pixelBlack = dataBlack[i]; int pixelWhite = dataWhite[i]; if (pixelBlack == pixelWhite) { resultMask[i] = pixelBlack & rgbOpacity; } else if (pixelBlack != bgColorBlack || pixelWhite != bgColorWhite) { if (pixelBlack == lastPixelBlack && pixelWhite == lastPixelWhite) { resultMask[i] = lastPixelResult; } else { // this pixel contains translucency: int redBlack = (pixelBlack & 0xff0000) >> 16; int greenBlack = (pixelBlack & 0xff00) >> 8; int blueBlack = (pixelBlack & 0xff); int redWhite = (pixelWhite & 0xff0000) >> 16; int greenWhite = (pixelWhite & 0xff00) >> 8; int blueWhite = (pixelWhite & 0xff); int originalAlpha = 0; int originalRed; if (redBlack == 0 && redWhite == 255) { originalRed = 0; } else { if (redBlack == 0) { redBlack = 1; } else if (redWhite == 255) { redWhite = 254; } originalRed = (255 * redBlack) / (redBlack - redWhite + 255); originalAlpha = redBlack - redWhite + 255; } int originalGreen; if (greenBlack == 0 && greenWhite == 255) { originalGreen = 0; } else { if (greenBlack == 0) { greenBlack = 1; } else if (greenWhite == 255) { greenWhite = 254; } originalGreen = (255 * greenBlack) / (greenBlack - greenWhite + 255); originalAlpha = greenBlack - greenWhite + 255; } int originalBlue; if (blueBlack == 0 && blueWhite == 255) { originalBlue = 0; } else { if (blueBlack == 0) { blueBlack = 1; } else if (blueWhite == 255) { blueWhite = 254; } originalBlue = (255 * blueBlack) / (blueBlack - blueWhite + 255); originalAlpha = blueBlack - blueWhite + 255; } lastPixelWhite = pixelWhite; lastPixelBlack = pixelBlack; lastPixelResult = ((originalAlpha << 24) | (originalRed << 16) | (originalGreen << 8) | originalBlue) & rgbOpacity; resultMask[i] = lastPixelResult; } } } int[] backgroundData = new int[width * height]; backgroundBitmap.getARGB(backgroundData, 0, width, 0, 0, width, height); for (int i = 0; i < resultMask.length; i++) { backgroundData[i] = (backgroundData[i] & 0x00FFFFFF) | (resultMask[i] & 0xFF000000); } return backgroundData; }
public int[] create(int width, int height) { Bitmap maskBitmap = new Bitmap(width, height); Graphics maskBuffer = new Graphics(maskBitmap); Bitmap backgroundBitmap = new Bitmap(width, height); Graphics backgroundBuffer = new Graphics(backgroundBitmap); this.background.draw(backgroundBuffer, new XYRect(0, 0, width, height)); int bgColorBlack = 0x0; maskBuffer.setColor(bgColorBlack); maskBuffer.fillRect(0, 0, width, height); int[] transparentColorRgb = new int[1]; maskBitmap.getARGB(transparentColorRgb, 0, 1, 0, 0, 1, 1); bgColorBlack = transparentColorRgb[0]; this.mask.draw(maskBuffer, new XYRect(0, 0, width, height)); int[] dataBlack = new int[width * height]; maskBitmap.getARGB(dataBlack, 0, width, 0, 0, width, height); int bgColorWhite = 0xffffff; maskBuffer.setColor(bgColorWhite); maskBuffer.fillRect(0, 0, width, height); maskBitmap.getARGB(transparentColorRgb, 0, 1, 0, 0, 1, 1); bgColorWhite = transparentColorRgb[0]; this.mask.draw(maskBuffer, new XYRect(0, 0, width, height)); int[] dataWhite = new int[width * height]; maskBitmap.getARGB(dataWhite, 0, width, 0, 0, width, height); int rgbOpacity = (255 << 24); int[] resultMask = new int[dataBlack.length]; int lastPixelWhite = 0; int lastPixelBlack = 0; int lastPixelResult = 0; // ensure transparent parts are indeed transparent for (int i = 0; i < dataBlack.length; i++) { int pixelBlack = dataBlack[i]; int pixelWhite = dataWhite[i]; if (pixelBlack == pixelWhite) { resultMask[i] = pixelBlack & rgbOpacity; } else if (pixelBlack != bgColorBlack || pixelWhite != bgColorWhite) { if (pixelBlack == lastPixelBlack && pixelWhite == lastPixelWhite) { resultMask[i] = lastPixelResult; } else { // this pixel contains translucency: int redBlack = (pixelBlack & 0xff0000) >> 16; int greenBlack = (pixelBlack & 0xff00) >> 8; int blueBlack = (pixelBlack & 0xff); int redWhite = (pixelWhite & 0xff0000) >> 16; int greenWhite = (pixelWhite & 0xff00) >> 8; int blueWhite = (pixelWhite & 0xff); int originalAlpha = 0; int originalRed; if (redBlack == 0 && redWhite == 255) { originalRed = 0; } else { if (redBlack == 0) { redBlack = 1; } else if (redWhite == 255) { redWhite = 254; } originalRed = (255 * redBlack) / (redBlack - redWhite + 255); originalAlpha = redBlack - redWhite + 255; } int originalGreen; if (greenBlack == 0 && greenWhite == 255) { originalGreen = 0; } else { if (greenBlack == 0) { greenBlack = 1; } else if (greenWhite == 255) { greenWhite = 254; } originalGreen = (255 * greenBlack) / (greenBlack - greenWhite + 255); originalAlpha = greenBlack - greenWhite + 255; } int originalBlue; if (blueBlack == 0 && blueWhite == 255) { originalBlue = 0; } else { if (blueBlack == 0) { blueBlack = 1; } else if (blueWhite == 255) { blueWhite = 254; } originalBlue = (255 * blueBlack) / (blueBlack - blueWhite + 255); originalAlpha = blueBlack - blueWhite + 255; } if ( originalAlpha > 255) { originalAlpha = 255; } else if ( originalAlpha < 0 ) { originalAlpha = 0; } lastPixelWhite = pixelWhite; lastPixelBlack = pixelBlack; lastPixelResult = ((originalAlpha << 24) | (originalRed << 16) | (originalGreen << 8) | originalBlue) & rgbOpacity; resultMask[i] = lastPixelResult; } } } int[] backgroundData = new int[width * height]; backgroundBitmap.getARGB(backgroundData, 0, width, 0, 0, width, height); for (int i = 0; i < resultMask.length; i++) { backgroundData[i] = (backgroundData[i] & 0x00FFFFFF) | (resultMask[i] & 0xFF000000); } return backgroundData; }
diff --git a/src/radlab/rain/ScenarioTrack.java b/src/radlab/rain/ScenarioTrack.java index 3d33a3c..951124f 100644 --- a/src/radlab/rain/ScenarioTrack.java +++ b/src/radlab/rain/ScenarioTrack.java @@ -1,456 +1,461 @@ /* * Copyright (c) 2010, Regents of the University of California * 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 University of California, Berkeley * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package radlab.rain; import java.lang.reflect.Constructor; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException; import radlab.rain.util.MetricWriter; import radlab.rain.util.MetricWriterFactory; /** * The ScenarioTrack abstract class represents a single workload among * potentially many that are simultaneously run under a single * Scenario.<br /> * <br /> * The ScenarioTrack is responsible for reading in the configuration of a * workload and generating the load profiles. */ public abstract class ScenarioTrack { public static final int VALID_LOAD_PROFILE = 0; public static final int ERROR_INVALID_LOAD_PROFILE_BAD_NUM_USERS = 1777; public static final int ERROR_INVALID_LOAD_PROFILE_BAD_MIX_NAME = 1778; public static final int ERROR_INVALID_LOAD_PROFILE_BAD_BEHAVIOR_HINT = 1779; public static final int ERROR_TRACK_NOT_FOUND = 1780; public static String CFG_TRACK_CLASS_KEY = "track"; public static String CFG_OPEN_LOOP_PROBABILITY_KEY = "pOpenLoop"; public static String CFG_LOG_SAMPLING_PROBABILITY_KEY = "pLogSampling"; public static String CFG_MEAN_CYCLE_TIME_KEY = "meanCycleTime"; public static String CFG_MEAN_THINK_TIME_KEY = "meanThinkTime"; public static String CFG_INTERACTIVE_KEY = "interactive"; public static String CFG_TARGET_KEY = "target"; public static String CFG_METRIC_SNAPSHOT_INTERVAL = "metricSnapshotInterval"; public static String CFG_METRIC_SNAPSHOTS = "metricSnapshots"; public static String CFG_METRIC_SNAPSHOT_FILE_SUFFIX = "metricSnapshotsFileSuffix"; public static String CFG_METRIC_SNAPSHOT_CONFIG = "metricSnapshotConfig"; public static String CFG_METRIC_DB = "metricDB"; // Targets keys: hostname, port public static String CFG_TARGET_HOSTNAME_KEY = "hostname"; public static String CFG_TARGET_PORT_KEY = "port"; public static String CFG_GENERATOR_KEY = "generator"; public static String CFG_GENERATOR_PARAMS_KEY = "generatorParameters"; public static String CFG_LOAD_PROFILE_CLASS_KEY = "loadProfileClass"; public static String CFG_LOAD_PROFILE_KEY = "loadProfile"; public static String CFG_LOAD_SCHEDULE_CREATOR_KEY = "loadScheduleCreator"; public static String CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY = "loadScheduleCreatorParameters"; public static String CFG_LOAD_GENERATION_STRATEGY_KEY = "loadGenerationStrategy"; public static String CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY= "loadGenerationStrategyParams"; // Load behavioral hints public static String CFG_BEHAVIOR_KEY = "behavior"; public static String CFG_RESOURCE_PATH = "resourcePath"; public static String CFG_OBJECT_POOL_MAX_SIZE = "objectPoolMaxSize"; public static String CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL = "meanResponseTimeSamplingInterval"; public static String CFG_MAX_USERS = "maxUsers"; // Defaults public static long DEFAULT_OBJECT_POOL_MAX_SIZE = 50000; public static long DEFAULT_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL = 500; public static String DEFAULT_LOAD_PROFILE_CLASS = "radlab.rain.LoadProfile"; public static final String DEFAULT_LOAD_GENERATION_STRATEGY_CLASS = "radlab.rain.PartlyOpenLoopLoadGeneration"; protected Scenario _parentScenario = null; //protected Generator _generator = null; protected String _name = "none"; protected String _targetHostname = null; protected int _targetPort = 80; public volatile LoadProfile _currentLoadProfile = null; protected LinkedList<LoadProfile> _loadSchedule = new LinkedList<LoadProfile>(); protected Hashtable<String,MixMatrix> _mixMap = new Hashtable<String,MixMatrix>(); protected String _scoreboardClassName = "radlab.rain.Scoreboard"; protected String _generatorClassName = ""; protected JSONObject _generatorParams = null; protected String _loadProfileClassName = ""; protected String _loadGenerationStrategyClassName = ""; protected JSONObject _loadGenerationStrategyParams = null; protected boolean _interactive = true; private IScoreboard _scoreboard = null; protected double _openLoopProbability = 0.0; protected String _resourcePath = "resources/"; // Path on local machine for files we may need (e.g. to send an image/data file as part of an operation) protected double _meanCycleTime = 0.0; // non-stop request generation protected double _meanThinkTime = 0.0; // non-stop request generation protected double _logSamplingProbability = 1.0; // Log every executed request seen by the Scoreboard protected double _metricSnapshotInterval = 60.0; // (seconds) protected boolean _useMetricSnapshots = false; protected MetricWriter _metricWriter = null; protected String _metricSnapshotFileSuffix = ""; protected ObjectPool _objPool = null; protected long _meanResponseTimeSamplingInterval = DEFAULT_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL; protected int _maxUsersFromConfig = 0; /** * Create a new scenario track that will be benchmarked as part of the * provided <code>Scenario</code>. * * @param parentScenario The Scenario under which this will be running. */ public ScenarioTrack( Scenario parentScenario ) { this._parentScenario = parentScenario; } public abstract void start(); public abstract void end(); public abstract LoadProfile getCurrentLoadProfile(); public abstract int validateLoadProfile( LoadProfile profile ); public abstract void submitDynamicLoadProfile( LoadProfile profile ); // public abstract LoadProfile getNextLoadProfile(); public String getGeneratorClassName() { return this._generatorClassName; } public JSONObject getGeneratorParams() { return this._generatorParams; } public String getName() { return this._name; } public void setName( String val ) { this._name = val; } public long getRampUp() { return this._parentScenario.getRampUp(); } public long getDuration() { return this._parentScenario.getDuration(); } public long getRampDown() { return this._parentScenario.getRampDown(); } public boolean getInteractive() { return this._interactive; } public void setInteractive( boolean val ) { this._interactive = val; } public String getLoadGenerationStrategyClassName() { return this._loadGenerationStrategyClassName; } public JSONObject getLoadGenerationStrategyParams() { return this._loadGenerationStrategyParams; } public ObjectPool getObjectPool() { return this._objPool; }; public int getMaxUsers() { // Search the load profiles to figure out the maximum int maxUsersFromProfile = 0; Iterator<LoadProfile> it = this._loadSchedule.iterator(); while( it.hasNext() ) { LoadProfile current = it.next(); if( current.getNumberOfUsers() > maxUsersFromProfile ) maxUsersFromProfile = current.getNumberOfUsers(); } // In the end return the max of what's in the schedule and what was // put in the explicit maxUsers config setting. If the config setting // is larger that what's in the profile, then this allows the for a dynamic // load profile to create a spike of that magnitude. return Math.max( maxUsersFromProfile, this._maxUsersFromConfig ); } public MixMatrix getMixMatrix( String name ) { return this._mixMap.get( name ); } public Scenario getParentScenario() { return this._parentScenario; } public void setParentScenario( Scenario val ) { this._parentScenario = val; } public IScoreboard getScoreboard() { return this._scoreboard; } public void setScoreboard( IScoreboard val ) { this._scoreboard = val; val.setTargetHost( this._targetHostname ); } public double getOpenLoopProbability() { return this._openLoopProbability; } public void setOpenLoopProbability( double val ) { this._openLoopProbability = val; } public String getTargetHostName() { return this._targetHostname; } public void setTargetHostName( String val ) { this._targetHostname = val; } public int getTargetHostPort() { return this._targetPort; } public void setTargetHostPort( int val ) { this._targetPort = val; } public double getMeanCycleTime() { return this._meanCycleTime; } public void setMeanCycleTime( double val ) { this._meanCycleTime = val; } public double getMeanThinkTime() { return this._meanThinkTime; } public void setMeanThinkTime( double val ) { this._meanThinkTime = val; } public String getResourcePath() { return this._resourcePath; } public void setResourcePath( String val ) { this._resourcePath = val; } //public Generator getGenerator() { return this._generator; } //public void setGenerator( Generator val ) { this._generator = val; } public double getLogSamplingProbability() { return this._logSamplingProbability; } public void setLogSamplingProbability( double val ) { this._logSamplingProbability = val; } public double getMetricSnapshotInterval() { return this._metricSnapshotInterval; } public void setMetricSnapshotInterval( double val ) { this._metricSnapshotInterval = val; } public MetricWriter getMetricWriter() { return this._metricWriter; } public void setMetricWriter( MetricWriter val ) { this._metricWriter = val; } /** * Initializes a ScenarioTrack by reading the configurations set in the * provided JSON object. * * @param config The JSON configuration object. * * @throws JSONException * @throws Exception */ @SuppressWarnings("unchecked") public void initialize( JSONObject config ) throws JSONException, Exception { // 1) Open-Loop Probability this._openLoopProbability = config.getDouble( ScenarioTrack.CFG_OPEN_LOOP_PROBABILITY_KEY ); // 3) Target Information JSONObject target = config.getJSONObject( ScenarioTrack.CFG_TARGET_KEY ); this._targetHostname = target.getString( ScenarioTrack.CFG_TARGET_HOSTNAME_KEY ); this._targetPort = target.getInt( ScenarioTrack.CFG_TARGET_PORT_KEY ); // 2) Concrete Generator this._generatorClassName = config.getString( ScenarioTrack.CFG_GENERATOR_KEY ); this._generatorParams = null; if( config.has( ScenarioTrack.CFG_GENERATOR_PARAMS_KEY ) ) this._generatorParams = config.getJSONObject( ScenarioTrack.CFG_GENERATOR_PARAMS_KEY ); //this._generator = this.createWorkloadGenerator( this._generatorClassName, this._generatorParams ); // 4) Log Sampling Probability this._logSamplingProbability = config.getDouble( ScenarioTrack.CFG_LOG_SAMPLING_PROBABILITY_KEY ); // 5) Mean Cycle Time this._meanCycleTime = config.getDouble( ScenarioTrack.CFG_MEAN_CYCLE_TIME_KEY ); // 6) Mean Think Time this._meanThinkTime = config.getDouble( ScenarioTrack.CFG_MEAN_THINK_TIME_KEY ); //this._generator.setMeanCycleTime( (long) (this._meanCycleTime * 1000) ); //this._generator.setMeanThinkTime( (long) (this._meanThinkTime * 1000) ); // 7) Interactive? this._interactive = config.getBoolean( ScenarioTrack.CFG_INTERACTIVE_KEY ); // 8) Concrete Load Profile and Load Profile Array if ( config.has( ScenarioTrack.CFG_LOAD_PROFILE_CLASS_KEY ) ) { this._loadProfileClassName = config.getString( ScenarioTrack.CFG_LOAD_PROFILE_CLASS_KEY ); } else { this._loadProfileClassName = ScenarioTrack.DEFAULT_LOAD_PROFILE_CLASS; } // Look for a load schedule OR a class that creates it, we prefer the class if( config.has( ScenarioTrack.CFG_LOAD_SCHEDULE_CREATOR_KEY ) ) { // Create the load schedule creator String loadSchedulerClass = config.getString( ScenarioTrack.CFG_LOAD_SCHEDULE_CREATOR_KEY ); LoadScheduleCreator loadScheduler = this.createLoadScheduleCreator( loadSchedulerClass ); JSONObject loadSchedulerParams = new JSONObject(); // Look for load scheduler parameters if any exist if( config.has( CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY) ) loadSchedulerParams = config.getJSONObject( CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY ); if( loadScheduler != null ) this._loadSchedule = loadScheduler.createSchedule( loadSchedulerParams ); else throw new Exception( "Error creating load scheduler class: " + loadSchedulerClass ); } else { JSONArray loadSchedule = config.getJSONArray( ScenarioTrack.CFG_LOAD_PROFILE_KEY ); for ( int i = 0; i < loadSchedule.length(); i++ ) { JSONObject profileObj = loadSchedule.getJSONObject( i ); LoadProfile profile = this.createLoadProfile( this._loadProfileClassName, profileObj ); // If the profile does NOT have a name, set one using "i" formatted as "00000N" if( profile._name == null || profile._name.length() == 0 ) profile._name = new java.text.DecimalFormat("00000").format( i ); this._loadSchedule.add( profile ); } } if( this._loadSchedule.size() == 0 ) throw new Exception( "Error: empty load schedule. Nothing to do." ); // 9) Load Mix Matrices/Behavior Directives JSONObject behavior = config.getJSONObject( ScenarioTrack.CFG_BEHAVIOR_KEY ); Iterator<String> keyIt = behavior.keys(); // Each of the keys in the behavior section should be for some mix matrix while ( keyIt.hasNext() ) { String mixName = keyIt.next(); // Now we need to get this object and parse it JSONArray mix = behavior.getJSONArray( mixName ); double[][] data = null; for ( int i = 0; i < mix.length(); i++ ) { if ( i == 0 ) { data = new double[mix.length()][mix.length()]; } // Each row is itself an array of doubles JSONArray row = mix.getJSONArray( i ); for ( int j = 0; j < row.length(); j++ ) { data[i][j] = row.getDouble( j ); } } MixMatrix m = new MixMatrix( data ); this._mixMap.put( mixName, m ); } // 10 Scoreboard snapshot interval if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_INTERVAL ) ) { this._metricSnapshotInterval = config.getDouble( ScenarioTrack.CFG_METRIC_SNAPSHOT_INTERVAL ); } if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_FILE_SUFFIX ) ) this._metricSnapshotFileSuffix = config.getString( ScenarioTrack.CFG_METRIC_SNAPSHOT_FILE_SUFFIX ); if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOTS ) ) { this._useMetricSnapshots = config.getBoolean( ScenarioTrack.CFG_METRIC_SNAPSHOTS ); if( this._useMetricSnapshots ) { // Extract the metricwriter config, create an instance and pass it to the scoreboard if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_CONFIG ) ) { JSONObject metricWriterConfig = config.getJSONObject( ScenarioTrack.CFG_METRIC_SNAPSHOT_CONFIG ); this._metricWriter = MetricWriterFactory.createMetricWriter( metricWriterConfig.getString( MetricWriter.CFG_TYPE_KEY ), metricWriterConfig ); } else { // Default to file writer StringBuffer buf = new StringBuffer(); buf.append( "metrics-snapshots-" ).append( this._name ).append( "-" ).append( this._metricSnapshotFileSuffix ).append( ".log" ); String metricSnapshotFileName = buf.toString(); JSONObject metricWriterConfig = new JSONObject(); metricWriterConfig.put( MetricWriter.CFG_TYPE_KEY, MetricWriterFactory.FILE_WRITER_TYPE ); metricWriterConfig.put( MetricWriter.CFG_FILENAME_KEY, metricSnapshotFileName ); this._metricWriter = MetricWriterFactory.createMetricWriter( metricWriterConfig.getString( MetricWriter.CFG_TYPE_KEY ), metricWriterConfig ); } } } // 11 Initialize the object pool - by default it remains empty unless one of the concrete operations // uses it. if( config.has( ScenarioTrack.CFG_OBJECT_POOL_MAX_SIZE ) ) { this._objPool = new ObjectPool( config.getLong( ScenarioTrack.CFG_OBJECT_POOL_MAX_SIZE ) ); } else { this._objPool = new ObjectPool( ScenarioTrack.DEFAULT_OBJECT_POOL_MAX_SIZE ); } this._objPool.setTrackName( this._name ); // 12 Configure the response time sampler if( config.has( ScenarioTrack.CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL ) ) this._meanResponseTimeSamplingInterval = config.getLong( ScenarioTrack.CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL ); // 13 Configure the maxUsers if specified if( config.has( ScenarioTrack.CFG_MAX_USERS ) ) this._maxUsersFromConfig = config.getInt( ScenarioTrack.CFG_MAX_USERS ); // 14 Look for a load generation strategy and optional params if they exist if( config.has( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_KEY ) ) { this._loadGenerationStrategyClassName = config.getString( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_KEY ); // Check for parameters if( config.has( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY ) ) this._loadGenerationStrategyParams = config.getJSONObject( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY ); else this._loadGenerationStrategyParams = new JSONObject(); } else { this._loadGenerationStrategyClassName = ScenarioTrack.DEFAULT_LOAD_GENERATION_STRATEGY_CLASS; this._loadGenerationStrategyParams = new JSONObject(); } + // 15 Look for a resource path + if (config.has(ScenarioTrack.CFG_RESOURCE_PATH)) + { + this._resourcePath = config.getString(ScenarioTrack.CFG_RESOURCE_PATH); + } } // Factory methods @SuppressWarnings("unchecked") public LoadScheduleCreator createLoadScheduleCreator( String name ) throws Exception { LoadScheduleCreator creator = null; Class<LoadScheduleCreator> creatorClass = (Class<LoadScheduleCreator>) Class.forName( name ); Constructor<LoadScheduleCreator> creatorCtor = creatorClass.getConstructor( new Class[]{} ); creator = (LoadScheduleCreator) creatorCtor.newInstance( (Object[]) null ); return creator; } @SuppressWarnings("unchecked") public Generator createWorkloadGenerator( String name, JSONObject config ) throws Exception { Generator generator = null; Class<Generator> generatorClass = (Class<Generator>) Class.forName( name ); Constructor<Generator> generatorCtor = generatorClass.getConstructor( new Class[]{ ScenarioTrack.class } ); generator = (Generator) generatorCtor.newInstance( new Object[] { this } ); if( config != null ) generator.configure( config ); return generator; } @SuppressWarnings("unchecked") public LoadProfile createLoadProfile( String name, JSONObject profileObj ) throws Exception { LoadProfile loadProfile = null; Class<LoadProfile> loadProfileClass = (Class<LoadProfile>) Class.forName( name ); Constructor<LoadProfile> loadProfileCtor = loadProfileClass.getConstructor( new Class[]{ JSONObject.class } ); loadProfile = (LoadProfile) loadProfileCtor.newInstance( new Object[] { profileObj } ); return loadProfile; } @SuppressWarnings("unchecked") public IScoreboard createScoreboard( String name ) throws Exception { if( name == null ) name = this._scoreboardClassName; IScoreboard scoreboard = null; Class<IScoreboard> scoreboardClass = (Class<IScoreboard>) Class.forName( name ); Constructor<IScoreboard> scoreboardCtor = scoreboardClass.getConstructor( String.class ); scoreboard = (IScoreboard) scoreboardCtor.newInstance( this._name ); // Set the log sampling probability for the scoreboard scoreboard.setLogSamplingProbability( this._logSamplingProbability ); scoreboard.setScenarioTrack( this ); scoreboard.setUsingMetricSnapshots( this._useMetricSnapshots ); scoreboard.setMeanResponseTimeSamplingInterval( this._meanResponseTimeSamplingInterval ); return scoreboard; } @SuppressWarnings("unchecked") public LoadGenerationStrategy createLoadGenerationStrategy( String loadGenerationStrategyClassName, JSONObject loadGenerationStrategyParams, Generator generator, int id ) throws Exception { LoadGenerationStrategy loadGenStrategy = null; Class<LoadGenerationStrategy> loadGenStrategyClass = (Class<LoadGenerationStrategy>) Class.forName( loadGenerationStrategyClassName ); Constructor<LoadGenerationStrategy> loadGenStrategyCtor = loadGenStrategyClass.getConstructor( new Class[] {Generator.class, long.class, JSONObject.class} ); loadGenStrategy = (LoadGenerationStrategy) loadGenStrategyCtor.newInstance( new Object[] { generator, id, loadGenerationStrategyParams } ); return loadGenStrategy; } public String toString() { return "[TRACK: " + this._name + "]"; } }
true
true
public void initialize( JSONObject config ) throws JSONException, Exception { // 1) Open-Loop Probability this._openLoopProbability = config.getDouble( ScenarioTrack.CFG_OPEN_LOOP_PROBABILITY_KEY ); // 3) Target Information JSONObject target = config.getJSONObject( ScenarioTrack.CFG_TARGET_KEY ); this._targetHostname = target.getString( ScenarioTrack.CFG_TARGET_HOSTNAME_KEY ); this._targetPort = target.getInt( ScenarioTrack.CFG_TARGET_PORT_KEY ); // 2) Concrete Generator this._generatorClassName = config.getString( ScenarioTrack.CFG_GENERATOR_KEY ); this._generatorParams = null; if( config.has( ScenarioTrack.CFG_GENERATOR_PARAMS_KEY ) ) this._generatorParams = config.getJSONObject( ScenarioTrack.CFG_GENERATOR_PARAMS_KEY ); //this._generator = this.createWorkloadGenerator( this._generatorClassName, this._generatorParams ); // 4) Log Sampling Probability this._logSamplingProbability = config.getDouble( ScenarioTrack.CFG_LOG_SAMPLING_PROBABILITY_KEY ); // 5) Mean Cycle Time this._meanCycleTime = config.getDouble( ScenarioTrack.CFG_MEAN_CYCLE_TIME_KEY ); // 6) Mean Think Time this._meanThinkTime = config.getDouble( ScenarioTrack.CFG_MEAN_THINK_TIME_KEY ); //this._generator.setMeanCycleTime( (long) (this._meanCycleTime * 1000) ); //this._generator.setMeanThinkTime( (long) (this._meanThinkTime * 1000) ); // 7) Interactive? this._interactive = config.getBoolean( ScenarioTrack.CFG_INTERACTIVE_KEY ); // 8) Concrete Load Profile and Load Profile Array if ( config.has( ScenarioTrack.CFG_LOAD_PROFILE_CLASS_KEY ) ) { this._loadProfileClassName = config.getString( ScenarioTrack.CFG_LOAD_PROFILE_CLASS_KEY ); } else { this._loadProfileClassName = ScenarioTrack.DEFAULT_LOAD_PROFILE_CLASS; } // Look for a load schedule OR a class that creates it, we prefer the class if( config.has( ScenarioTrack.CFG_LOAD_SCHEDULE_CREATOR_KEY ) ) { // Create the load schedule creator String loadSchedulerClass = config.getString( ScenarioTrack.CFG_LOAD_SCHEDULE_CREATOR_KEY ); LoadScheduleCreator loadScheduler = this.createLoadScheduleCreator( loadSchedulerClass ); JSONObject loadSchedulerParams = new JSONObject(); // Look for load scheduler parameters if any exist if( config.has( CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY) ) loadSchedulerParams = config.getJSONObject( CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY ); if( loadScheduler != null ) this._loadSchedule = loadScheduler.createSchedule( loadSchedulerParams ); else throw new Exception( "Error creating load scheduler class: " + loadSchedulerClass ); } else { JSONArray loadSchedule = config.getJSONArray( ScenarioTrack.CFG_LOAD_PROFILE_KEY ); for ( int i = 0; i < loadSchedule.length(); i++ ) { JSONObject profileObj = loadSchedule.getJSONObject( i ); LoadProfile profile = this.createLoadProfile( this._loadProfileClassName, profileObj ); // If the profile does NOT have a name, set one using "i" formatted as "00000N" if( profile._name == null || profile._name.length() == 0 ) profile._name = new java.text.DecimalFormat("00000").format( i ); this._loadSchedule.add( profile ); } } if( this._loadSchedule.size() == 0 ) throw new Exception( "Error: empty load schedule. Nothing to do." ); // 9) Load Mix Matrices/Behavior Directives JSONObject behavior = config.getJSONObject( ScenarioTrack.CFG_BEHAVIOR_KEY ); Iterator<String> keyIt = behavior.keys(); // Each of the keys in the behavior section should be for some mix matrix while ( keyIt.hasNext() ) { String mixName = keyIt.next(); // Now we need to get this object and parse it JSONArray mix = behavior.getJSONArray( mixName ); double[][] data = null; for ( int i = 0; i < mix.length(); i++ ) { if ( i == 0 ) { data = new double[mix.length()][mix.length()]; } // Each row is itself an array of doubles JSONArray row = mix.getJSONArray( i ); for ( int j = 0; j < row.length(); j++ ) { data[i][j] = row.getDouble( j ); } } MixMatrix m = new MixMatrix( data ); this._mixMap.put( mixName, m ); } // 10 Scoreboard snapshot interval if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_INTERVAL ) ) { this._metricSnapshotInterval = config.getDouble( ScenarioTrack.CFG_METRIC_SNAPSHOT_INTERVAL ); } if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_FILE_SUFFIX ) ) this._metricSnapshotFileSuffix = config.getString( ScenarioTrack.CFG_METRIC_SNAPSHOT_FILE_SUFFIX ); if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOTS ) ) { this._useMetricSnapshots = config.getBoolean( ScenarioTrack.CFG_METRIC_SNAPSHOTS ); if( this._useMetricSnapshots ) { // Extract the metricwriter config, create an instance and pass it to the scoreboard if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_CONFIG ) ) { JSONObject metricWriterConfig = config.getJSONObject( ScenarioTrack.CFG_METRIC_SNAPSHOT_CONFIG ); this._metricWriter = MetricWriterFactory.createMetricWriter( metricWriterConfig.getString( MetricWriter.CFG_TYPE_KEY ), metricWriterConfig ); } else { // Default to file writer StringBuffer buf = new StringBuffer(); buf.append( "metrics-snapshots-" ).append( this._name ).append( "-" ).append( this._metricSnapshotFileSuffix ).append( ".log" ); String metricSnapshotFileName = buf.toString(); JSONObject metricWriterConfig = new JSONObject(); metricWriterConfig.put( MetricWriter.CFG_TYPE_KEY, MetricWriterFactory.FILE_WRITER_TYPE ); metricWriterConfig.put( MetricWriter.CFG_FILENAME_KEY, metricSnapshotFileName ); this._metricWriter = MetricWriterFactory.createMetricWriter( metricWriterConfig.getString( MetricWriter.CFG_TYPE_KEY ), metricWriterConfig ); } } } // 11 Initialize the object pool - by default it remains empty unless one of the concrete operations // uses it. if( config.has( ScenarioTrack.CFG_OBJECT_POOL_MAX_SIZE ) ) { this._objPool = new ObjectPool( config.getLong( ScenarioTrack.CFG_OBJECT_POOL_MAX_SIZE ) ); } else { this._objPool = new ObjectPool( ScenarioTrack.DEFAULT_OBJECT_POOL_MAX_SIZE ); } this._objPool.setTrackName( this._name ); // 12 Configure the response time sampler if( config.has( ScenarioTrack.CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL ) ) this._meanResponseTimeSamplingInterval = config.getLong( ScenarioTrack.CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL ); // 13 Configure the maxUsers if specified if( config.has( ScenarioTrack.CFG_MAX_USERS ) ) this._maxUsersFromConfig = config.getInt( ScenarioTrack.CFG_MAX_USERS ); // 14 Look for a load generation strategy and optional params if they exist if( config.has( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_KEY ) ) { this._loadGenerationStrategyClassName = config.getString( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_KEY ); // Check for parameters if( config.has( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY ) ) this._loadGenerationStrategyParams = config.getJSONObject( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY ); else this._loadGenerationStrategyParams = new JSONObject(); } else { this._loadGenerationStrategyClassName = ScenarioTrack.DEFAULT_LOAD_GENERATION_STRATEGY_CLASS; this._loadGenerationStrategyParams = new JSONObject(); } }
public void initialize( JSONObject config ) throws JSONException, Exception { // 1) Open-Loop Probability this._openLoopProbability = config.getDouble( ScenarioTrack.CFG_OPEN_LOOP_PROBABILITY_KEY ); // 3) Target Information JSONObject target = config.getJSONObject( ScenarioTrack.CFG_TARGET_KEY ); this._targetHostname = target.getString( ScenarioTrack.CFG_TARGET_HOSTNAME_KEY ); this._targetPort = target.getInt( ScenarioTrack.CFG_TARGET_PORT_KEY ); // 2) Concrete Generator this._generatorClassName = config.getString( ScenarioTrack.CFG_GENERATOR_KEY ); this._generatorParams = null; if( config.has( ScenarioTrack.CFG_GENERATOR_PARAMS_KEY ) ) this._generatorParams = config.getJSONObject( ScenarioTrack.CFG_GENERATOR_PARAMS_KEY ); //this._generator = this.createWorkloadGenerator( this._generatorClassName, this._generatorParams ); // 4) Log Sampling Probability this._logSamplingProbability = config.getDouble( ScenarioTrack.CFG_LOG_SAMPLING_PROBABILITY_KEY ); // 5) Mean Cycle Time this._meanCycleTime = config.getDouble( ScenarioTrack.CFG_MEAN_CYCLE_TIME_KEY ); // 6) Mean Think Time this._meanThinkTime = config.getDouble( ScenarioTrack.CFG_MEAN_THINK_TIME_KEY ); //this._generator.setMeanCycleTime( (long) (this._meanCycleTime * 1000) ); //this._generator.setMeanThinkTime( (long) (this._meanThinkTime * 1000) ); // 7) Interactive? this._interactive = config.getBoolean( ScenarioTrack.CFG_INTERACTIVE_KEY ); // 8) Concrete Load Profile and Load Profile Array if ( config.has( ScenarioTrack.CFG_LOAD_PROFILE_CLASS_KEY ) ) { this._loadProfileClassName = config.getString( ScenarioTrack.CFG_LOAD_PROFILE_CLASS_KEY ); } else { this._loadProfileClassName = ScenarioTrack.DEFAULT_LOAD_PROFILE_CLASS; } // Look for a load schedule OR a class that creates it, we prefer the class if( config.has( ScenarioTrack.CFG_LOAD_SCHEDULE_CREATOR_KEY ) ) { // Create the load schedule creator String loadSchedulerClass = config.getString( ScenarioTrack.CFG_LOAD_SCHEDULE_CREATOR_KEY ); LoadScheduleCreator loadScheduler = this.createLoadScheduleCreator( loadSchedulerClass ); JSONObject loadSchedulerParams = new JSONObject(); // Look for load scheduler parameters if any exist if( config.has( CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY) ) loadSchedulerParams = config.getJSONObject( CFG_LOAD_SCHEDULE_CREATOR_PARAMS_KEY ); if( loadScheduler != null ) this._loadSchedule = loadScheduler.createSchedule( loadSchedulerParams ); else throw new Exception( "Error creating load scheduler class: " + loadSchedulerClass ); } else { JSONArray loadSchedule = config.getJSONArray( ScenarioTrack.CFG_LOAD_PROFILE_KEY ); for ( int i = 0; i < loadSchedule.length(); i++ ) { JSONObject profileObj = loadSchedule.getJSONObject( i ); LoadProfile profile = this.createLoadProfile( this._loadProfileClassName, profileObj ); // If the profile does NOT have a name, set one using "i" formatted as "00000N" if( profile._name == null || profile._name.length() == 0 ) profile._name = new java.text.DecimalFormat("00000").format( i ); this._loadSchedule.add( profile ); } } if( this._loadSchedule.size() == 0 ) throw new Exception( "Error: empty load schedule. Nothing to do." ); // 9) Load Mix Matrices/Behavior Directives JSONObject behavior = config.getJSONObject( ScenarioTrack.CFG_BEHAVIOR_KEY ); Iterator<String> keyIt = behavior.keys(); // Each of the keys in the behavior section should be for some mix matrix while ( keyIt.hasNext() ) { String mixName = keyIt.next(); // Now we need to get this object and parse it JSONArray mix = behavior.getJSONArray( mixName ); double[][] data = null; for ( int i = 0; i < mix.length(); i++ ) { if ( i == 0 ) { data = new double[mix.length()][mix.length()]; } // Each row is itself an array of doubles JSONArray row = mix.getJSONArray( i ); for ( int j = 0; j < row.length(); j++ ) { data[i][j] = row.getDouble( j ); } } MixMatrix m = new MixMatrix( data ); this._mixMap.put( mixName, m ); } // 10 Scoreboard snapshot interval if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_INTERVAL ) ) { this._metricSnapshotInterval = config.getDouble( ScenarioTrack.CFG_METRIC_SNAPSHOT_INTERVAL ); } if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_FILE_SUFFIX ) ) this._metricSnapshotFileSuffix = config.getString( ScenarioTrack.CFG_METRIC_SNAPSHOT_FILE_SUFFIX ); if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOTS ) ) { this._useMetricSnapshots = config.getBoolean( ScenarioTrack.CFG_METRIC_SNAPSHOTS ); if( this._useMetricSnapshots ) { // Extract the metricwriter config, create an instance and pass it to the scoreboard if( config.has( ScenarioTrack.CFG_METRIC_SNAPSHOT_CONFIG ) ) { JSONObject metricWriterConfig = config.getJSONObject( ScenarioTrack.CFG_METRIC_SNAPSHOT_CONFIG ); this._metricWriter = MetricWriterFactory.createMetricWriter( metricWriterConfig.getString( MetricWriter.CFG_TYPE_KEY ), metricWriterConfig ); } else { // Default to file writer StringBuffer buf = new StringBuffer(); buf.append( "metrics-snapshots-" ).append( this._name ).append( "-" ).append( this._metricSnapshotFileSuffix ).append( ".log" ); String metricSnapshotFileName = buf.toString(); JSONObject metricWriterConfig = new JSONObject(); metricWriterConfig.put( MetricWriter.CFG_TYPE_KEY, MetricWriterFactory.FILE_WRITER_TYPE ); metricWriterConfig.put( MetricWriter.CFG_FILENAME_KEY, metricSnapshotFileName ); this._metricWriter = MetricWriterFactory.createMetricWriter( metricWriterConfig.getString( MetricWriter.CFG_TYPE_KEY ), metricWriterConfig ); } } } // 11 Initialize the object pool - by default it remains empty unless one of the concrete operations // uses it. if( config.has( ScenarioTrack.CFG_OBJECT_POOL_MAX_SIZE ) ) { this._objPool = new ObjectPool( config.getLong( ScenarioTrack.CFG_OBJECT_POOL_MAX_SIZE ) ); } else { this._objPool = new ObjectPool( ScenarioTrack.DEFAULT_OBJECT_POOL_MAX_SIZE ); } this._objPool.setTrackName( this._name ); // 12 Configure the response time sampler if( config.has( ScenarioTrack.CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL ) ) this._meanResponseTimeSamplingInterval = config.getLong( ScenarioTrack.CFG_MEAN_RESPONSE_TIME_SAMPLE_INTERVAL ); // 13 Configure the maxUsers if specified if( config.has( ScenarioTrack.CFG_MAX_USERS ) ) this._maxUsersFromConfig = config.getInt( ScenarioTrack.CFG_MAX_USERS ); // 14 Look for a load generation strategy and optional params if they exist if( config.has( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_KEY ) ) { this._loadGenerationStrategyClassName = config.getString( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_KEY ); // Check for parameters if( config.has( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY ) ) this._loadGenerationStrategyParams = config.getJSONObject( ScenarioTrack.CFG_LOAD_GENERATION_STRATEGY_PARAMS_KEY ); else this._loadGenerationStrategyParams = new JSONObject(); } else { this._loadGenerationStrategyClassName = ScenarioTrack.DEFAULT_LOAD_GENERATION_STRATEGY_CLASS; this._loadGenerationStrategyParams = new JSONObject(); } // 15 Look for a resource path if (config.has(ScenarioTrack.CFG_RESOURCE_PATH)) { this._resourcePath = config.getString(ScenarioTrack.CFG_RESOURCE_PATH); } }
diff --git a/source/com/mucommander/ui/dialog/file/PackDialog.java b/source/com/mucommander/ui/dialog/file/PackDialog.java index 94c26cf2..46160146 100644 --- a/source/com/mucommander/ui/dialog/file/PackDialog.java +++ b/source/com/mucommander/ui/dialog/file/PackDialog.java @@ -1,253 +1,253 @@ /* * This file is part of muCommander, http://www.mucommander.com * Copyright (C) 2002-2009 Maxence Bernard * * muCommander 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. * * muCommander 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 com.mucommander.ui.dialog.file; import com.mucommander.file.archiver.Archiver; import com.mucommander.file.util.FileSet; import com.mucommander.file.util.PathUtils; import com.mucommander.job.ArchiveJob; import com.mucommander.text.Translator; import com.mucommander.ui.action.ActionProperties; import com.mucommander.ui.action.impl.PackAction; import com.mucommander.ui.dialog.DialogToolkit; import com.mucommander.ui.dialog.QuestionDialog; import com.mucommander.ui.layout.YBoxPanel; import com.mucommander.ui.main.MainFrame; import com.mucommander.ui.main.table.FileTable; import com.mucommander.ui.text.FilePathField; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; /** * This dialog allows the user to pack marked files to an archive file of a selected format (Zip, TAR, ...) * and add an optional comment to the archive (for the formats that support it). * * @author Maxence Bernard */ public class PackDialog extends JobDialog implements ActionListener, ItemListener { private JTextField filePathField; private JComboBox formatsComboBox; private int formats[]; private JTextArea commentArea; private JButton okButton; private JButton cancelButton; /** Used to keep track of the last selected archive format. */ private int oldFormatIndex; // Dialog's width has to be at least 240 private final static Dimension MINIMUM_DIALOG_DIMENSION = new Dimension(320,0); // Dialog's width has to be at most 320 private final static Dimension MAXIMUM_DIALOG_DIMENSION = new Dimension(400,10000); /** Last archive format used (Zip initially), selected by default when this dialog is created */ private static int lastFormat = Archiver.ZIP_FORMAT; public PackDialog(MainFrame mainFrame, FileSet files, boolean isShiftDown) { super(mainFrame, ActionProperties.getActionLabel(PackAction.Descriptor.ACTION_ID), files); // Retrieve available formats for single file or many file archives int nbFiles = files.size(); this.formats = Archiver.getFormats(nbFiles>1 || (nbFiles>0 && files.fileAt(0).isDirectory())); int nbFormats = formats.length; int initialFormat = formats[0]; // this value will only be used if last format is not available int initialFormatIndex = 0; // this value will only be used if last format is not available for(int i=0; i<nbFormats; i++) { if(formats[i]==lastFormat) { initialFormat = formats[i]; initialFormatIndex = i; break; } } oldFormatIndex = initialFormatIndex; Container contentPane = getContentPane(); YBoxPanel mainPanel = new YBoxPanel(5); JLabel label = new JLabel(Translator.get("pack_dialog_description")+" :"); mainPanel.add(label); FileTable activeTable = mainFrame.getInactiveTable(); String initialPath = (isShiftDown?"":activeTable.getCurrentFolder().getAbsolutePath(true)); String fileName; // Computes the archive's default name: // - if it only contains one file, uses that file's name. // - if it contains more than one file, uses the FileSet's parent folder's name. if(files.size() == 1) fileName = files.fileAt(0).getNameWithoutExtension(); else if(files.getBaseFolder().getParent() != null) fileName = files.getBaseFolder().getName(); else fileName = ""; // Create a path field with auto-completion capabilities filePathField = new FilePathField(initialPath + fileName + "." + Archiver.getFormatExtension(initialFormat)); // Selects the file name. filePathField.setSelectionStart(initialPath.length()); filePathField.setSelectionEnd(initialPath.length() + fileName.length()); mainPanel.add(filePathField); mainPanel.addSpace(10); // Archive formats combo box JPanel tempPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); tempPanel.add(new JLabel(Translator.get("pack_dialog.archive_format"))); this.formatsComboBox = new JComboBox(); for(int i=0; i<nbFormats; i++) formatsComboBox.addItem(Archiver.getFormatName(formats[i])); formatsComboBox.setSelectedIndex(initialFormatIndex); formatsComboBox.addItemListener(this); tempPanel.add(formatsComboBox); mainPanel.add(tempPanel); mainPanel.addSpace(10); // Comment area, enabled only if selected archive format has comment support label = new JLabel(Translator.get("comment")); mainPanel.add(label); commentArea = new JTextArea(); commentArea.setRows(4); mainPanel.add(commentArea); mainPanel.addSpace(10); // Create file details button and OK/cancel buttons and lay them out a single row JPanel fileDetailsPanel = createFileDetailsPanel(); - okButton = new JButton(Translator.get("pack_dialog.pack")); + okButton = new JButton(Translator.get("pack")); cancelButton = new JButton(Translator.get("cancel")); mainPanel.add(createButtonsPanel(createFileDetailsButton(fileDetailsPanel), DialogToolkit.createOKCancelPanel(okButton, cancelButton, getRootPane(), this))); mainPanel.add(fileDetailsPanel); // Text field will receive initial focus setInitialFocusComponent(filePathField); contentPane.add(mainPanel, BorderLayout.NORTH); // Packs dialog setMinimumSize(MINIMUM_DIALOG_DIMENSION); setMaximumSize(MAXIMUM_DIALOG_DIMENSION); } //////////////////////////// // ActionListener methods // //////////////////////////// public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source==okButton) { // Start by disposing the dialog dispose(); // Check that destination file can be resolved String filePath = filePathField.getText(); // TODO: move those I/O bound calls to job as they can lock the main thread PathUtils.ResolvedDestination resolvedDest = PathUtils.resolveDestination(filePath, mainFrame.getActiveTable().getCurrentFolder()); if (resolvedDest==null || resolvedDest.getDestinationType()==PathUtils.ResolvedDestination.EXISTING_FOLDER) { // Incorrect destination QuestionDialog dialog = new QuestionDialog(mainFrame, Translator.get("pack_dialog.error_title"), Translator.get("invalid_path", filePath), mainFrame, new String[] {Translator.get("ok")}, new int[] {0}, 0); dialog.getActionValue(); return; } // Start packing ProgressDialog progressDialog = new ProgressDialog(mainFrame, Translator.get("pack_dialog.packing")); int format = formats[formatsComboBox.getSelectedIndex()]; ArchiveJob archiveJob = new ArchiveJob(progressDialog, mainFrame, files, resolvedDest.getDestinationFile(), format, Archiver.formatSupportsComment(format)?commentArea.getText():null); progressDialog.start(archiveJob); // Remember last format used, for next time this dialog is invoked lastFormat = format; } else if (source==cancelButton) { // Simply dispose the dialog dispose(); } } ////////////////////////// // ItemListener methods // ////////////////////////// public void itemStateChanged(ItemEvent e) { int newFormatIndex; // Updates the GUI if, and only if, the format selection has changed. if(oldFormatIndex != (newFormatIndex = formatsComboBox.getSelectedIndex())) { String fileName = filePathField.getText(); // Name of the destination archive file. String oldFormatExtension = Archiver.getFormatExtension(formats[oldFormatIndex]); // Old/current format's extension if(fileName.endsWith("." + oldFormatExtension)) { int selectionStart; int selectionEnd; // Saves the old selection. selectionStart = filePathField.getSelectionStart(); selectionEnd = filePathField.getSelectionEnd(); // Computes the new file name. fileName = fileName.substring(0, fileName.length() - oldFormatExtension.length()) + Archiver.getFormatExtension(formats[newFormatIndex]); // Makes sure that the selection stays somewhat coherent. if(selectionEnd == filePathField.getText().length()) selectionEnd = fileName.length(); // Resets the file path field. filePathField.setText(fileName); filePathField.setSelectionStart(selectionStart); filePathField.setSelectionEnd(selectionEnd); } commentArea.setEnabled(Archiver.formatSupportsComment(formats[formatsComboBox.getSelectedIndex()])); oldFormatIndex = newFormatIndex; } // Transfer focus back to the text field filePathField.requestFocus(); } }
true
true
public PackDialog(MainFrame mainFrame, FileSet files, boolean isShiftDown) { super(mainFrame, ActionProperties.getActionLabel(PackAction.Descriptor.ACTION_ID), files); // Retrieve available formats for single file or many file archives int nbFiles = files.size(); this.formats = Archiver.getFormats(nbFiles>1 || (nbFiles>0 && files.fileAt(0).isDirectory())); int nbFormats = formats.length; int initialFormat = formats[0]; // this value will only be used if last format is not available int initialFormatIndex = 0; // this value will only be used if last format is not available for(int i=0; i<nbFormats; i++) { if(formats[i]==lastFormat) { initialFormat = formats[i]; initialFormatIndex = i; break; } } oldFormatIndex = initialFormatIndex; Container contentPane = getContentPane(); YBoxPanel mainPanel = new YBoxPanel(5); JLabel label = new JLabel(Translator.get("pack_dialog_description")+" :"); mainPanel.add(label); FileTable activeTable = mainFrame.getInactiveTable(); String initialPath = (isShiftDown?"":activeTable.getCurrentFolder().getAbsolutePath(true)); String fileName; // Computes the archive's default name: // - if it only contains one file, uses that file's name. // - if it contains more than one file, uses the FileSet's parent folder's name. if(files.size() == 1) fileName = files.fileAt(0).getNameWithoutExtension(); else if(files.getBaseFolder().getParent() != null) fileName = files.getBaseFolder().getName(); else fileName = ""; // Create a path field with auto-completion capabilities filePathField = new FilePathField(initialPath + fileName + "." + Archiver.getFormatExtension(initialFormat)); // Selects the file name. filePathField.setSelectionStart(initialPath.length()); filePathField.setSelectionEnd(initialPath.length() + fileName.length()); mainPanel.add(filePathField); mainPanel.addSpace(10); // Archive formats combo box JPanel tempPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); tempPanel.add(new JLabel(Translator.get("pack_dialog.archive_format"))); this.formatsComboBox = new JComboBox(); for(int i=0; i<nbFormats; i++) formatsComboBox.addItem(Archiver.getFormatName(formats[i])); formatsComboBox.setSelectedIndex(initialFormatIndex); formatsComboBox.addItemListener(this); tempPanel.add(formatsComboBox); mainPanel.add(tempPanel); mainPanel.addSpace(10); // Comment area, enabled only if selected archive format has comment support label = new JLabel(Translator.get("comment")); mainPanel.add(label); commentArea = new JTextArea(); commentArea.setRows(4); mainPanel.add(commentArea); mainPanel.addSpace(10); // Create file details button and OK/cancel buttons and lay them out a single row JPanel fileDetailsPanel = createFileDetailsPanel(); okButton = new JButton(Translator.get("pack_dialog.pack")); cancelButton = new JButton(Translator.get("cancel")); mainPanel.add(createButtonsPanel(createFileDetailsButton(fileDetailsPanel), DialogToolkit.createOKCancelPanel(okButton, cancelButton, getRootPane(), this))); mainPanel.add(fileDetailsPanel); // Text field will receive initial focus setInitialFocusComponent(filePathField); contentPane.add(mainPanel, BorderLayout.NORTH); // Packs dialog setMinimumSize(MINIMUM_DIALOG_DIMENSION); setMaximumSize(MAXIMUM_DIALOG_DIMENSION); }
public PackDialog(MainFrame mainFrame, FileSet files, boolean isShiftDown) { super(mainFrame, ActionProperties.getActionLabel(PackAction.Descriptor.ACTION_ID), files); // Retrieve available formats for single file or many file archives int nbFiles = files.size(); this.formats = Archiver.getFormats(nbFiles>1 || (nbFiles>0 && files.fileAt(0).isDirectory())); int nbFormats = formats.length; int initialFormat = formats[0]; // this value will only be used if last format is not available int initialFormatIndex = 0; // this value will only be used if last format is not available for(int i=0; i<nbFormats; i++) { if(formats[i]==lastFormat) { initialFormat = formats[i]; initialFormatIndex = i; break; } } oldFormatIndex = initialFormatIndex; Container contentPane = getContentPane(); YBoxPanel mainPanel = new YBoxPanel(5); JLabel label = new JLabel(Translator.get("pack_dialog_description")+" :"); mainPanel.add(label); FileTable activeTable = mainFrame.getInactiveTable(); String initialPath = (isShiftDown?"":activeTable.getCurrentFolder().getAbsolutePath(true)); String fileName; // Computes the archive's default name: // - if it only contains one file, uses that file's name. // - if it contains more than one file, uses the FileSet's parent folder's name. if(files.size() == 1) fileName = files.fileAt(0).getNameWithoutExtension(); else if(files.getBaseFolder().getParent() != null) fileName = files.getBaseFolder().getName(); else fileName = ""; // Create a path field with auto-completion capabilities filePathField = new FilePathField(initialPath + fileName + "." + Archiver.getFormatExtension(initialFormat)); // Selects the file name. filePathField.setSelectionStart(initialPath.length()); filePathField.setSelectionEnd(initialPath.length() + fileName.length()); mainPanel.add(filePathField); mainPanel.addSpace(10); // Archive formats combo box JPanel tempPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); tempPanel.add(new JLabel(Translator.get("pack_dialog.archive_format"))); this.formatsComboBox = new JComboBox(); for(int i=0; i<nbFormats; i++) formatsComboBox.addItem(Archiver.getFormatName(formats[i])); formatsComboBox.setSelectedIndex(initialFormatIndex); formatsComboBox.addItemListener(this); tempPanel.add(formatsComboBox); mainPanel.add(tempPanel); mainPanel.addSpace(10); // Comment area, enabled only if selected archive format has comment support label = new JLabel(Translator.get("comment")); mainPanel.add(label); commentArea = new JTextArea(); commentArea.setRows(4); mainPanel.add(commentArea); mainPanel.addSpace(10); // Create file details button and OK/cancel buttons and lay them out a single row JPanel fileDetailsPanel = createFileDetailsPanel(); okButton = new JButton(Translator.get("pack")); cancelButton = new JButton(Translator.get("cancel")); mainPanel.add(createButtonsPanel(createFileDetailsButton(fileDetailsPanel), DialogToolkit.createOKCancelPanel(okButton, cancelButton, getRootPane(), this))); mainPanel.add(fileDetailsPanel); // Text field will receive initial focus setInitialFocusComponent(filePathField); contentPane.add(mainPanel, BorderLayout.NORTH); // Packs dialog setMinimumSize(MINIMUM_DIALOG_DIMENSION); setMaximumSize(MAXIMUM_DIALOG_DIMENSION); }
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/PickerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/PickerTest.java index 6f3ef7402..625d07c8f 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/PickerTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/director/PickerTest.java @@ -1,104 +1,104 @@ /******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.p2.tests.director; import junit.framework.TestCase; import org.eclipse.equinox.internal.p2.director.Picker; import org.eclipse.equinox.p2.metadata.*; import org.eclipse.osgi.service.resolver.VersionRange; import org.osgi.framework.Version; /** * Testing of the {@link Picker} class. */ public class PickerTest extends TestCase { InstallableUnit unitVersion5; private Picker picker; public PickerTest() { super(""); //$NON-NLS-1$ } public PickerTest(String name) { super(name); } private RequiredCapability[] createRequiredCapabilities(String namespace, String name, VersionRange range, String filter) { return new RequiredCapability[] {new RequiredCapability(namespace, name, range, filter, false, false)}; } protected void setUp() throws Exception { super.setUp(); Version version = new Version(5, 0, 0); //create some sample IUs to be available for the picker unitVersion5 = new InstallableUnit(); unitVersion5.setId("required"); unitVersion5.setVersion(version); unitVersion5.setCapabilities(new ProvidedCapability[] {new ProvidedCapability("test.capability", "test", version)}); InstallableUnit[] units = new InstallableUnit[] {unitVersion5}; picker = new Picker(units, null); } /** * Tests picking an IU that requires a capability, and the available * provided capability is above the required capability's version range. */ public void testRequiredBelowVersionRange() { //an IU whose required capability falls outside available range RequiredCapability[] required = createRequiredCapabilities("test.capability", "test", new VersionRange("[2.0,5.0)"), null); IInstallableUnit[][] result = picker.findInstallableUnit(null, null, required, false); assertEquals("1.0", 0, result[0].length + result[1].length); } /** * Tests picking an IU that requires a capability, and the available * provided capability is above the required capability's version range. */ public void testRequiredWithinVersionRange() { //in middle of range RequiredCapability[] required = createRequiredCapabilities("test.capability", "test", new VersionRange("[2.0,6.0)"), null); - IInstallableUnit[][] result = picker.findInstallableUnit(null, null, required, false); + IInstallableUnit[] result = picker.findInstallableUnit(null, null, required, false)[1]; assertEquals("1.0", 1, result.length); assertEquals("1.1", unitVersion5, result[0]); //on lower bound required = createRequiredCapabilities("test.capability", "test", new VersionRange("[5.0,6.0)"), null); - result = picker.findInstallableUnit(null, null, required, false); - assertEquals("1.0", 1, result[0].length + result[1].length); - assertEquals("1.1", unitVersion5, result[1][0]); + result = picker.findInstallableUnit(null, null, required, false)[1]; + assertEquals("1.0", 1, result.length); + assertEquals("1.1", unitVersion5, result[0]); //on upper bound required = createRequiredCapabilities("test.capability", "test", new VersionRange("[1.0,5.0]"), null); - result = picker.findInstallableUnit(null, null, required, false); - assertEquals("1.0", 1, result[0].length + result[1].length); - assertEquals("1.1", unitVersion5, result[1][0]); + result = picker.findInstallableUnit(null, null, required, false)[1]; + assertEquals("1.0", 1, result.length); + assertEquals("1.1", unitVersion5, result[0]); } /** * Tests picking an IU that requires a capability, and the available * provided capability is above the required capability's version range. */ public void testRequiredAboveVersionRange() { //an IU whose required capability falls outside available range RequiredCapability[] required = createRequiredCapabilities("test.capability", "test", new VersionRange("[5.1,6.0)"), null); IInstallableUnit[][] result = picker.findInstallableUnit(null, null, required, false); assertEquals("1.0", 0, result[0].length + result[1].length); } }
false
true
public void testRequiredWithinVersionRange() { //in middle of range RequiredCapability[] required = createRequiredCapabilities("test.capability", "test", new VersionRange("[2.0,6.0)"), null); IInstallableUnit[][] result = picker.findInstallableUnit(null, null, required, false); assertEquals("1.0", 1, result.length); assertEquals("1.1", unitVersion5, result[0]); //on lower bound required = createRequiredCapabilities("test.capability", "test", new VersionRange("[5.0,6.0)"), null); result = picker.findInstallableUnit(null, null, required, false); assertEquals("1.0", 1, result[0].length + result[1].length); assertEquals("1.1", unitVersion5, result[1][0]); //on upper bound required = createRequiredCapabilities("test.capability", "test", new VersionRange("[1.0,5.0]"), null); result = picker.findInstallableUnit(null, null, required, false); assertEquals("1.0", 1, result[0].length + result[1].length); assertEquals("1.1", unitVersion5, result[1][0]); }
public void testRequiredWithinVersionRange() { //in middle of range RequiredCapability[] required = createRequiredCapabilities("test.capability", "test", new VersionRange("[2.0,6.0)"), null); IInstallableUnit[] result = picker.findInstallableUnit(null, null, required, false)[1]; assertEquals("1.0", 1, result.length); assertEquals("1.1", unitVersion5, result[0]); //on lower bound required = createRequiredCapabilities("test.capability", "test", new VersionRange("[5.0,6.0)"), null); result = picker.findInstallableUnit(null, null, required, false)[1]; assertEquals("1.0", 1, result.length); assertEquals("1.1", unitVersion5, result[0]); //on upper bound required = createRequiredCapabilities("test.capability", "test", new VersionRange("[1.0,5.0]"), null); result = picker.findInstallableUnit(null, null, required, false)[1]; assertEquals("1.0", 1, result.length); assertEquals("1.1", unitVersion5, result[0]); }
diff --git a/dbproject/src/my/triviagame/bll/MatchQuestion.java b/dbproject/src/my/triviagame/bll/MatchQuestion.java index 2a126a2..575d55b 100644 --- a/dbproject/src/my/triviagame/bll/MatchQuestion.java +++ b/dbproject/src/my/triviagame/bll/MatchQuestion.java @@ -1,56 +1,56 @@ package my.triviagame.bll; import com.sun.tools.javac.util.Pair; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * TODO class-level documentation. */ public class MatchQuestion extends Question{ public MatchQuestion(String questionTitle, MatchAnswer answer) { super(questionTitle, answer); this.left = new ArrayList<String>(4); this.right = new ArrayList<String>(4); for (Pair<String, String> pair: answer.getPairs()) { this.left.add(pair.fst); this.right.add(pair.snd); } Collections.shuffle(this.left); Collections.shuffle(this.right); } private List<String> left; private List<String> right; @Override public int getScore(IAnswer answer) { int score = 0; for (Pair<String, String> actualPair: ((MatchAnswer)answer).getPairs()) { for (Pair<String, String> expectedPair: (((MatchAnswer)this.correctAnswer).getPairs())) { - if (actualPair.fst.equals(expectedPair.fst) && actualPair.equals(expectedPair.snd)) { + if (actualPair.fst.equals(expectedPair.fst) && actualPair.snd.equals(expectedPair.snd)) { score++; break; } } } return score; } @Override public IAnswer getCorrectAnswer() { return this.correctAnswer; } public List<String> getLeftItems() { return left; } public List<String> getRightItems() { return right; } }
true
true
public int getScore(IAnswer answer) { int score = 0; for (Pair<String, String> actualPair: ((MatchAnswer)answer).getPairs()) { for (Pair<String, String> expectedPair: (((MatchAnswer)this.correctAnswer).getPairs())) { if (actualPair.fst.equals(expectedPair.fst) && actualPair.equals(expectedPair.snd)) { score++; break; } } } return score; }
public int getScore(IAnswer answer) { int score = 0; for (Pair<String, String> actualPair: ((MatchAnswer)answer).getPairs()) { for (Pair<String, String> expectedPair: (((MatchAnswer)this.correctAnswer).getPairs())) { if (actualPair.fst.equals(expectedPair.fst) && actualPair.snd.equals(expectedPair.snd)) { score++; break; } } } return score; }
diff --git a/ui/GUIHelp.java b/ui/GUIHelp.java index aec05b2..b49cc98 100644 --- a/ui/GUIHelp.java +++ b/ui/GUIHelp.java @@ -1,107 +1,108 @@ /* GUIHelp.java * * EduMIPS64 Help * (c) 2006 Vanni Rizzo G. * * This file is part of the EduMIPS64 project, and is released under the GNU * General Public License. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edumips64.ui; import java.awt.Dimension; import java.awt.Window; import java.net.URL; import java.net.URLClassLoader; import java.util.Vector; import javax.help.BadIDException; import javax.help.DefaultHelpBroker; import javax.help.HelpBroker; import javax.help.HelpSet; import javax.help.HelpSetException; import javax.swing.JOptionPane; import edumips64.Main; import edumips64.utils.CurrentLocale; /** * This class controls the Edumips64 user guide. */ public class GUIHelp { public final static String HELP_DEFAULT = "EduMIPS64Help"; /** * The help broker used to display Edumips's help. */ private static HelpBroker helpBroker; private static URL url,HSurl; private static URL[] parseURLs(String s){ Vector<URL> vector = new Vector<URL>(); try{ URL url = new URL(s); vector.addElement(url); } catch(Exception exception){ System.err.println("cannot create URL for " + s); } URL aurl[] = new URL[vector.size()]; vector.copyInto(aurl); return aurl; } /** * Shows the Edumips64 help window. If the help system was not initialized properly, shows an error dialog * instead. * * @param parent * the parent that owns this help dialog * @param helpId * the help ID to display (an invalid ID will result in the top level help topic being * displayed) */ public static void showHelp(Window parent, String helpId) { HSurl = Main.class.getResource(CurrentLocale.getString("HELPDIR") + "/"); String s = HSurl.getProtocol()+ ":" + HSurl.getPath().replace("%20", " "); String s1 = CurrentLocale.getString("HELPSET"); try { URL aurl[] = GUIHelp.parseURLs(s); URLClassLoader urlclassloader = new URLClassLoader(aurl); url = HelpSet.findHelpSet(urlclassloader, s1); HelpSet helpset = new HelpSet(urlclassloader, url); helpBroker = helpset.createHelpBroker(); helpBroker.initPresentation(); helpBroker.setSize(new Dimension(800,600)); ((DefaultHelpBroker) helpBroker).setActivationWindow(parent); helpBroker.initPresentation(); helpBroker.setSize(helpBroker.getSize()); helpBroker.setDisplayed(true); } catch(HelpSetException helpsetexception) { System.err.println("Could not create HelpSet for " + url); + System.err.println(helpsetexception); } catch (BadIDException bie) { helpBroker.setCurrentID(HELP_DEFAULT); } } }
true
true
public static void showHelp(Window parent, String helpId) { HSurl = Main.class.getResource(CurrentLocale.getString("HELPDIR") + "/"); String s = HSurl.getProtocol()+ ":" + HSurl.getPath().replace("%20", " "); String s1 = CurrentLocale.getString("HELPSET"); try { URL aurl[] = GUIHelp.parseURLs(s); URLClassLoader urlclassloader = new URLClassLoader(aurl); url = HelpSet.findHelpSet(urlclassloader, s1); HelpSet helpset = new HelpSet(urlclassloader, url); helpBroker = helpset.createHelpBroker(); helpBroker.initPresentation(); helpBroker.setSize(new Dimension(800,600)); ((DefaultHelpBroker) helpBroker).setActivationWindow(parent); helpBroker.initPresentation(); helpBroker.setSize(helpBroker.getSize()); helpBroker.setDisplayed(true); } catch(HelpSetException helpsetexception) { System.err.println("Could not create HelpSet for " + url); } catch (BadIDException bie) { helpBroker.setCurrentID(HELP_DEFAULT); } }
public static void showHelp(Window parent, String helpId) { HSurl = Main.class.getResource(CurrentLocale.getString("HELPDIR") + "/"); String s = HSurl.getProtocol()+ ":" + HSurl.getPath().replace("%20", " "); String s1 = CurrentLocale.getString("HELPSET"); try { URL aurl[] = GUIHelp.parseURLs(s); URLClassLoader urlclassloader = new URLClassLoader(aurl); url = HelpSet.findHelpSet(urlclassloader, s1); HelpSet helpset = new HelpSet(urlclassloader, url); helpBroker = helpset.createHelpBroker(); helpBroker.initPresentation(); helpBroker.setSize(new Dimension(800,600)); ((DefaultHelpBroker) helpBroker).setActivationWindow(parent); helpBroker.initPresentation(); helpBroker.setSize(helpBroker.getSize()); helpBroker.setDisplayed(true); } catch(HelpSetException helpsetexception) { System.err.println("Could not create HelpSet for " + url); System.err.println(helpsetexception); } catch (BadIDException bie) { helpBroker.setCurrentID(HELP_DEFAULT); } }
diff --git a/hazelcast/src/main/java/com/hazelcast/core/ItemEvent.java b/hazelcast/src/main/java/com/hazelcast/core/ItemEvent.java index 2a6d3c68..edcd2059 100644 --- a/hazelcast/src/main/java/com/hazelcast/core/ItemEvent.java +++ b/hazelcast/src/main/java/com/hazelcast/core/ItemEvent.java @@ -1,51 +1,51 @@ /* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.core; import java.util.EventObject; public class ItemEvent<E> extends EventObject { private final E item; private final ItemEventType eventType; public ItemEvent(String name, int eventType, E item) { this(name, ItemEventType.getByType(eventType), item); } public ItemEvent(String name, ItemEventType itemEventType, E item) { super(name); this.item = item; this.eventType = itemEventType; } public ItemEventType getEventType() { return eventType; } public E getItem() { return item; } @Override public String toString() { return "ItemEvent{" + "event=" + eventType + - ", item=" + item + + ", item=" + getItem() + "} "; } }
true
true
public String toString() { return "ItemEvent{" + "event=" + eventType + ", item=" + item + "} "; }
public String toString() { return "ItemEvent{" + "event=" + eventType + ", item=" + getItem() + "} "; }
diff --git a/api/src/main/java/org/openmrs/aop/RequiredDataAdvice.java b/api/src/main/java/org/openmrs/aop/RequiredDataAdvice.java index 4979a471..7c474881 100644 --- a/api/src/main/java/org/openmrs/aop/RequiredDataAdvice.java +++ b/api/src/main/java/org/openmrs/aop/RequiredDataAdvice.java @@ -1,332 +1,332 @@ /** * 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.aop; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import org.openmrs.OpenmrsObject; import org.openmrs.Retireable; import org.openmrs.User; import org.openmrs.Voidable; import org.openmrs.api.APIException; import org.openmrs.api.context.Context; import org.openmrs.api.handler.ConceptNameSaveHandler; import org.openmrs.api.handler.RequiredDataHandler; import org.openmrs.api.handler.RetireHandler; import org.openmrs.api.handler.SaveHandler; import org.openmrs.api.handler.UnretireHandler; import org.openmrs.api.handler.UnvoidHandler; import org.openmrs.api.handler.VoidHandler; import org.openmrs.util.HandlerUtil; import org.openmrs.util.Reflect; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.util.StringUtils; /** * This class provides the AOP around each save, (un)void, and (un)retire method in the service * layer so that the required data (like creator, dateChanged, dateVoided, etc) can be set * automatically and the developer doesn't have to worry about doing it explicitly in the service * impl method. <br/> * <br/> * See /metadata/api/spring/applicationContext-service.xml for the mapping of this bean. <br/> * <br/> * For an Openmrs Service to use this AOP advice class and take advantage of its automatic variable * setting, it must have "&lt;ref local="requiredDataInterceptor"/>" in its "preInterceptors".<br/> * <br/> * By default, this should take care of any child collections on the object being acted on. Any * child collection of {@link OpenmrsObject}s will get "handled" (i.e., void data set up, save data * set up, or retire data set up, etc) by the same handler type that the parent object was handled * with.<br/> * <br/> * To add a new action to happen for a save* method, create a new class that extends * {@link RequiredDataHandler}. Add any <b>unique</b> code that needs to be done automatically * before the save. See {@link ConceptNameSaveHandler} as an example. (The code should be * <b>unique</b> because all other {@link SaveHandler}s will still be called <i>in addition to</i> * your new handler.) Be sure to add the {@link org.openmrs.annotation.Handler} annotation (like * "@Handler(supports=YourPojoThatHasUniqueSaveNeeds.class)") to your class so that it is picked up * by Spring automatically.<br/> * <br/> * To add a new action for a void* or retire* method, extend the {@link VoidHandler}/ * {@link RetireHandler} class and override the handle method. Do not call super, because that code * would then be run twice because both handlers are registered. Be sure to add the * {@link org.openmrs.annotation.Handler} annotation (like * "@Handler(supports=YourPojoThatHasUniqueSaveNeeds.class)") to your class so that it is picked up * by Spring automatically. * * @see RequiredDataHandler * @see SaveHandler * @see VoidHandler * @since 1.5 */ public class RequiredDataAdvice implements MethodBeforeAdvice { // TODO put this somewhere and do it right and add class name, etc // TODO do this with an annotation on the field? or on the method? protected static List<String> fieldAccess = new ArrayList<String>(); //private static Log log = LogFactory.getLog(RequiredDataAdvice.class); static { fieldAccess.add("Concept.answers"); fieldAccess.add("Concept.names"); fieldAccess.add("Encounter.obs"); fieldAccess.add("Program.allWorkflows"); fieldAccess.add("Obs.groupMembers"); } /** * @see org.springframework.aop.MethodBeforeAdvice#before(java.lang.reflect.Method, * java.lang.Object[], java.lang.Object) * @should not fail on update method with no arguments */ @SuppressWarnings("unchecked") public void before(Method method, Object[] args, Object target) throws Throwable { String methodName = method.getName(); // the "create" is there to cover old deprecated methods since AOP doesn't occur // on method calls within a class, only on calls to methods from external classes to methods // "update" is not an option here because there are multiple methods that start with "update" but is // not updating the primary argument. eg: ConceptService.updateConceptWord(Concept) if (methodName.startsWith("save") || methodName.startsWith("create")) { // skip out early if there are no arguments if (args == null || args.length == 0) return; Object mainArgument = args[0]; // fail early on a null parameter if (mainArgument == null) return; // if the first argument is an OpenmrsObject, handle it now Reflect reflect = new Reflect(OpenmrsObject.class); if (reflect.isSuperClass(mainArgument)) { // if a second argument exists, pass that to the save handler as well // (with current code, it means we're either in an obs save or a user save) String other = null; - if (args.length > 1) + if (args.length > 1 && args[1] instanceof String) other = (String) args[1]; recursivelyHandle(SaveHandler.class, (OpenmrsObject) mainArgument, other); } // if the first argument is a list of openmrs objects, handle them all now else if (Reflect.isCollection(mainArgument) && isOpenmrsObjectCollection(mainArgument)) { // if a second argument exists, pass that to the save handler as well // (with current code, it means we're either in an obs save or a user save) String other = null; if (args.length > 1) other = (String) args[1]; Collection<OpenmrsObject> openmrsObjects = (Collection<OpenmrsObject>) mainArgument; for (OpenmrsObject object : openmrsObjects) { recursivelyHandle(SaveHandler.class, object, other); } } } else if (methodName.startsWith("void")) { Voidable voidable = (Voidable) args[0]; String voidReason = (String) args[1]; recursivelyHandle(VoidHandler.class, voidable, voidReason); } else if (methodName.startsWith("unvoid")) { Voidable voidable = (Voidable) args[0]; Date originalDateVoided = voidable.getDateVoided(); recursivelyHandle(UnvoidHandler.class, voidable, Context.getAuthenticatedUser(), originalDateVoided, null, null); } else if (methodName.startsWith("retire")) { Retireable retirable = (Retireable) args[0]; String retireReason = (String) args[1]; recursivelyHandle(RetireHandler.class, retirable, retireReason); } else if (methodName.startsWith("unretire")) { Retireable retirable = (Retireable) args[0]; Date originalDateRetired = retirable.getDateRetired(); recursivelyHandle(UnretireHandler.class, retirable, Context.getAuthenticatedUser(), originalDateRetired, null, null); } } /** * Convenience method for {@link #recursivelyHandle(Class, OpenmrsObject, User, Date, String)}. * Calls that method with the current user and the current Date. * * @param <H> the type of Handler to get (should extend {@link RequiredDataHandler}) * @param handlerType the type of Handler to get (should extend {@link RequiredDataHandler}) * @param openmrsObject the object that is being acted upon * @param reason an optional second argument that was passed to the service method (usually a * void/retire reason) * @see #recursivelyHandle(Class, OpenmrsObject, User, Date, String) */ @SuppressWarnings("unchecked") public static <H extends RequiredDataHandler> void recursivelyHandle(Class<H> handlerType, OpenmrsObject openmrsObject, String reason) { recursivelyHandle(handlerType, openmrsObject, Context.getAuthenticatedUser(), new Date(), reason, null); } /** * This loops over all declared collections on the given object and all declared collections on * parent objects to use the given <code>handlerType</code>. * * @param <H> the type of Handler to get (should extend {@link RequiredDataHandler}) * @param handlerType the type of Handler to get (should extend {@link RequiredDataHandler}) * @param openmrsObject the object that is being acted upon * @param currentUser the current user to set recursively on the object * @param currentDate the date to set recursively on the object * @param other an optional second argument that was passed to the service method (usually a * void/retire reason) * @param alreadyHandled an optional list of objects that have already been handled and should * not be processed again. this is intended to prevent infinite recursion when * handling collection properties. * @see HandlerUtil#getHandlersForType(Class, Class) */ @SuppressWarnings("unchecked") public static <H extends RequiredDataHandler> void recursivelyHandle(Class<H> handlerType, OpenmrsObject openmrsObject, User currentUser, Date currentDate, String other, List<OpenmrsObject> alreadyHandled) { if (openmrsObject == null) return; Class<? extends OpenmrsObject> openmrsObjectClass = openmrsObject.getClass(); if (alreadyHandled == null) { alreadyHandled = new ArrayList<OpenmrsObject>(); } // fetch all handlers for the object being saved List<H> handlers = HandlerUtil.getHandlersForType(handlerType, openmrsObjectClass); // loop over all handlers, calling onSave on each for (H handler : handlers) { handler.handle(openmrsObject, currentUser, currentDate, other); } alreadyHandled.add(openmrsObject); Reflect reflect = new Reflect(OpenmrsObject.class); List<Field> allInheritedFields = reflect.getInheritedFields(openmrsObjectClass); // loop over all child collections of OpenmrsObjects and recursively save on those for (Field field : allInheritedFields) { if (reflect.isCollectionField(field)) { // the collection we'll be looping over Collection<OpenmrsObject> childCollection = getChildCollection(openmrsObject, field); if (childCollection != null) { for (Object collectionElement : childCollection) { if (!alreadyHandled.contains(collectionElement)) { recursivelyHandle(handlerType, (OpenmrsObject) collectionElement, currentUser, currentDate, other, alreadyHandled); } } } } } } /** * This method gets a child attribute off of an OpenmrsObject. It usually uses the getter for * the attribute, but can use the direct field (even if its private) if told to by the * {@link #fieldAccess} list. * * @param openmrsObject the object to get the collection off of * @param field the name of the field that is the collection * @return the actual collection of objects that is on the given <code>openmrsObject</code> * @should get value of given child collection on given field * @should be able to get private fields in fieldAccess list * @should throw APIException if getter method not found */ @SuppressWarnings("unchecked") protected static Collection<OpenmrsObject> getChildCollection(OpenmrsObject openmrsObject, Field field) { String fieldName = field.getName(); String classdotfieldname = field.getDeclaringClass().getSimpleName() + "." + fieldName; String getterName = "get" + StringUtils.capitalize(fieldName); try { // checks the fieldAccess list for something like "Concept.answers" if (fieldAccess.contains(classdotfieldname)) { boolean previousFieldAccessibility = field.isAccessible(); field.setAccessible(true); Collection<OpenmrsObject> childCollection = (Collection<OpenmrsObject>) field.get(openmrsObject); field.setAccessible(previousFieldAccessibility); return childCollection; } else { // access the field via its getter method Class<? extends OpenmrsObject> openmrsObjectClass = openmrsObject.getClass(); Method getterMethod = openmrsObjectClass.getMethod(getterName, (Class[]) null); return (Collection<OpenmrsObject>) getterMethod.invoke(openmrsObject, new Object[] {}); } } catch (IllegalAccessException e) { if (fieldAccess.contains(classdotfieldname)) throw new APIException("Unable to get field: " + fieldName + " on " + openmrsObject.getClass()); else throw new APIException("Unable to use getter method: " + getterName + " for field: " + fieldName + " on " + openmrsObject.getClass()); } catch (InvocationTargetException e) { throw new APIException("Unable to run getter method: " + getterName + " for field: " + fieldName + " on " + openmrsObject.getClass()); } catch (NoSuchMethodException e) { throw new APIException("Unable to find getter method: " + getterName + " for field: " + fieldName + " on " + openmrsObject.getClass()); } } /** * Checks the given {@link Class} to see if it A) is a {@link Collection}/{@link Set}/ * {@link List}, and B) contains {@link OpenmrsObject}s * * @param arg the actual object being passed in * @return true if it is a Collection of some kind of OpenmrsObject * @should return true if class is openmrsObject list * @should return true if class is openmrsObject set * @should return false if collection is empty regardless of type held */ @SuppressWarnings("unchecked") protected static boolean isOpenmrsObjectCollection(Object arg) { // kind of a hacky way to test for a list of openmrs objects, but java strips out // the generic info for 1.4 compat, so we don't have access to that info here try { Collection<Object> objects = (Collection<Object>) arg; if (!objects.isEmpty()) { @SuppressWarnings("unused") OpenmrsObject openmrsObject = (OpenmrsObject) objects.iterator().next(); } else { return false; } return true; } catch (ClassCastException ex) { // do nothing } return false; } }
true
true
public void before(Method method, Object[] args, Object target) throws Throwable { String methodName = method.getName(); // the "create" is there to cover old deprecated methods since AOP doesn't occur // on method calls within a class, only on calls to methods from external classes to methods // "update" is not an option here because there are multiple methods that start with "update" but is // not updating the primary argument. eg: ConceptService.updateConceptWord(Concept) if (methodName.startsWith("save") || methodName.startsWith("create")) { // skip out early if there are no arguments if (args == null || args.length == 0) return; Object mainArgument = args[0]; // fail early on a null parameter if (mainArgument == null) return; // if the first argument is an OpenmrsObject, handle it now Reflect reflect = new Reflect(OpenmrsObject.class); if (reflect.isSuperClass(mainArgument)) { // if a second argument exists, pass that to the save handler as well // (with current code, it means we're either in an obs save or a user save) String other = null; if (args.length > 1) other = (String) args[1]; recursivelyHandle(SaveHandler.class, (OpenmrsObject) mainArgument, other); } // if the first argument is a list of openmrs objects, handle them all now else if (Reflect.isCollection(mainArgument) && isOpenmrsObjectCollection(mainArgument)) { // if a second argument exists, pass that to the save handler as well // (with current code, it means we're either in an obs save or a user save) String other = null; if (args.length > 1) other = (String) args[1]; Collection<OpenmrsObject> openmrsObjects = (Collection<OpenmrsObject>) mainArgument; for (OpenmrsObject object : openmrsObjects) { recursivelyHandle(SaveHandler.class, object, other); } } } else if (methodName.startsWith("void")) { Voidable voidable = (Voidable) args[0]; String voidReason = (String) args[1]; recursivelyHandle(VoidHandler.class, voidable, voidReason); } else if (methodName.startsWith("unvoid")) { Voidable voidable = (Voidable) args[0]; Date originalDateVoided = voidable.getDateVoided(); recursivelyHandle(UnvoidHandler.class, voidable, Context.getAuthenticatedUser(), originalDateVoided, null, null); } else if (methodName.startsWith("retire")) { Retireable retirable = (Retireable) args[0]; String retireReason = (String) args[1]; recursivelyHandle(RetireHandler.class, retirable, retireReason); } else if (methodName.startsWith("unretire")) { Retireable retirable = (Retireable) args[0]; Date originalDateRetired = retirable.getDateRetired(); recursivelyHandle(UnretireHandler.class, retirable, Context.getAuthenticatedUser(), originalDateRetired, null, null); } }
public void before(Method method, Object[] args, Object target) throws Throwable { String methodName = method.getName(); // the "create" is there to cover old deprecated methods since AOP doesn't occur // on method calls within a class, only on calls to methods from external classes to methods // "update" is not an option here because there are multiple methods that start with "update" but is // not updating the primary argument. eg: ConceptService.updateConceptWord(Concept) if (methodName.startsWith("save") || methodName.startsWith("create")) { // skip out early if there are no arguments if (args == null || args.length == 0) return; Object mainArgument = args[0]; // fail early on a null parameter if (mainArgument == null) return; // if the first argument is an OpenmrsObject, handle it now Reflect reflect = new Reflect(OpenmrsObject.class); if (reflect.isSuperClass(mainArgument)) { // if a second argument exists, pass that to the save handler as well // (with current code, it means we're either in an obs save or a user save) String other = null; if (args.length > 1 && args[1] instanceof String) other = (String) args[1]; recursivelyHandle(SaveHandler.class, (OpenmrsObject) mainArgument, other); } // if the first argument is a list of openmrs objects, handle them all now else if (Reflect.isCollection(mainArgument) && isOpenmrsObjectCollection(mainArgument)) { // if a second argument exists, pass that to the save handler as well // (with current code, it means we're either in an obs save or a user save) String other = null; if (args.length > 1) other = (String) args[1]; Collection<OpenmrsObject> openmrsObjects = (Collection<OpenmrsObject>) mainArgument; for (OpenmrsObject object : openmrsObjects) { recursivelyHandle(SaveHandler.class, object, other); } } } else if (methodName.startsWith("void")) { Voidable voidable = (Voidable) args[0]; String voidReason = (String) args[1]; recursivelyHandle(VoidHandler.class, voidable, voidReason); } else if (methodName.startsWith("unvoid")) { Voidable voidable = (Voidable) args[0]; Date originalDateVoided = voidable.getDateVoided(); recursivelyHandle(UnvoidHandler.class, voidable, Context.getAuthenticatedUser(), originalDateVoided, null, null); } else if (methodName.startsWith("retire")) { Retireable retirable = (Retireable) args[0]; String retireReason = (String) args[1]; recursivelyHandle(RetireHandler.class, retirable, retireReason); } else if (methodName.startsWith("unretire")) { Retireable retirable = (Retireable) args[0]; Date originalDateRetired = retirable.getDateRetired(); recursivelyHandle(UnretireHandler.class, retirable, Context.getAuthenticatedUser(), originalDateRetired, null, null); } }
diff --git a/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/SWTContainerView.java b/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/SWTContainerView.java index 54090adf..5db04000 100644 --- a/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/SWTContainerView.java +++ b/plugins/org.eclipse.wazaabi.engine.swt/src/org/eclipse/wazaabi/engine/swt/views/SWTContainerView.java @@ -1,338 +1,340 @@ /******************************************************************************* * Copyright (c) 2008 Olivier Moises * * 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: * Olivier Moises- initial API and implementation *******************************************************************************/ package org.eclipse.wazaabi.engine.swt.views; import java.util.SortedMap; import java.util.TreeMap; import org.eclipse.emf.ecore.EClass; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.CoolBar; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.ExpandBar; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.Widget; import org.eclipse.wazaabi.engine.core.CoreSingletons; import org.eclipse.wazaabi.engine.core.editparts.AbstractComponentEditPart; import org.eclipse.wazaabi.engine.core.editparts.ContainerEditPart; import org.eclipse.wazaabi.engine.core.gef.EditPart; import org.eclipse.wazaabi.engine.core.views.AbstractComponentView; import org.eclipse.wazaabi.engine.core.views.ContainerView; import org.eclipse.wazaabi.engine.core.views.WidgetView; import org.eclipse.wazaabi.engine.swt.editparts.stylerules.managers.StackLayoutStyleRuleManager; import org.eclipse.wazaabi.mm.core.Orientation; import org.eclipse.wazaabi.mm.core.Position; import org.eclipse.wazaabi.mm.core.styles.BarLayoutRule; import org.eclipse.wazaabi.mm.core.styles.BlankRule; import org.eclipse.wazaabi.mm.core.styles.BooleanRule; import org.eclipse.wazaabi.mm.core.styles.CoreStylesPackage; import org.eclipse.wazaabi.mm.core.styles.ExpandLayoutRule; import org.eclipse.wazaabi.mm.core.styles.LayoutRule; import org.eclipse.wazaabi.mm.core.styles.SashFormLayoutRule; import org.eclipse.wazaabi.mm.core.styles.StackLayoutRule; import org.eclipse.wazaabi.mm.core.styles.StringRule; import org.eclipse.wazaabi.mm.core.styles.StyleRule; import org.eclipse.wazaabi.mm.core.styles.StyledElement; import org.eclipse.wazaabi.mm.core.styles.TabbedLayoutRule; import org.eclipse.wazaabi.mm.core.styles.impl.BarLayoutRuleImpl; import org.eclipse.wazaabi.mm.core.widgets.AbstractComponent; import org.eclipse.wazaabi.mm.swt.descriptors.SWTDescriptorsPackage; public class SWTContainerView extends SWTControlView implements ContainerView { public EClass getWidgetViewEClass() { return SWTDescriptorsPackage.Literals.COMPOSITE; } protected Widget createSWTWidget(Widget parent, int swtStyle, int index) { for (StyleRule rule : ((StyledElement) getHost().getModel()) .getStyleRules()) { if (rule instanceof BarLayoutRuleImpl && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { if (((BarLayoutRule) rule).isDraggable()) { // If the elements are draggable, then we need a coolbar CoolBar bar = new CoolBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); bar.setLocked(false); bar.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { Composite parent = (Composite) ((CoolBar) event.widget) .getParent(); if (parent != null) parent.layout(); } }); return bar; } else { // If the elements are not draggable, we need a toolbar return new ToolBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); } } else if (rule instanceof TabbedLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { CTabFolder folder = new CTabFolder( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); folder.setMaximizeVisible(((TabbedLayoutRule) rule) .isMaximizeVisible()); folder.setMinimizeVisible(((TabbedLayoutRule) rule) .isMinimizeVisible()); + folder.marginWidth = ((TabbedLayoutRule) rule).getMarginWidth(); + folder.marginHeight = ((TabbedLayoutRule) rule).getMarginHeight(); return folder; } else if (rule instanceof ExpandLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { ExpandBar expandBar = new ExpandBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost()) | SWT.V_SCROLL); return expandBar; } else if (rule instanceof SashFormLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { SashForm sashForm = new SashForm( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); return sashForm; } } StringRule containerTitleRule = (StringRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_VALUE_PROPERTY_NAME, null); BooleanRule containerBorderRule = (BooleanRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_BORDER_PROPERTY_NAME, null); Composite composite; if (containerTitleRule != null && containerBorderRule != null && !containerTitleRule.getValue().equalsIgnoreCase("")) { composite = new org.eclipse.swt.widgets.Group((Composite) parent, computeSWTCreationStyle(getHost())); ((Group) composite).setText(containerTitleRule.getValue()); } else { composite = new org.eclipse.swt.widgets.Composite( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); } return wrapForSpecificParent((Composite) parent, composite); } private LayoutRule currentLayoutRule = null; protected void setLayout(LayoutRule rule) { if (!(rule instanceof BlankRule)) currentLayoutRule = rule; else currentLayoutRule = (LayoutRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.LAYOUT_PROPERTY_NAME, CoreStylesPackage.Literals.LAYOUT_RULE); if (currentLayoutRule != null) CoreSingletons.getComposedStyleRuleManagerFactory() .platformSpecificRefresh(this, currentLayoutRule); else ((Composite) getSWTControl()).setLayout(null); revalidate(); } @Override protected int computeSWTCreationStyle(StyleRule rule) { if (ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName()) && rule instanceof SashFormLayoutRule) { if (((SashFormLayoutRule) rule).getOrientation() == Orientation.VERTICAL) return SWT.VERTICAL; return SWT.HORIZONTAL; } else if (ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName()) && rule instanceof TabbedLayoutRule) return ((TabbedLayoutRule) rule).getPosition() == Position.TOP ? SWT.TOP : SWT.BOTTOM; return super.computeSWTCreationStyle(rule); } @Override public void updateStyleRule(StyleRule rule) { if (rule == null) return; if (ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { if (rule instanceof LayoutRule) { setLayout((LayoutRule) rule); } else setLayout(null); } else super.updateStyleRule(rule); } @Override protected boolean needReCreateWidgetView(StyleRule styleRule, org.eclipse.swt.widgets.Widget widget) { if (styleRule == null) { return false; } if ((widget instanceof SashForm) && styleRule instanceof SashFormLayoutRule) { return !(isStyleBitCorrectlySet(widget, org.eclipse.swt.SWT.HORIZONTAL, Orientation.HORIZONTAL == ((SashFormLayoutRule) styleRule) .getOrientation()) & isStyleBitCorrectlySet(widget, org.eclipse.swt.SWT.VERTICAL, Orientation.VERTICAL == ((SashFormLayoutRule) styleRule) .getOrientation())); // we catch the border rule since apparently this SWT widget does // not manage it } else if (ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(styleRule .getPropertyName())) { if (styleRule instanceof BarLayoutRule) return !(getSWTWidget() instanceof ToolBar) && !(getSWTWidget() instanceof CoolBar); else if (styleRule instanceof TabbedLayoutRule) return !(getSWTWidget() instanceof CTabFolder); else if (styleRule instanceof ExpandLayoutRule) return !(getSWTWidget() instanceof ExpandBar); else if (styleRule instanceof SashFormLayoutRule) return !(getSWTWidget() instanceof SashForm); else return false; } else if (ContainerEditPart.TITLE_VALUE_PROPERTY_NAME.equals(styleRule .getPropertyName()) && styleRule instanceof StringRule && ((StringRule) styleRule).getValue() != null && !((StringRule) styleRule).getValue().equalsIgnoreCase("")) { BooleanRule containerBorderRule = (BooleanRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_BORDER_PROPERTY_NAME, null); if (containerBorderRule != null) { return true; } else { return super.needReCreateWidgetView(styleRule, widget); } } else if (ContainerEditPart.TITLE_BORDER_PROPERTY_NAME .equals(styleRule.getPropertyName()) && styleRule instanceof BooleanRule) { StringRule containerTitleRule = (StringRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_VALUE_PROPERTY_NAME, null); if (containerTitleRule != null && !containerTitleRule.getValue().equalsIgnoreCase("")) { return true; } else { return super.needReCreateWidgetView(styleRule, widget); } } else { return super.needReCreateWidgetView(styleRule, widget); } } /** * Indicates that this SWTComposite should make itself valid. Validation * includes invoking layout on a LayoutManager if present, and then * validating all children figures. Default validation uses pre-order, * depth-first ordering. */ @Override public void add(WidgetView view, int index) { // first we create the widget super.add(view, index); if (index != ((Composite) getSWTWidget()).getChildren().length - 1) if (view instanceof SWTControlView) reorderChild((SWTControlView) view, index); } public void reorderChild(AbstractComponentView child, int index) { if (!(((SWTWidgetView) child).getSWTWidget() instanceof org.eclipse.swt.widgets.Control) || ((SWTWidgetView) child).getSWTWidget().isDisposed()) return; // get the SWT Control child final org.eclipse.swt.widgets.Control childControl = (org.eclipse.swt.widgets.Control) ((SWTWidgetView) child) .getSWTWidget(); // get the SWT Composite (this) final org.eclipse.swt.widgets.Composite composite = (Composite) getSWTWidget(); EditPart parentModel = (EditPart) getHost(); if (parentModel instanceof ContainerEditPart && parentModel.getModel() != null) { StyleRule parentLayoutRule = ((StyledElement) parentModel .getModel()).getFirstStyleRule( ContainerEditPart.LAYOUT_PROPERTY_NAME, CoreStylesPackage.Literals.SASH_FORM_LAYOUT_RULE); if (parentLayoutRule != null) { return; } } if (childControl.getParent() != composite) return; int oldIndex = -1; for (int i = 0; i < composite.getChildren().length; i++) if (composite.getChildren()[i] == childControl) { oldIndex = i; break; } if (index == oldIndex) return; if (oldIndex < index) childControl.moveBelow(composite.getChildren()[index]); else childControl.moveAbove(composite.getChildren()[index]); } @Override public void validate() { if (currentLayoutRule instanceof StackLayoutRule) StackLayoutStyleRuleManager.platformSpecificRefresh(this, (StackLayoutRule) currentLayoutRule); super.validate(); } public void refreshTabIndexes() { if (getSWTWidget().isDisposed()) return; SortedMap<Integer, Control> tabList = null; for (EditPart child : getHost().getChildren()) { if (child.getModel() instanceof AbstractComponent && ((AbstractComponentEditPart) child).getWidgetView() instanceof SWTWidgetView) { int index = ((AbstractComponent) child.getModel()) .getTabIndex(); if (index != -1) { if (tabList == null) tabList = new TreeMap<Integer, Control>(); tabList.put( index, (Control) ((SWTWidgetView) ((AbstractComponentEditPart) child) .getWidgetView()).getSWTWidget()); } } } if (tabList != null) ((Composite) getSWTWidget()).setTabList((Control[]) tabList .values().toArray(new Control[] {})); } }
true
true
protected Widget createSWTWidget(Widget parent, int swtStyle, int index) { for (StyleRule rule : ((StyledElement) getHost().getModel()) .getStyleRules()) { if (rule instanceof BarLayoutRuleImpl && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { if (((BarLayoutRule) rule).isDraggable()) { // If the elements are draggable, then we need a coolbar CoolBar bar = new CoolBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); bar.setLocked(false); bar.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { Composite parent = (Composite) ((CoolBar) event.widget) .getParent(); if (parent != null) parent.layout(); } }); return bar; } else { // If the elements are not draggable, we need a toolbar return new ToolBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); } } else if (rule instanceof TabbedLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { CTabFolder folder = new CTabFolder( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); folder.setMaximizeVisible(((TabbedLayoutRule) rule) .isMaximizeVisible()); folder.setMinimizeVisible(((TabbedLayoutRule) rule) .isMinimizeVisible()); return folder; } else if (rule instanceof ExpandLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { ExpandBar expandBar = new ExpandBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost()) | SWT.V_SCROLL); return expandBar; } else if (rule instanceof SashFormLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { SashForm sashForm = new SashForm( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); return sashForm; } } StringRule containerTitleRule = (StringRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_VALUE_PROPERTY_NAME, null); BooleanRule containerBorderRule = (BooleanRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_BORDER_PROPERTY_NAME, null); Composite composite; if (containerTitleRule != null && containerBorderRule != null && !containerTitleRule.getValue().equalsIgnoreCase("")) { composite = new org.eclipse.swt.widgets.Group((Composite) parent, computeSWTCreationStyle(getHost())); ((Group) composite).setText(containerTitleRule.getValue()); } else { composite = new org.eclipse.swt.widgets.Composite( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); } return wrapForSpecificParent((Composite) parent, composite); }
protected Widget createSWTWidget(Widget parent, int swtStyle, int index) { for (StyleRule rule : ((StyledElement) getHost().getModel()) .getStyleRules()) { if (rule instanceof BarLayoutRuleImpl && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { if (((BarLayoutRule) rule).isDraggable()) { // If the elements are draggable, then we need a coolbar CoolBar bar = new CoolBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); bar.setLocked(false); bar.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { Composite parent = (Composite) ((CoolBar) event.widget) .getParent(); if (parent != null) parent.layout(); } }); return bar; } else { // If the elements are not draggable, we need a toolbar return new ToolBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); } } else if (rule instanceof TabbedLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { CTabFolder folder = new CTabFolder( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); folder.setMaximizeVisible(((TabbedLayoutRule) rule) .isMaximizeVisible()); folder.setMinimizeVisible(((TabbedLayoutRule) rule) .isMinimizeVisible()); folder.marginWidth = ((TabbedLayoutRule) rule).getMarginWidth(); folder.marginHeight = ((TabbedLayoutRule) rule).getMarginHeight(); return folder; } else if (rule instanceof ExpandLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { ExpandBar expandBar = new ExpandBar( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost()) | SWT.V_SCROLL); return expandBar; } else if (rule instanceof SashFormLayoutRule && ContainerEditPart.LAYOUT_PROPERTY_NAME.equals(rule .getPropertyName())) { SashForm sashForm = new SashForm( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); return sashForm; } } StringRule containerTitleRule = (StringRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_VALUE_PROPERTY_NAME, null); BooleanRule containerBorderRule = (BooleanRule) ((StyledElement) getHost() .getModel()).getFirstStyleRule( ContainerEditPart.TITLE_BORDER_PROPERTY_NAME, null); Composite composite; if (containerTitleRule != null && containerBorderRule != null && !containerTitleRule.getValue().equalsIgnoreCase("")) { composite = new org.eclipse.swt.widgets.Group((Composite) parent, computeSWTCreationStyle(getHost())); ((Group) composite).setText(containerTitleRule.getValue()); } else { composite = new org.eclipse.swt.widgets.Composite( (org.eclipse.swt.widgets.Composite) parent, computeSWTCreationStyle(getHost())); } return wrapForSpecificParent((Composite) parent, composite); }
diff --git a/app/models/FamousPerson.java b/app/models/FamousPerson.java index 0b36f6a..736ae7d 100644 --- a/app/models/FamousPerson.java +++ b/app/models/FamousPerson.java @@ -1,361 +1,361 @@ package models; import java.util.ArrayList; import java.util.List; import javax.persistence.*; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import com.avaje.ebean.ExpressionList; import enums.MementoCategory; import play.db.ebean.Model; import pojos.LocationMinimalBean; @Entity @Table(name="Famous_Person") public class FamousPerson extends Model { /** * */ private static final long serialVersionUID = 7758981950323371564L; @Id @GeneratedValue @Column(name="famous_id") private Long famousId; @Column private String fullname; @Column private String firstname; @Column private String lastname; @Column(name="famous_for") private String famousFor; @Column private String source; @Column(name="source_url") private String sourceUrl; @Column private String locale; @Column(name="picture_url") private String resourceUrl; @Column private String status; @Column private String tags; @Column(name="creator_type") private String creatorType; @Temporal(TemporalType.DATE) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") @Column(name="creation_date") private DateTime creationDate; @Temporal(TemporalType.DATE) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") @Column(name="last_update") private DateTime lastUpdate; @Column private boolean indexed; @Column (name="resource_type") private String resourceType; @Column private String category; @ManyToOne @MapsId @JoinColumn(name="birthdate_fuzzy_id") private FuzzyDate startDate; @ManyToOne @MapsId @JoinColumn(name="deathdate_fuzzy_id") private FuzzyDate endDate; @ManyToOne @MapsId @JoinColumn(name="birthplace_id") private Location startLocation; @ManyToOne @MapsId @JoinColumn(name="deathplace_id") private Location endLocation; @ManyToOne @MapsId @JoinColumn(name="nationality_country_id") private Country country; public static Model.Finder<Long,FamousPerson> find = new Finder<Long, FamousPerson>( Long.class,FamousPerson.class ); public static List<FamousPerson> all(){ return find.all(); } public static void create(FamousPerson famousPerson){ famousPerson.save(); } public static FamousPerson createObject(FamousPerson famousPerson){ famousPerson.save(); return famousPerson; } public static void delete(Long id){ find.ref(id).delete(); } public static FamousPerson read(Long id){ return find.byId(id); } public Long getFamousId() { return famousId; } public void setFamousId(Long famousId) { this.famousId = famousId; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getFamousFor() { return famousFor; } public void setFamousFor(String famousFor) { this.famousFor = famousFor; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getSourceUrl() { return sourceUrl; } public void setSourceUrl(String sourceUrl) { this.sourceUrl = sourceUrl; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getResourceUrl() { return resourceUrl; } public void setResourceUrl(String pictureUrl) { this.resourceUrl = pictureUrl; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCreatorType() { return creatorType; } public void setCreatorType(String creatorType) { this.creatorType = creatorType; } public DateTime getCreationDate() { return creationDate; } public void setCreationDate(DateTime dateAdded) { this.creationDate = dateAdded; } public DateTime getLastUpdate() { return lastUpdate; } public void setLastUpdate(DateTime lastUpdate) { this.lastUpdate = lastUpdate; } public boolean isIndexed() { return indexed; } public void setIndexed(boolean indexed) { this.indexed = indexed; } public FuzzyDate getStartBirthDate() { return startDate; } public void setStartBirthDate(FuzzyDate birthDate) { this.startDate = birthDate; } public FuzzyDate getEndDeathDate() { return endDate; } public void setEndDeathDate(FuzzyDate deathDate) { this.endDate = deathDate; } public Location getStartLocation() { return startLocation; } public void setStartLocation(Location birhplace) { this.startLocation = birhplace; } public Location getEndLocation() { return endLocation; } public void setEndLocation(Location deathplace) { this.endLocation = deathplace; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public static List<FamousPerson> readForContext(String locale, MementoCategory category, Long decade, List<LocationMinimalBean> locations, String level, int itemsPerLevel) { List<FamousPerson> result = new ArrayList<FamousPerson>(); ExpressionList<FamousPerson> el = find.where(); if (level.equals("WORLD")) { el.eq("locale", locale) .eq("category", category.toString()) - .eq("birthDate.decade",decade) + .eq("startDate.decade",decade) .orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } else if (level.equals("COUNTRY")) { List<String> countries = new ArrayList<String>(); for (LocationMinimalBean loc : locations) { String country = loc.getCountry(); countries.add(country); } el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade) .in("startLocatoin.country", countries) .orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } else if (level.equals("REGION")) { for (LocationMinimalBean loc : locations) { el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade); String country = loc.getCountry(); if (country != null && !country.isEmpty()) { el.eq("startLocation.country", country); String region = loc.getRegion(); if (region != null && !region.isEmpty()) { el.eq("startLocation.region", region); el.orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } } } } return result; } }
true
true
public static List<FamousPerson> readForContext(String locale, MementoCategory category, Long decade, List<LocationMinimalBean> locations, String level, int itemsPerLevel) { List<FamousPerson> result = new ArrayList<FamousPerson>(); ExpressionList<FamousPerson> el = find.where(); if (level.equals("WORLD")) { el.eq("locale", locale) .eq("category", category.toString()) .eq("birthDate.decade",decade) .orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } else if (level.equals("COUNTRY")) { List<String> countries = new ArrayList<String>(); for (LocationMinimalBean loc : locations) { String country = loc.getCountry(); countries.add(country); } el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade) .in("startLocatoin.country", countries) .orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } else if (level.equals("REGION")) { for (LocationMinimalBean loc : locations) { el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade); String country = loc.getCountry(); if (country != null && !country.isEmpty()) { el.eq("startLocation.country", country); String region = loc.getRegion(); if (region != null && !region.isEmpty()) { el.eq("startLocation.region", region); el.orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } } } } return result; }
public static List<FamousPerson> readForContext(String locale, MementoCategory category, Long decade, List<LocationMinimalBean> locations, String level, int itemsPerLevel) { List<FamousPerson> result = new ArrayList<FamousPerson>(); ExpressionList<FamousPerson> el = find.where(); if (level.equals("WORLD")) { el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade) .orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } else if (level.equals("COUNTRY")) { List<String> countries = new ArrayList<String>(); for (LocationMinimalBean loc : locations) { String country = loc.getCountry(); countries.add(country); } el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade) .in("startLocatoin.country", countries) .orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } else if (level.equals("REGION")) { for (LocationMinimalBean loc : locations) { el.eq("locale", locale) .eq("category", category.toString()) .eq("startDate.decade",decade); String country = loc.getCountry(); if (country != null && !country.isEmpty()) { el.eq("startLocation.country", country); String region = loc.getRegion(); if (region != null && !region.isEmpty()) { el.eq("startLocation.region", region); el.orderBy("rand()") .setMaxRows(itemsPerLevel); result.addAll(el.findList()); } } } } return result; }
diff --git a/java/de/dfki/lt/mary/MaryData.java b/java/de/dfki/lt/mary/MaryData.java index 52683db14..19deaf8a6 100755 --- a/java/de/dfki/lt/mary/MaryData.java +++ b/java/de/dfki/lt/mary/MaryData.java @@ -1,536 +1,537 @@ /** * Copyright 2000-2006 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * Permission is hereby granted, free of charge, to use and distribute * this software and its documentation without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of this work, and to * permit persons to whom this work is furnished to do so, subject to * the following conditions: * * 1. The code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Any modifications must be clearly marked as such. * 3. Original authors' names are not deleted. * 4. The authors' names are not used to endorse or promote products * derived from this software without specific prior written * permission. * * DFKI GMBH AND THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DFKI GMBH NOR THE * CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ package de.dfki.lt.mary; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import java.util.List; import java.util.Locale; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.jsresources.AppendableSequenceAudioInputStream; import org.jsresources.SequenceAudioInputStream; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import de.dfki.lt.mary.modules.synthesis.Voice; import de.dfki.lt.mary.util.LoggingErrorHandler; import de.dfki.lt.mary.util.MaryNormalisedWriter; import de.dfki.lt.mary.util.MaryUtils; import de.dfki.lt.mary.util.ReaderSplitter; import de.dfki.lt.mary.util.UncloseableBufferedReader; /** * A representation of any type of mary data, be it input, intermediate or * output data. The "technical" representation of the read data is hidden from * the caller, but can be accessed on request. * Internally, the data is appropriately represented according to this data's * type, i.e. as a String containing plain text, an XML DOM tree, or an * input stream containing audio data. * @author Marc Schr&ouml;der */ public class MaryData { private MaryDataType type; // Only one of the following data representations should be non-null // for a given instance; which one depends on our type. private Document xmlDocument = null; private String plainText = null; private AudioInputStream audio = null; private AudioFileFormat audioFileFormat = null; private List utterances = null; // List of Utterance objects private Logger logger = Logger.getLogger("IO"); // for plainText, allow additional information: private Voice defaultVoice = null; // The following XML I/O helpers are only initialised // if actually needed. private MaryNormalisedWriter writer = null; private DocumentBuilderFactory factory = null; private DocumentBuilder docBuilder = null; private StringBuffer buf = null; private boolean doValidate; private boolean doWarnClient = false; public MaryData(MaryDataType type) { this(type, false); } public MaryData(MaryDataType type, boolean createStubDocument) { if (type == null) throw new NullPointerException("Received null type for MaryData"); this.type = type; // The following is the default setting for module output (we suppose // that for the input data, setValidating() is called as appropriate): doValidate = MaryProperties.getBoolean("maryxml.validate.modules", false); if (createStubDocument && type.isMaryXML()) { xmlDocument = MaryXML.newDocument(); } } public boolean getValidating() { return doValidate; } public void setValidating(boolean doValidate) throws ParserConfigurationException { if (doValidate != this.doValidate) { this.doValidate = doValidate; if (factory != null) { initialiseXMLParser(); // re-initialise } } } public boolean getWarnClient() { return doWarnClient; } public void setWarnClient(boolean doWarnClient) { if (doWarnClient != this.doWarnClient) { this.doWarnClient = doWarnClient; if (docBuilder != null) { // Following code copied from initialiseXMLParser(): if (doWarnClient) { // Use custom error handler: docBuilder.setErrorHandler( new LoggingErrorHandler( Thread.currentThread().getName() + " client." + type.name() + " parser")); } else { docBuilder.setErrorHandler(null); } } } } private void initialiseXMLParser() throws ParserConfigurationException { factory = DocumentBuilderFactory.newInstance(); factory.setExpandEntityReferences(true); factory.setNamespaceAware(true); factory.setValidating(doValidate); if (doValidate) { factory.setIgnoringElementContentWhitespace(true); try { factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); // Specify other factory configuration settings factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", MaryProperties.localSchemas()); } catch (Exception x) { // This can happen if the parser does not support JAXP 1.2 logger.warn("Cannot use Schema validation -- turning off validation."); factory.setValidating(false); } } docBuilder = factory.newDocumentBuilder(); docBuilder.setEntityResolver(new org.xml.sax.EntityResolver() { public InputSource resolveEntity (String publicId, String systemId) { if (systemId.equals("http://mary.dfki.de/lib/Sable.v0_2.dtd")) { try { // return a local copy of the sable dtd: String localSableDTD = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "Sable.v0_2.mary.dtd"; return new InputSource(new FileReader(localSableDTD)); } catch (FileNotFoundException e) { logger.warn("Cannot find local Sable.v0_2.mary.dtd"); } } else if (systemId.equals("http://mary.dfki.de/lib/sable-latin.ent")) { try { // return a local copy of the sable dtd: String localFilename = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "sable-latin.ent"; return new InputSource(new FileReader(localFilename)); } catch (FileNotFoundException e) { logger.warn("Cannot find local sable-latin.ent"); } - } else if (systemId.equals("http://mary.dfki.de/lib/apml.dtd")) { + } else if (systemId.equals("http://mary.dfki.de/lib/apml.dtd") + || !systemId.startsWith("http")&&systemId.endsWith("apml.dtd")) { try { - // return a local copy of the sable dtd: + // return a local copy of the apml dtd: String localFilename = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "apml.dtd"; return new InputSource(new FileReader(localFilename)); } catch (FileNotFoundException e) { logger.warn("Cannot find local apml.dtd"); } } // else, use the default behaviour: return null; } }); if (doWarnClient) { // Use custom error handler: docBuilder.setErrorHandler( new LoggingErrorHandler(Thread.currentThread().getName() + " client." + type.name() + " parser")); } else { docBuilder.setErrorHandler(null); } } public MaryDataType type() { return type; } /** * Read data from input stream <code>is</code>, * in the appropriate way as determined by our <code>type</code>. */ public void readFrom(InputStream is) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { readFrom(is, null); } /** * Read data from input stream <code>is</code>, * in the appropriate way as determined by our <code>type</code>. * @param is the InputStream from which to read. * @param endMarker a string marking end of file. If this is null, read until * end-of-file; if it is non-null, read up to (and including) the first line containing * the end marker string. This will be ignored for audio data. */ public void readFrom(InputStream is, String endMarker) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { if (type.isUtterances()) throw new IOException("Cannot read into utterance-based data type!"); if (type.isXMLType() || type.isTextType()) readFrom(new InputStreamReader(is, "UTF-8"), endMarker); else { // audio // ignore endMarker setAudio((AudioInputStream) is); } } /** * Read data from reader <code>r</code> * in the appropriate way as determined by our <code>type</code>. * Only XML and Text data can be read from a reader, audio data cannot. * "Helpers" needed to read the data, such as XML parser objects, * are created when they are needed. * If doWarnClient is set to true, warning and error messages related * to XML parsing are logged to the log category connected to the client * from which this request originated. */ public void readFrom(Reader from) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { readFrom(from, null); } /** * Read data from reader <code>r</code> * in the appropriate way as determined by our <code>type</code>. * Only XML and Text data can be read from a reader, audio data cannot. * "Helpers" needed to read the data, such as XML parser objects, * are created when they are needed. * If doWarnClient is set to true, warning and error messages related * to XML parsing are logged to the log category connected to the client * from which this request originated. * @param from the Reader from which to read. * @param endMarker a string marking end of file. If this is null, read until * end-of-file; if it is non-null, read up to (and including) the first line containing * the end marker string. */ public void readFrom(Reader from, String endMarker) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { if (type.isUtterances()) throw new IOException("Cannot read into utterance-based data type!"); // For the case that the data to be read it is not // followed by end-of-file, we use a ReaderSplitter which // provides a reader artificially "inserting" an end-of-file // after a line containing the pattern given in endMarker. Reader r = from; if (endMarker != null) { ReaderSplitter fromSplitter = new ReaderSplitter(from, endMarker); r = fromSplitter.nextReader(); } if (type.isXMLType()) { if (factory == null) { initialiseXMLParser(); } // The XML parser closes its input stream when it reads EOF. // In the case of a socket, this closes the socket altogether, // so we cannot send data back! Therefore, use a subclass of // BufferedReader that simply ignores the close() call. UncloseableBufferedReader ubr = new UncloseableBufferedReader(r); if (doValidate) { logger.debug("Reading XML input (validating)..."); } else { logger.debug("Reading XML input (non-validating)..."); } xmlDocument = docBuilder.parse(new InputSource(ubr)); if (logger.getEffectiveLevel().equals(Level.DEBUG)) { if (writer == null) writer = new MaryNormalisedWriter(); ByteArrayOutputStream debugOut = new ByteArrayOutputStream(); writer.output(xmlDocument, debugOut); logger.debug("Read XML input:\n" + debugOut.toString()); } } else if (type.isTextType()) { // Plain text is read until end-of-file? if (buf == null) buf = new StringBuffer(1000); else buf.setLength(0); BufferedReader br = new BufferedReader(r); String line = null; while ((line = br.readLine()) != null) { buf.append(line); buf.append(System.getProperty("line.separator")); logger.debug("Reading text input: " + line); } plainText = buf.toString(); } else { // audio -- cannot read this from a reader throw new IOException("Illegal attempt to read audio data from a character Reader"); } } /** * Write our internal representation to output stream <code>os</code>, * in the appropriate way as determined by our <code>type</code>. */ public void writeTo(OutputStream os) throws TransformerConfigurationException, FileNotFoundException, TransformerException, IOException, Exception { if (type.isUtterances()) throw new IOException("Cannot write out utterance-based data type!"); if (type.isXMLType()) { if (writer == null) writer = new MaryNormalisedWriter(); if (logger.getEffectiveLevel().equals(Level.DEBUG)) { ByteArrayOutputStream debugOut = new ByteArrayOutputStream(); writer.output(xmlDocument, debugOut); logger.debug(debugOut.toString()); } writer.output(xmlDocument, new BufferedOutputStream(os)); } else if (type.isTextType()) { // caution: XML types are text types! writeTo(new OutputStreamWriter(os, "UTF-8")); } else { // audio logger.debug("Writing audio output, frame length "+audio.getFrameLength()); AudioSystem.write(audio, audioFileFormat.getType(), os); os.flush(); } } /** * Write our internal representation to writer <code>w</code>, * in the appropriate way as determined by our <code>type</code>. * Only XML and Text data can be written to a writer, audio data cannot. * "Helpers" needed to read the data, such as XML parser objects, * are created when they are needed. */ public void writeTo(Writer w) throws TransformerConfigurationException, FileNotFoundException, TransformerException, IOException, Exception { if (type.isUtterances()) throw new IOException("Cannot write out utterance-based data type!"); if (type.isXMLType()) { throw new IOException("Better write XML data to an OutputStream, not to a Writer"); } else if (type.isTextType()) { // caution: XML types are text types! w.write(plainText); w.flush(); logger.debug("Writing Text output:\n" + plainText); } else { // audio - cannot write this to a writer throw new Exception("Illegal attempt to write audio data to a character Writer"); } } public Object getData() { if (type.isXMLType()) { return xmlDocument; } else if (type.isTextType()) { return plainText; } else if (type.isUtterances()) { return utterances; } else { // audio return audio; } } public String getPlainText() { return plainText; } public void setPlainText(String plainText) { this.plainText = plainText; } public Document getDocument() { return xmlDocument; } public void setDocument(Document xmlDocument) { this.xmlDocument = xmlDocument; } public AudioInputStream getAudio() { return audio; } /** * Set the audio data. This will discard any previously set audio data. If audio data is to be * appended, consider appendAudio(). * @param audio */ public void setAudio(AudioInputStream audio) { this.audio = audio; } public List getUtterances() { return utterances; } public void setUtterances(List utterances) { this.utterances = utterances; } public void setDefaultVoice(Voice voice) { if (voice == null) logger.warn("received null default voice"); // check that voice locale fits before accepting the voice: Locale voiceLocale = null; if (voice != null) voiceLocale = voice.getLocale(); Locale docLocale = type().getLocale(); if (docLocale == null && type().isXMLType() && getDocument() != null && getDocument().getDocumentElement().hasAttribute("xml:lang")) { docLocale = MaryUtils.string2locale(getDocument().getDocumentElement().getAttribute("xml:lang")); } if (docLocale != null && voiceLocale != null && !(MaryUtils.subsumes(docLocale, voiceLocale) || MaryUtils.subsumes(voiceLocale, docLocale))) { logger.warn("Voice `"+voice.getName()+"' does not match document locale `"+docLocale+"' -- ignoring!"); return; } this.defaultVoice = voice; } public Voice getDefaultVoice() { return defaultVoice; } /** * The audio file format is required only for data types serving as input * to modules producing AUDIO data (e.g., MBROLA data), as well as for the * AUDIO data itself. It should be set by the calling code before passing * the data to the module producing AUDIO data. */ public void setAudioFileFormat(AudioFileFormat audioFileFormat) { this.audioFileFormat = audioFileFormat; } public AudioFileFormat getAudioFileFormat() { return audioFileFormat; } public void append(MaryData md) { if (md == null) throw new NullPointerException("Received null marydata"); if (!md.type().equals(this.type())) throw new IllegalArgumentException("Cannot append mary data of type `" + md.type().name() + "' to mary data of type `" + this.type().name() + "'"); if (type().isXMLType()) { NodeList kids = md.getDocument().getDocumentElement().getChildNodes(); logger.debug("Appending " + kids.getLength() + " nodes to MaryXML structure"); Element docEl = this.getDocument().getDocumentElement(); for (int i=0; i<kids.getLength(); i++) { docEl.appendChild(this.getDocument().importNode(kids.item(i), true)); } } else if (type().isTextType()) { // Attention: XML type is a text type! this.plainText = this.plainText + "\n\n" + md.getPlainText(); } else if (type().equals(MaryDataType.get("AUDIO"))) { appendAudio(md.getAudio()); } else { throw new UnsupportedOperationException("Cannot append two mary data items of type `" + type() + "'"); } } /** * For audio data, append more audio data to the one currently present. If no audio data is set yet, * this call is equivalent to setAudio(). * @param audio the new audio data to append */ public void appendAudio(AudioInputStream audio) { if (this.audio == null) setAudio(audio); else if (this.audio instanceof AppendableSequenceAudioInputStream) ((AppendableSequenceAudioInputStream)this.audio).append(audio); else this.audio = new SequenceAudioInputStream(this.audio.getFormat(), Arrays.asList(new AudioInputStream[] {this.audio, audio})); } }
false
true
private void initialiseXMLParser() throws ParserConfigurationException { factory = DocumentBuilderFactory.newInstance(); factory.setExpandEntityReferences(true); factory.setNamespaceAware(true); factory.setValidating(doValidate); if (doValidate) { factory.setIgnoringElementContentWhitespace(true); try { factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); // Specify other factory configuration settings factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", MaryProperties.localSchemas()); } catch (Exception x) { // This can happen if the parser does not support JAXP 1.2 logger.warn("Cannot use Schema validation -- turning off validation."); factory.setValidating(false); } } docBuilder = factory.newDocumentBuilder(); docBuilder.setEntityResolver(new org.xml.sax.EntityResolver() { public InputSource resolveEntity (String publicId, String systemId) { if (systemId.equals("http://mary.dfki.de/lib/Sable.v0_2.dtd")) { try { // return a local copy of the sable dtd: String localSableDTD = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "Sable.v0_2.mary.dtd"; return new InputSource(new FileReader(localSableDTD)); } catch (FileNotFoundException e) { logger.warn("Cannot find local Sable.v0_2.mary.dtd"); } } else if (systemId.equals("http://mary.dfki.de/lib/sable-latin.ent")) { try { // return a local copy of the sable dtd: String localFilename = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "sable-latin.ent"; return new InputSource(new FileReader(localFilename)); } catch (FileNotFoundException e) { logger.warn("Cannot find local sable-latin.ent"); } } else if (systemId.equals("http://mary.dfki.de/lib/apml.dtd")) { try { // return a local copy of the sable dtd: String localFilename = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "apml.dtd"; return new InputSource(new FileReader(localFilename)); } catch (FileNotFoundException e) { logger.warn("Cannot find local apml.dtd"); } } // else, use the default behaviour: return null; } }); if (doWarnClient) { // Use custom error handler: docBuilder.setErrorHandler( new LoggingErrorHandler(Thread.currentThread().getName() + " client." + type.name() + " parser")); } else { docBuilder.setErrorHandler(null); } }
private void initialiseXMLParser() throws ParserConfigurationException { factory = DocumentBuilderFactory.newInstance(); factory.setExpandEntityReferences(true); factory.setNamespaceAware(true); factory.setValidating(doValidate); if (doValidate) { factory.setIgnoringElementContentWhitespace(true); try { factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); // Specify other factory configuration settings factory.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", MaryProperties.localSchemas()); } catch (Exception x) { // This can happen if the parser does not support JAXP 1.2 logger.warn("Cannot use Schema validation -- turning off validation."); factory.setValidating(false); } } docBuilder = factory.newDocumentBuilder(); docBuilder.setEntityResolver(new org.xml.sax.EntityResolver() { public InputSource resolveEntity (String publicId, String systemId) { if (systemId.equals("http://mary.dfki.de/lib/Sable.v0_2.dtd")) { try { // return a local copy of the sable dtd: String localSableDTD = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "Sable.v0_2.mary.dtd"; return new InputSource(new FileReader(localSableDTD)); } catch (FileNotFoundException e) { logger.warn("Cannot find local Sable.v0_2.mary.dtd"); } } else if (systemId.equals("http://mary.dfki.de/lib/sable-latin.ent")) { try { // return a local copy of the sable dtd: String localFilename = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "sable-latin.ent"; return new InputSource(new FileReader(localFilename)); } catch (FileNotFoundException e) { logger.warn("Cannot find local sable-latin.ent"); } } else if (systemId.equals("http://mary.dfki.de/lib/apml.dtd") || !systemId.startsWith("http")&&systemId.endsWith("apml.dtd")) { try { // return a local copy of the apml dtd: String localFilename = MaryProperties.maryBase() + File.separator + "lib" + File.separator + "apml.dtd"; return new InputSource(new FileReader(localFilename)); } catch (FileNotFoundException e) { logger.warn("Cannot find local apml.dtd"); } } // else, use the default behaviour: return null; } }); if (doWarnClient) { // Use custom error handler: docBuilder.setErrorHandler( new LoggingErrorHandler(Thread.currentThread().getName() + " client." + type.name() + " parser")); } else { docBuilder.setErrorHandler(null); } }
diff --git a/app/controllers/submit/DocumentInfo.java b/app/controllers/submit/DocumentInfo.java index fe2d16b52..76b765851 100644 --- a/app/controllers/submit/DocumentInfo.java +++ b/app/controllers/submit/DocumentInfo.java @@ -1,758 +1,758 @@ package controllers.submit; import static org.tdl.vireo.constant.AppConfig.*; import static org.tdl.vireo.constant.FieldConfig.*; import java.io.IOException; import java.io.StringReader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.LocaleUtils; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import org.tdl.vireo.constant.FieldConfig; import org.tdl.vireo.model.CommitteeMember; import org.tdl.vireo.model.CommitteeMemberRoleType; import org.tdl.vireo.model.Configuration; import org.tdl.vireo.model.DocumentType; import org.tdl.vireo.model.EmbargoType; import org.tdl.vireo.model.GraduationMonth; import org.tdl.vireo.model.Language; import org.tdl.vireo.model.NameFormat; import org.tdl.vireo.model.RoleType; import org.tdl.vireo.model.Submission; import org.tdl.vireo.proquest.ProquestSubject; import play.Logger; import au.com.bytecode.opencsv.CSVReader; import controllers.Security; /** * This is the third step of the submission process. This is where students * provide metedata about their document, committee members, and select among * publication options. * * @author <a href="http://www.scottphillips.com">Scott Phillips</a> * @author <a href="bill-ingram.com">Bill Ingram</a> * @author Dan Galewsky */ public class DocumentInfo extends AbstractSubmitStep { /** * The third step of the submission form. * * We handle committee members a bit differently. Basically we always keep a * List of Maps for each committee member while we are working with it. So * there are several methods to parse the committee members from the current * form data, validate the committee members, then save the committee * members, and if this is the first time visiting the form there is a * method to load committee members. It's complex, but the problem is * Difficult. * * @param subId The id the submission. */ @Security(RoleType.STUDENT) public static void documentInfo(Long subId) { // Validate the submission Submission sub = getSubmission(); // Get our form paramaters. String title = params.get("title"); String degreeMonth = params.get("degreeMonth"); String degreeYear = params.get("degreeYear"); Date defenseDate = null; DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); try { - if(params.get("defenseDate")!=null) + if(params.get("defenseDate")!=null && !"".equals(params.get("defenseDate").trim())) defenseDate = (Date)formatter.parse(params.get("defenseDate")); } catch (ParseException e) { validation.addError("defenseDate","Please format your defense date as mm/dd/yyyy"); } String docType = params.get("docType"); String abstractText = params.get("abstractText"); String keywords = params.get("keywords"); String subjectPrimary = params.get("subject-primary"); String subjectSecondary = params.get("subject-secondary"); String subjectTertiary = params.get("subject-tertiary"); String docLanguage = null; if(isFieldRequired(DOCUMENT_LANGUAGE) && settingRepo.findAllLanguages().size()==1) { docLanguage = settingRepo.findAllLanguages().get(0).getName(); } else { docLanguage = params.get("docLanguage"); if (docLanguage != null && docLanguage.trim().length() == 0) docLanguage = null; } Boolean publishedMaterialFlag = params.get("publishedMaterialFlag",Boolean.class); if (publishedMaterialFlag == null) publishedMaterialFlag = false; String publishedMaterial = params.get("publishedMaterial"); if (!publishedMaterialFlag) publishedMaterial = null; String chairEmail = params.get("chairEmail"); String embargo = params.get("embargo"); String umi = params.get("umi"); List<TransientMember> committee = parseCommitteeMembers(); if ("documentInfo".equals(params.get("step"))) { // Save the data if (isFieldEnabled(DOCUMENT_TITLE)) sub.setDocumentTitle(title); if (isFieldEnabled(GRADUATION_DATE)) { if (!isEmpty(degreeMonth)) { try { sub.setGraduationMonth(Integer.parseInt(degreeMonth)); } catch (RuntimeException re) { validation.addError("degreeMonth", "Please select a valid degree month"); } } else { sub.setGraduationMonth(null); } if (!isEmpty(degreeYear)) { try { sub.setGraduationYear(Integer.parseInt(degreeYear)); } catch (RuntimeException re) { validation.addError("degreeYear", "Please select a valid degree year"); } } else { sub.setGraduationYear(null); } } if (isFieldEnabled(DEFENSE_DATE)) { sub.setDefenseDate(defenseDate); } if (isFieldEnabled(DOCUMENT_TYPE)) sub.setDocumentType(docType); if (isFieldEnabled(DOCUMENT_ABSTRACT)) sub.setDocumentAbstract(abstractText); if (isFieldEnabled(DOCUMENT_KEYWORDS)) sub.setDocumentKeywords(keywords); if (isFieldEnabled(DOCUMENT_SUBJECTS)) { sub.getDocumentSubjects().clear(); if (!isEmpty(subjectPrimary)) sub.addDocumentSubject(subjectPrimary); if (!isEmpty(subjectSecondary)) sub.addDocumentSubject(subjectSecondary); if (!isEmpty(subjectTertiary)) sub.addDocumentSubject(subjectTertiary); } if (isFieldEnabled(DOCUMENT_LANGUAGE)) sub.setDocumentLanguage(docLanguage); if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL)) sub.setCommitteeContactEmail(chairEmail); if (isFieldEnabled(PUBLISHED_MATERIAL)) { if (publishedMaterialFlag) sub.setPublishedMaterial(publishedMaterial); else sub.setPublishedMaterial(null); } if (isFieldEnabled(EMBARGO_TYPE)) { try { sub.setEmbargoType(settingRepo.findEmbargoType(Long.parseLong(embargo))); } catch (RuntimeException re){ if (isFieldRequired(EMBARGO_TYPE)) validation.addError("embargo", "Please select a valid embargo option"); } } if (isFieldEnabled(UMI_RELEASE)) { if (umi != null && umi.trim().length() > 0) sub.setUMIRelease(true); else sub.setUMIRelease(false); } if (isFieldEnabled(COMMITTEE)) { try { saveCommitteeMembers(sub, committee); } catch (RuntimeException re){ /*ignore*/ } } sub.save(); } else { if (isFieldEnabled(DOCUMENT_TITLE)) title = sub.getDocumentTitle(); if (isFieldEnabled(GRADUATION_DATE) && sub.getGraduationMonth() != null) degreeMonth = sub.getGraduationMonth().toString(); if (isFieldEnabled(GRADUATION_DATE) && sub.getGraduationYear() != null) degreeYear = sub.getGraduationYear().toString(); if (isFieldEnabled(DEFENSE_DATE) && sub.getDefenseDate() != null) defenseDate = sub.getDefenseDate(); if (isFieldEnabled(DOCUMENT_TYPE)) docType = sub.getDocumentType(); if (isFieldEnabled(DOCUMENT_ABSTRACT)) abstractText = sub.getDocumentAbstract(); if (isFieldEnabled(DOCUMENT_KEYWORDS)) keywords = sub.getDocumentKeywords(); if (isFieldEnabled(DOCUMENT_SUBJECTS)) { List<String> subjects = sub.getDocumentSubjects(); if (subjects.size() > 0) subjectPrimary = subjects.get(0); if (subjects.size() > 1) subjectSecondary = subjects.get(1); if (subjects.size() > 2) subjectTertiary = subjects.get(2); } if (isFieldEnabled(DOCUMENT_LANGUAGE)) { docLanguage = sub.getDocumentLanguage(); } // Get the list of committee members if (isFieldEnabled(COMMITTEE)) committee = loadCommitteeMembers(sub); if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL)) chairEmail = sub.getCommitteeContactEmail(); if (isFieldEnabled(PUBLISHED_MATERIAL)) publishedMaterial = sub.getPublishedMaterial(); if (isFieldEnabled(EMBARGO_TYPE) && sub.getEmbargoType() != null) embargo = sub.getEmbargoType().getId().toString(); if (isFieldEnabled(UMI_RELEASE) && sub.getUMIRelease() != null && sub.getUMIRelease() != false) umi = "true"; } // Verify the form if we are submitting or if jumping from the confirm step. if ("documentInfo".equals(params.get("step")) || "confirm".equals(flash.get("from-step"))) { verify(sub); } // If there are no errors then go to the next step if (params.get("submit_next") != null && !validation.hasErrors() ) { FileUpload.fileUpload(subId); } // List of valid degree years for drop-down population List<Integer> degreeYears = getDegreeYears(); renderArgs.put("degreeYears", degreeYears); // List of all document types List<String> docTypes = getValidDocumentTypes(sub); renderArgs.put("docTypes", docTypes); // List of all *active* Embargo Types List<EmbargoType> embargoTypes = settingRepo.findAllActiveEmbargoTypes(); renderArgs.put("embargoTypes", embargoTypes); // List of all subjects List<ProquestSubject> subjects = proquestRepo.findAllSubjects(); renderArgs.put("subjects", subjects); // List available committe roles List<CommitteeMemberRoleType> availableRoles = settingRepo.findAllCommitteeMemberRoleTypes(sub.getDegreeLevel()); renderArgs.put("availableRoles", availableRoles); // List of all languages List<Language> languages = settingRepo.findAllLanguages(); renderArgs.put("docLanguages", languages); // Figure out how mayn committee spots to show. int committeeSlots = 4; if (committee.size() > 3) committeeSlots = committee.size(); if (params.get("submit_add") != null) committeeSlots += 4; List<String> stickies = new ArrayList<String>(); String stickiesRaw = settingRepo.getConfigValue(SUBMIT_DOCUMENT_INFO_STICKIES); if (stickiesRaw != null && !"null".equals(stickiesRaw)) { try { CSVReader reader = new CSVReader(new StringReader(stickiesRaw)); stickies = Arrays.asList(reader.readNext()); reader.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } if (publishedMaterial != null) publishedMaterialFlag = true; renderTemplate("Submit/documentInfo.html", subId, stickies, title, degreeMonth, degreeYear, defenseDate, docType, abstractText, keywords, subjectPrimary, subjectSecondary, subjectTertiary, docLanguage, committeeSlots, committee, chairEmail, publishedMaterialFlag, publishedMaterial, embargo, umi); } /** * Verify that all the document information is correct. This will be * accessed from two places, the document info page as well as the * confirmation page. * * @return True if there are no errors found, otherwise false. */ public static boolean verify(Submission sub) { int numberOfErrorsBefore = validation.errors().size(); // Document Title if(isFieldRequired(DOCUMENT_TITLE) && isEmpty(sub.getDocumentTitle())) validation.addError("title", "Please enter a thesis title"); // Graduation Date (month & year) if (!isValidDegreeMonth(sub.getGraduationMonth())) validation.addError("degreeMonth", "Please select a degree month"); if (!isValidDegreeYear(sub.getGraduationYear())) validation.addError("degreeYear", "Please select a degree year"); // Defense Date Date now = new Date(); Date min = new Date(-2208967200000L); Date max = new Date(now.getTime() + (365 * 24 * 60 * 60 * 1000L)); DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); if (isFieldRequired(DEFENSE_DATE) && (sub.getDefenseDate()==null)) validation.addError("defenseDate", "Please enter a defense date"); else if(sub.getDefenseDate()!=null && (!sub.getDefenseDate().after(min) || !sub.getDefenseDate().before(max))) validation.addError("defenseDate", "Please enter a defense date between "+formatter.format(min)+" and "+formatter.format(max)); // Document Type if (!isValidDocType(sub.getDocumentType())) validation.addError("docType", "Please select a Document Type"); // Document Abstract if (isFieldRequired(DOCUMENT_ABSTRACT) && isEmpty(sub.getDocumentAbstract())) validation.addError("abstractText", "Please enter an abstract"); // Document Keywords if (isFieldRequired(DOCUMENT_KEYWORDS) && isEmpty(sub.getDocumentKeywords())) validation.addError("keywords", "Please enter at least one keyword"); // Document Subjects if (isFieldEnabled(DOCUMENT_SUBJECTS)) { for (String subject : sub.getDocumentSubjects()) { if (proquestRepo.findSubjectByDescription(subject) == null) { validation.addError("subjects", "One of the selected subjects is invalid"); } } if (isFieldRequired(DOCUMENT_SUBJECTS) && sub.getDocumentSubjects().size() == 0) { validation.addError("subjects", "Please provide atleast a primary subject."); } } // Language if (isFieldRequired(DOCUMENT_LANGUAGE) && isEmpty(sub.getDocumentLanguage())) validation.addError("language", "Please select a language."); // Committee members (make sure they aren't any double entries) if (isFieldRequired(COMMITTEE) && !validation.hasError("committee")) { List<TransientMember> committee = loadCommitteeMembers(sub); validateCommitteeMembers(sub,committee); } // Committee Contact Email if (isFieldRequired(COMMITTEE_CONTACT_EMAIL) && isEmpty(sub.getCommitteeContactEmail())) { validation.addError("chairEmail", "Please enter an email address for the committee chair"); } else if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL) && !isEmpty(sub.getCommitteeContactEmail())) { try { new InternetAddress(sub.getCommitteeContactEmail()).validate(); } catch (AddressException e) { validation.addError("chairEmail","The committee chair email address '"+sub.getCommitteeContactEmail()+"' you provided is invalid."); } } // Previously Published if (isFieldEnabled(PUBLISHED_MATERIAL)) { if (sub.getPublishedMaterial() != null && sub.getPublishedMaterial().trim().length() < 10) { validation.addError("publishedMaterial", "If the any material being submitted has been previously published then you must identify the material which was published. (i.e. the section or chapter)."); } } // Embargo if (isFieldRequired(EMBARGO_TYPE) && sub.getEmbargoType() == null) validation.addError("embargo", "Please choose an embargo option"); // UMI if (isFieldRequired(UMI_RELEASE) && sub.getUMIRelease() == null) validation.addError("umi", "Please select whether to release to UMI."); // Check if we've added any new errors. If so return false; if (numberOfErrorsBefore == validation.errors().size()) return true; else return false; } /** * @param degreeMonth * The month of the degree * @return True if the name is a valid degree month. */ protected static boolean isValidDegreeMonth(Integer degreeMonth) { if (degreeMonth == null) { if (isFieldRequired(GRADUATION_DATE)) return false; return true; } for (GraduationMonth month : settingRepo.findAllGraduationMonths()) { if (degreeMonth == month.getMonth()) { return true; } } return false; } /** * @param degreeYear * The year of the degree * @return True if the name is a valid degree year. */ protected static boolean isValidDegreeYear(Integer degreeYear) { if (degreeYear == null) { if (isFieldRequired(GRADUATION_DATE)) return false; return true; } for (Integer y : getDegreeYears()) { if (degreeYear.equals(y)) { return true; } } return false; } /** * * @param docType The document type. * @return True if the docType is a valid document type. */ protected static boolean isValidDocType(String docType) { if (isEmpty(docType)) { if (isFieldRequired(DOCUMENT_TYPE)) return false; return true; } List<DocumentType> docTypes = settingRepo.findAllDocumentTypes(); for(DocumentType type : docTypes) { if(docType.equals(type.getName())) { return true; } } return false; } /** * Determine if the provided roles are valid for this given degree level of the submission. * * @param sub The submission * @param roles The roles to validate. * @return True if valid, otherwise false. */ protected static boolean isValidRoleType(Submission sub, List<String> roles) { List<CommitteeMemberRoleType> types = settingRepo.findAllCommitteeMemberRoleTypes(sub.getDegreeLevel()); for (String role : roles) { boolean found = false; for (CommitteeMemberRoleType type : types) { if (type.getName().equals(role)) { found = true; break; } } if (!found) return false; } return true; } /** * For now, this method returns the current valid years based on * the subsequent two years. This will possible move into a * configuration setting eventually. * * @return list of current valid degree years */ protected static List<Integer> getDegreeYears() { Integer currentYear = Calendar.getInstance().get(Calendar.YEAR); List<Integer> validYears = new ArrayList<Integer>(); validYears.add(currentYear - 3); validYears.add(currentYear - 2); validYears.add(currentYear - 1); validYears.add(currentYear); validYears.add(currentYear + 1); validYears.add(currentYear + 2); validYears.add(currentYear + 3); validYears.add(currentYear + 4); validYears.add(currentYear + 5); validYears.add(currentYear + 6); validYears.add(currentYear + 7); validYears.add(currentYear + 8); validYears.add(currentYear + 9); return validYears; } /** * Returns a list of valid Document Types * * @return list of valid document types for this submission's degree */ protected static List<String> getValidDocumentTypes(Submission sub) { List<DocumentType> validTypes = settingRepo.findAllDocumentTypes(); // If a valid degree is set, then limit the choices to those of that same level. if (sub.getDegree() != null && settingRepo.findDegreeByName(sub.getDegree()) != null) { validTypes = settingRepo.findAllDocumentTypes(settingRepo.findDegreeByName(sub.getDegree()).getLevel()); } List<String> typeNames = new ArrayList<String>(); // Gather Document Type names, since we are soft-linking these to Submission for(DocumentType type : validTypes) { typeNames.add(type.getName()); } return typeNames; } /** * Load committee members from the supplied submission * object. * * @param sub * The submission object * @return List of transient committee members. */ public static List<TransientMember> loadCommitteeMembers(Submission sub) { List<TransientMember> committee = new ArrayList<TransientMember>(); for (CommitteeMember member: sub.getCommitteeMembers()) { TransientMember transientMember = new TransientMember( member.getFirstName(), member.getMiddleName(), member.getLastName(), member.getRoles()); committee.add(transientMember); } return committee; } /** * Validate the transient list for committee members. This method * checks that all members have their first and last names * * @param members * List of maps for each committee member. */ public static boolean validateCommitteeMembers(Submission sub, List<TransientMember> members ) { boolean atLeastOneMember = false; int i = 1; for (TransientMember member : members) { // Check that if we have a first name, then we have a last name. if (isEmpty(member.firstName) && isEmpty(member.lastName)) { validation.addError("member"+i,"Please provide a first or last name for all committee members."); } else { atLeastOneMember = true; } // roles if (!isValidRoleType(sub, member.roles)) validation.addError("member"+i,"One of the roles selected is invalid"); } if (!atLeastOneMember) validation.addError("committee", "You must specify who is on your committee."); return true; } /** * Construct the transient list for committee members from the html * form parameters. * * @return List of committee member. */ public static List<TransientMember> parseCommitteeMembers() { List<TransientMember> committee = new ArrayList<TransientMember>(); int i = 1; while (params.get("committeeFirstName"+i) != null || params.get("committeeLastName"+i) != null) { String firstName = params.get("committeeFirstName"+i); String middleName = params.get("committeeMiddleName"+i); String lastName = params.get("committeeLastName"+i); String[] roles = params.get("committeeRoles"+i,String[].class); if (roles == null || (roles.length == 1 && roles[0].trim().length() == 0)) roles = new String[0]; i++; if ((firstName == null || firstName.trim().length() == 0) && (lastName == null || lastName.trim().length() == 0)) // If the first or last name fields are blank then skip this one. continue; TransientMember member = new TransientMember( firstName, middleName, lastName, roles); committee.add(member); } return committee; } /** * Save the transient list of committee members into the submission * object. * * @param sub * The submission object to be modified. * @param members * The new list of committee members. */ public static boolean saveCommitteeMembers(Submission sub, List<TransientMember> members) { for (CommitteeMember member : new ArrayList<CommitteeMember>(sub.getCommitteeMembers())) { member.delete(); } int i = 1; for (TransientMember member : members) { String firstName = member.firstName; String middleName = member.middleName; String lastName = member.lastName; List<String> roles = member.roles; // Make sure that we have a first or last name if (firstName != null && firstName.trim().length() == 0) firstName = null; if (lastName != null && lastName.trim().length() == 0) lastName = null; if (firstName == null && lastName == null) continue; CommitteeMember newMember = sub.addCommitteeMember(firstName, lastName, middleName).save(); newMember.setDisplayOrder(i); for (String role : roles) { newMember.addRole(role); } newMember.save(); i++; } return true; } /** * Simple data structure to keep committee members while being processed. */ public static class TransientMember { public String firstName; public String middleName; public String lastName; public List<String> roles; public TransientMember(String firstName, String middleName, String lastName, List<String> roles) { this.firstName = firstName; this.middleName = middleName; this.lastName = lastName; this.roles = new ArrayList<String>(roles); } public TransientMember(String firstName, String middleName, String lastName, String[] roles) { this.firstName = firstName; this.middleName = middleName; this.lastName = lastName; this.roles = Arrays.asList(roles); } } }
true
true
public static void documentInfo(Long subId) { // Validate the submission Submission sub = getSubmission(); // Get our form paramaters. String title = params.get("title"); String degreeMonth = params.get("degreeMonth"); String degreeYear = params.get("degreeYear"); Date defenseDate = null; DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); try { if(params.get("defenseDate")!=null) defenseDate = (Date)formatter.parse(params.get("defenseDate")); } catch (ParseException e) { validation.addError("defenseDate","Please format your defense date as mm/dd/yyyy"); } String docType = params.get("docType"); String abstractText = params.get("abstractText"); String keywords = params.get("keywords"); String subjectPrimary = params.get("subject-primary"); String subjectSecondary = params.get("subject-secondary"); String subjectTertiary = params.get("subject-tertiary"); String docLanguage = null; if(isFieldRequired(DOCUMENT_LANGUAGE) && settingRepo.findAllLanguages().size()==1) { docLanguage = settingRepo.findAllLanguages().get(0).getName(); } else { docLanguage = params.get("docLanguage"); if (docLanguage != null && docLanguage.trim().length() == 0) docLanguage = null; } Boolean publishedMaterialFlag = params.get("publishedMaterialFlag",Boolean.class); if (publishedMaterialFlag == null) publishedMaterialFlag = false; String publishedMaterial = params.get("publishedMaterial"); if (!publishedMaterialFlag) publishedMaterial = null; String chairEmail = params.get("chairEmail"); String embargo = params.get("embargo"); String umi = params.get("umi"); List<TransientMember> committee = parseCommitteeMembers(); if ("documentInfo".equals(params.get("step"))) { // Save the data if (isFieldEnabled(DOCUMENT_TITLE)) sub.setDocumentTitle(title); if (isFieldEnabled(GRADUATION_DATE)) { if (!isEmpty(degreeMonth)) { try { sub.setGraduationMonth(Integer.parseInt(degreeMonth)); } catch (RuntimeException re) { validation.addError("degreeMonth", "Please select a valid degree month"); } } else { sub.setGraduationMonth(null); } if (!isEmpty(degreeYear)) { try { sub.setGraduationYear(Integer.parseInt(degreeYear)); } catch (RuntimeException re) { validation.addError("degreeYear", "Please select a valid degree year"); } } else { sub.setGraduationYear(null); } } if (isFieldEnabled(DEFENSE_DATE)) { sub.setDefenseDate(defenseDate); } if (isFieldEnabled(DOCUMENT_TYPE)) sub.setDocumentType(docType); if (isFieldEnabled(DOCUMENT_ABSTRACT)) sub.setDocumentAbstract(abstractText); if (isFieldEnabled(DOCUMENT_KEYWORDS)) sub.setDocumentKeywords(keywords); if (isFieldEnabled(DOCUMENT_SUBJECTS)) { sub.getDocumentSubjects().clear(); if (!isEmpty(subjectPrimary)) sub.addDocumentSubject(subjectPrimary); if (!isEmpty(subjectSecondary)) sub.addDocumentSubject(subjectSecondary); if (!isEmpty(subjectTertiary)) sub.addDocumentSubject(subjectTertiary); } if (isFieldEnabled(DOCUMENT_LANGUAGE)) sub.setDocumentLanguage(docLanguage); if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL)) sub.setCommitteeContactEmail(chairEmail); if (isFieldEnabled(PUBLISHED_MATERIAL)) { if (publishedMaterialFlag) sub.setPublishedMaterial(publishedMaterial); else sub.setPublishedMaterial(null); } if (isFieldEnabled(EMBARGO_TYPE)) { try { sub.setEmbargoType(settingRepo.findEmbargoType(Long.parseLong(embargo))); } catch (RuntimeException re){ if (isFieldRequired(EMBARGO_TYPE)) validation.addError("embargo", "Please select a valid embargo option"); } } if (isFieldEnabled(UMI_RELEASE)) { if (umi != null && umi.trim().length() > 0) sub.setUMIRelease(true); else sub.setUMIRelease(false); } if (isFieldEnabled(COMMITTEE)) { try { saveCommitteeMembers(sub, committee); } catch (RuntimeException re){ /*ignore*/ } } sub.save(); } else { if (isFieldEnabled(DOCUMENT_TITLE)) title = sub.getDocumentTitle(); if (isFieldEnabled(GRADUATION_DATE) && sub.getGraduationMonth() != null) degreeMonth = sub.getGraduationMonth().toString(); if (isFieldEnabled(GRADUATION_DATE) && sub.getGraduationYear() != null) degreeYear = sub.getGraduationYear().toString(); if (isFieldEnabled(DEFENSE_DATE) && sub.getDefenseDate() != null) defenseDate = sub.getDefenseDate(); if (isFieldEnabled(DOCUMENT_TYPE)) docType = sub.getDocumentType(); if (isFieldEnabled(DOCUMENT_ABSTRACT)) abstractText = sub.getDocumentAbstract(); if (isFieldEnabled(DOCUMENT_KEYWORDS)) keywords = sub.getDocumentKeywords(); if (isFieldEnabled(DOCUMENT_SUBJECTS)) { List<String> subjects = sub.getDocumentSubjects(); if (subjects.size() > 0) subjectPrimary = subjects.get(0); if (subjects.size() > 1) subjectSecondary = subjects.get(1); if (subjects.size() > 2) subjectTertiary = subjects.get(2); } if (isFieldEnabled(DOCUMENT_LANGUAGE)) { docLanguage = sub.getDocumentLanguage(); } // Get the list of committee members if (isFieldEnabled(COMMITTEE)) committee = loadCommitteeMembers(sub); if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL)) chairEmail = sub.getCommitteeContactEmail(); if (isFieldEnabled(PUBLISHED_MATERIAL)) publishedMaterial = sub.getPublishedMaterial(); if (isFieldEnabled(EMBARGO_TYPE) && sub.getEmbargoType() != null) embargo = sub.getEmbargoType().getId().toString(); if (isFieldEnabled(UMI_RELEASE) && sub.getUMIRelease() != null && sub.getUMIRelease() != false) umi = "true"; } // Verify the form if we are submitting or if jumping from the confirm step. if ("documentInfo".equals(params.get("step")) || "confirm".equals(flash.get("from-step"))) { verify(sub); } // If there are no errors then go to the next step if (params.get("submit_next") != null && !validation.hasErrors() ) { FileUpload.fileUpload(subId); } // List of valid degree years for drop-down population List<Integer> degreeYears = getDegreeYears(); renderArgs.put("degreeYears", degreeYears); // List of all document types List<String> docTypes = getValidDocumentTypes(sub); renderArgs.put("docTypes", docTypes); // List of all *active* Embargo Types List<EmbargoType> embargoTypes = settingRepo.findAllActiveEmbargoTypes(); renderArgs.put("embargoTypes", embargoTypes); // List of all subjects List<ProquestSubject> subjects = proquestRepo.findAllSubjects(); renderArgs.put("subjects", subjects); // List available committe roles List<CommitteeMemberRoleType> availableRoles = settingRepo.findAllCommitteeMemberRoleTypes(sub.getDegreeLevel()); renderArgs.put("availableRoles", availableRoles); // List of all languages List<Language> languages = settingRepo.findAllLanguages(); renderArgs.put("docLanguages", languages); // Figure out how mayn committee spots to show. int committeeSlots = 4; if (committee.size() > 3) committeeSlots = committee.size(); if (params.get("submit_add") != null) committeeSlots += 4; List<String> stickies = new ArrayList<String>(); String stickiesRaw = settingRepo.getConfigValue(SUBMIT_DOCUMENT_INFO_STICKIES); if (stickiesRaw != null && !"null".equals(stickiesRaw)) { try { CSVReader reader = new CSVReader(new StringReader(stickiesRaw)); stickies = Arrays.asList(reader.readNext()); reader.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } if (publishedMaterial != null) publishedMaterialFlag = true; renderTemplate("Submit/documentInfo.html", subId, stickies, title, degreeMonth, degreeYear, defenseDate, docType, abstractText, keywords, subjectPrimary, subjectSecondary, subjectTertiary, docLanguage, committeeSlots, committee, chairEmail, publishedMaterialFlag, publishedMaterial, embargo, umi); }
public static void documentInfo(Long subId) { // Validate the submission Submission sub = getSubmission(); // Get our form paramaters. String title = params.get("title"); String degreeMonth = params.get("degreeMonth"); String degreeYear = params.get("degreeYear"); Date defenseDate = null; DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); try { if(params.get("defenseDate")!=null && !"".equals(params.get("defenseDate").trim())) defenseDate = (Date)formatter.parse(params.get("defenseDate")); } catch (ParseException e) { validation.addError("defenseDate","Please format your defense date as mm/dd/yyyy"); } String docType = params.get("docType"); String abstractText = params.get("abstractText"); String keywords = params.get("keywords"); String subjectPrimary = params.get("subject-primary"); String subjectSecondary = params.get("subject-secondary"); String subjectTertiary = params.get("subject-tertiary"); String docLanguage = null; if(isFieldRequired(DOCUMENT_LANGUAGE) && settingRepo.findAllLanguages().size()==1) { docLanguage = settingRepo.findAllLanguages().get(0).getName(); } else { docLanguage = params.get("docLanguage"); if (docLanguage != null && docLanguage.trim().length() == 0) docLanguage = null; } Boolean publishedMaterialFlag = params.get("publishedMaterialFlag",Boolean.class); if (publishedMaterialFlag == null) publishedMaterialFlag = false; String publishedMaterial = params.get("publishedMaterial"); if (!publishedMaterialFlag) publishedMaterial = null; String chairEmail = params.get("chairEmail"); String embargo = params.get("embargo"); String umi = params.get("umi"); List<TransientMember> committee = parseCommitteeMembers(); if ("documentInfo".equals(params.get("step"))) { // Save the data if (isFieldEnabled(DOCUMENT_TITLE)) sub.setDocumentTitle(title); if (isFieldEnabled(GRADUATION_DATE)) { if (!isEmpty(degreeMonth)) { try { sub.setGraduationMonth(Integer.parseInt(degreeMonth)); } catch (RuntimeException re) { validation.addError("degreeMonth", "Please select a valid degree month"); } } else { sub.setGraduationMonth(null); } if (!isEmpty(degreeYear)) { try { sub.setGraduationYear(Integer.parseInt(degreeYear)); } catch (RuntimeException re) { validation.addError("degreeYear", "Please select a valid degree year"); } } else { sub.setGraduationYear(null); } } if (isFieldEnabled(DEFENSE_DATE)) { sub.setDefenseDate(defenseDate); } if (isFieldEnabled(DOCUMENT_TYPE)) sub.setDocumentType(docType); if (isFieldEnabled(DOCUMENT_ABSTRACT)) sub.setDocumentAbstract(abstractText); if (isFieldEnabled(DOCUMENT_KEYWORDS)) sub.setDocumentKeywords(keywords); if (isFieldEnabled(DOCUMENT_SUBJECTS)) { sub.getDocumentSubjects().clear(); if (!isEmpty(subjectPrimary)) sub.addDocumentSubject(subjectPrimary); if (!isEmpty(subjectSecondary)) sub.addDocumentSubject(subjectSecondary); if (!isEmpty(subjectTertiary)) sub.addDocumentSubject(subjectTertiary); } if (isFieldEnabled(DOCUMENT_LANGUAGE)) sub.setDocumentLanguage(docLanguage); if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL)) sub.setCommitteeContactEmail(chairEmail); if (isFieldEnabled(PUBLISHED_MATERIAL)) { if (publishedMaterialFlag) sub.setPublishedMaterial(publishedMaterial); else sub.setPublishedMaterial(null); } if (isFieldEnabled(EMBARGO_TYPE)) { try { sub.setEmbargoType(settingRepo.findEmbargoType(Long.parseLong(embargo))); } catch (RuntimeException re){ if (isFieldRequired(EMBARGO_TYPE)) validation.addError("embargo", "Please select a valid embargo option"); } } if (isFieldEnabled(UMI_RELEASE)) { if (umi != null && umi.trim().length() > 0) sub.setUMIRelease(true); else sub.setUMIRelease(false); } if (isFieldEnabled(COMMITTEE)) { try { saveCommitteeMembers(sub, committee); } catch (RuntimeException re){ /*ignore*/ } } sub.save(); } else { if (isFieldEnabled(DOCUMENT_TITLE)) title = sub.getDocumentTitle(); if (isFieldEnabled(GRADUATION_DATE) && sub.getGraduationMonth() != null) degreeMonth = sub.getGraduationMonth().toString(); if (isFieldEnabled(GRADUATION_DATE) && sub.getGraduationYear() != null) degreeYear = sub.getGraduationYear().toString(); if (isFieldEnabled(DEFENSE_DATE) && sub.getDefenseDate() != null) defenseDate = sub.getDefenseDate(); if (isFieldEnabled(DOCUMENT_TYPE)) docType = sub.getDocumentType(); if (isFieldEnabled(DOCUMENT_ABSTRACT)) abstractText = sub.getDocumentAbstract(); if (isFieldEnabled(DOCUMENT_KEYWORDS)) keywords = sub.getDocumentKeywords(); if (isFieldEnabled(DOCUMENT_SUBJECTS)) { List<String> subjects = sub.getDocumentSubjects(); if (subjects.size() > 0) subjectPrimary = subjects.get(0); if (subjects.size() > 1) subjectSecondary = subjects.get(1); if (subjects.size() > 2) subjectTertiary = subjects.get(2); } if (isFieldEnabled(DOCUMENT_LANGUAGE)) { docLanguage = sub.getDocumentLanguage(); } // Get the list of committee members if (isFieldEnabled(COMMITTEE)) committee = loadCommitteeMembers(sub); if (isFieldEnabled(COMMITTEE_CONTACT_EMAIL)) chairEmail = sub.getCommitteeContactEmail(); if (isFieldEnabled(PUBLISHED_MATERIAL)) publishedMaterial = sub.getPublishedMaterial(); if (isFieldEnabled(EMBARGO_TYPE) && sub.getEmbargoType() != null) embargo = sub.getEmbargoType().getId().toString(); if (isFieldEnabled(UMI_RELEASE) && sub.getUMIRelease() != null && sub.getUMIRelease() != false) umi = "true"; } // Verify the form if we are submitting or if jumping from the confirm step. if ("documentInfo".equals(params.get("step")) || "confirm".equals(flash.get("from-step"))) { verify(sub); } // If there are no errors then go to the next step if (params.get("submit_next") != null && !validation.hasErrors() ) { FileUpload.fileUpload(subId); } // List of valid degree years for drop-down population List<Integer> degreeYears = getDegreeYears(); renderArgs.put("degreeYears", degreeYears); // List of all document types List<String> docTypes = getValidDocumentTypes(sub); renderArgs.put("docTypes", docTypes); // List of all *active* Embargo Types List<EmbargoType> embargoTypes = settingRepo.findAllActiveEmbargoTypes(); renderArgs.put("embargoTypes", embargoTypes); // List of all subjects List<ProquestSubject> subjects = proquestRepo.findAllSubjects(); renderArgs.put("subjects", subjects); // List available committe roles List<CommitteeMemberRoleType> availableRoles = settingRepo.findAllCommitteeMemberRoleTypes(sub.getDegreeLevel()); renderArgs.put("availableRoles", availableRoles); // List of all languages List<Language> languages = settingRepo.findAllLanguages(); renderArgs.put("docLanguages", languages); // Figure out how mayn committee spots to show. int committeeSlots = 4; if (committee.size() > 3) committeeSlots = committee.size(); if (params.get("submit_add") != null) committeeSlots += 4; List<String> stickies = new ArrayList<String>(); String stickiesRaw = settingRepo.getConfigValue(SUBMIT_DOCUMENT_INFO_STICKIES); if (stickiesRaw != null && !"null".equals(stickiesRaw)) { try { CSVReader reader = new CSVReader(new StringReader(stickiesRaw)); stickies = Arrays.asList(reader.readNext()); reader.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } if (publishedMaterial != null) publishedMaterialFlag = true; renderTemplate("Submit/documentInfo.html", subId, stickies, title, degreeMonth, degreeYear, defenseDate, docType, abstractText, keywords, subjectPrimary, subjectSecondary, subjectTertiary, docLanguage, committeeSlots, committee, chairEmail, publishedMaterialFlag, publishedMaterial, embargo, umi); }
diff --git a/core/org.eclipse.ptp.launch/src/org/eclipse/ptp/launch/ParallelLaunchConfigurationDelegate.java b/core/org.eclipse.ptp.launch/src/org/eclipse/ptp/launch/ParallelLaunchConfigurationDelegate.java index 166a87470..699aa75c2 100644 --- a/core/org.eclipse.ptp.launch/src/org/eclipse/ptp/launch/ParallelLaunchConfigurationDelegate.java +++ b/core/org.eclipse.ptp.launch/src/org/eclipse/ptp/launch/ParallelLaunchConfigurationDelegate.java @@ -1,288 +1,288 @@ /******************************************************************************* * 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.launch; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.osgi.util.NLS; import org.eclipse.ptp.core.attributes.AttributeManager; import org.eclipse.ptp.core.elements.IPJob; import org.eclipse.ptp.core.elements.IResourceManager; import org.eclipse.ptp.core.elements.attributes.ElementAttributes; import org.eclipse.ptp.core.elements.attributes.JobAttributes; import org.eclipse.ptp.debug.core.IPDebugConfiguration; import org.eclipse.ptp.debug.core.IPDebugger; import org.eclipse.ptp.debug.core.IPSession; import org.eclipse.ptp.debug.core.PTPDebugCorePlugin; import org.eclipse.ptp.debug.core.launch.IPLaunch; import org.eclipse.ptp.debug.ui.IPTPDebugUIConstants; import org.eclipse.ptp.launch.internal.RuntimeProcess; import org.eclipse.ptp.launch.messages.Messages; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.WorkbenchException; /** * A launch configuration delegate for launching jobs via the * PTP resource manager mechanism. */ public class ParallelLaunchConfigurationDelegate extends AbstractParallelLaunchConfigurationDelegate { /* (non-Javadoc) * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor) */ public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (!(launch instanceof IPLaunch)) { throw new CoreException(new Status(IStatus.ERROR, PTPLaunchPlugin.PLUGIN_ID, Messages.ParallelLaunchConfigurationDelegate_Invalid_launch_object)); } if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask("", 250); //$NON-NLS-1$ monitor.setTaskName(NLS.bind(Messages.ParallelLaunchConfigurationDelegate_3, configuration.getName())); if (monitor.isCanceled()) return; IPDebugger debugger = null; monitor.worked(10); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_4); AttributeManager attrManager = getAttributeManager(configuration, mode); // All copy pre-"job submission" occurs here copyExecutable(configuration, monitor); doPreLaunchSynchronization(configuration, monitor); //switch perspective switchPerspective(DebugUITools.getLaunchPerspective(configuration.getType(), mode)); try { if (mode.equals(ILaunchManager.DEBUG_MODE)) { // show ptp debug view showPTPDebugView(IPTPDebugUIConstants.ID_VIEW_PARALLELDEBUG); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_6); /* * Create the debugger extension, then the connection point for the debug server. * The debug server is launched via the submitJob() command. */ IPDebugConfiguration debugConfig = getDebugConfig(configuration); debugger = debugConfig.getDebugger(); debugger.initialize(configuration, attrManager, monitor); if (monitor.isCanceled()) { return; } debugger.getLaunchAttributes(configuration, attrManager); attrManager.addAttribute(JobAttributes.getDebugFlagAttributeDefinition().create(true)); attrManager.addAttribute(JobAttributes.getDebuggerIdAttributeDefinition().create(debugConfig.getID())); } monitor.worked(10); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_7); submitJob(configuration, mode, (IPLaunch)launch, attrManager, debugger, monitor); monitor.worked(10); } catch (CoreException e) { - if (debugger != null && mode.equals(ILaunchManager.DEBUG_MODE)) { + if (debugger != null) { debugger.cleanup((IPLaunch)launch); } if (e.getStatus().getCode() != IStatus.CANCEL) throw e; } finally { monitor.done(); } } /** * Terminate a job. * * @param job job to terminate */ private void terminateJob(final IPJob job) { try { IResourceManager rm = job.getQueue().getResourceManager(); rm.terminateJob(job); } catch (CoreException e1) { // Ignore, but log PTPLaunchPlugin.log(e1); } } /* (non-Javadoc) * @see org.eclipse.ptp.launch.AbstractParallelLaunchConfigurationDelegate#doCleanupLaunch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.ptp.debug.core.launch.IPLaunch) */ @Override protected void doCleanupLaunch(ILaunchConfiguration configuration, String mode, IPLaunch launch) { if (mode.equals(ILaunchManager.DEBUG_MODE)) { try { IPDebugConfiguration debugConfig = getDebugConfig(configuration); IPDebugger debugger = debugConfig.getDebugger(); debugger.cleanup(launch); } catch (CoreException e) { PTPLaunchPlugin.log(e); } } } /* (non-Javadoc) * @see org.eclipse.ptp.launch.internal.AbstractParallelLaunchConfigurationDelegate#doCompleteJobLaunch(org.eclipse.ptp.core.elements.IPJob) */ @Override protected void doCompleteJobLaunch(ILaunchConfiguration configuration, String mode, final IPLaunch launch, AttributeManager mgr, final IPDebugger debugger, final IPJob job) { launch.setAttribute(ElementAttributes.getIdAttributeDefinition().getId(), job.getID()); if (mode.equals(ILaunchManager.DEBUG_MODE)) { launch.setPJob(job); try { setDefaultSourceLocator(launch, configuration); final IProject project = verifyProject(configuration); final IPath execPath = verifyExecutablePath(configuration); Display.getDefault().asyncExec(new Runnable() { public void run() { IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor.isCanceled()) { throw new InterruptedException(Messages.ParallelLaunchConfigurationDelegate_2); } monitor.beginTask(Messages.ParallelLaunchConfigurationDelegate_5, 1); try { IPSession session = PTPDebugCorePlugin.getDebugModel().createDebugSession(debugger, launch, project, execPath); String app = job.getAttribute(JobAttributes.getExecutableNameAttributeDefinition()).getValueAsString(); String path = job.getAttribute(JobAttributes.getExecutablePathAttributeDefinition()).getValueAsString(); String cwd = job.getAttribute(JobAttributes.getWorkingDirectoryAttributeDefinition()).getValueAsString(); List<String> args = job.getAttribute(JobAttributes.getProgramArgumentsAttributeDefinition()).getValue(); session.connectToDebugger(monitor, app, path, cwd, args.toArray(new String[args.size()])); } catch (CoreException e) { PTPDebugCorePlugin.getDebugModel().shutdownSession(job); throw new InvocationTargetException(e); } finally { monitor.done(); } } }; try { new ProgressMonitorDialog(PTPLaunchPlugin.getActiveWorkbenchShell()).run(true, true, runnable); } catch (InterruptedException e) { terminateJob(job); } catch (InvocationTargetException e) { PTPLaunchPlugin.errorDialog(Messages.ParallelLaunchConfigurationDelegate_0, e.getCause()); PTPLaunchPlugin.log(e.getCause()); terminateJob(job); } } }); } catch (final CoreException e) { /* * Completion of launch fails, then terminate the job and display error message. */ Display.getDefault().asyncExec(new Runnable() { public void run() { PTPLaunchPlugin.errorDialog(Messages.ParallelLaunchConfigurationDelegate_1, e.getStatus()); } }); PTPLaunchPlugin.log(e); terminateJob(job); } } else { new RuntimeProcess(launch, job, null); } } /** * Show the PTP Debug view * * @param viewID */ protected void showPTPDebugView(final String viewID) { Display display = Display.getCurrent(); if (display == null) { display = Display.getDefault(); } if (display != null && !display.isDisposed()) { display.syncExec(new Runnable() { public void run() { IWorkbenchWindow window = PTPLaunchPlugin.getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { try { page.showView(viewID, null, IWorkbenchPage.VIEW_CREATE); } catch (PartInitException e) {} } } } }); } } /** * Used to force switching to the PTP Debug perspective * * @param perspectiveID */ protected void switchPerspective(final String perspectiveID) { if (perspectiveID != null) { Display display = Display.getCurrent(); if (display == null) { display = Display.getDefault(); } if (display != null && !display.isDisposed()) { display.syncExec(new Runnable() { public void run() { IWorkbenchWindow window = PTPLaunchPlugin.getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { if (page.getPerspective().getId().equals(perspectiveID)) return; try { window.getWorkbench().showPerspective(perspectiveID, window); } catch (WorkbenchException e) { } } } } }); } } } }
true
true
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (!(launch instanceof IPLaunch)) { throw new CoreException(new Status(IStatus.ERROR, PTPLaunchPlugin.PLUGIN_ID, Messages.ParallelLaunchConfigurationDelegate_Invalid_launch_object)); } if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask("", 250); //$NON-NLS-1$ monitor.setTaskName(NLS.bind(Messages.ParallelLaunchConfigurationDelegate_3, configuration.getName())); if (monitor.isCanceled()) return; IPDebugger debugger = null; monitor.worked(10); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_4); AttributeManager attrManager = getAttributeManager(configuration, mode); // All copy pre-"job submission" occurs here copyExecutable(configuration, monitor); doPreLaunchSynchronization(configuration, monitor); //switch perspective switchPerspective(DebugUITools.getLaunchPerspective(configuration.getType(), mode)); try { if (mode.equals(ILaunchManager.DEBUG_MODE)) { // show ptp debug view showPTPDebugView(IPTPDebugUIConstants.ID_VIEW_PARALLELDEBUG); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_6); /* * Create the debugger extension, then the connection point for the debug server. * The debug server is launched via the submitJob() command. */ IPDebugConfiguration debugConfig = getDebugConfig(configuration); debugger = debugConfig.getDebugger(); debugger.initialize(configuration, attrManager, monitor); if (monitor.isCanceled()) { return; } debugger.getLaunchAttributes(configuration, attrManager); attrManager.addAttribute(JobAttributes.getDebugFlagAttributeDefinition().create(true)); attrManager.addAttribute(JobAttributes.getDebuggerIdAttributeDefinition().create(debugConfig.getID())); } monitor.worked(10); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_7); submitJob(configuration, mode, (IPLaunch)launch, attrManager, debugger, monitor); monitor.worked(10); } catch (CoreException e) { if (debugger != null && mode.equals(ILaunchManager.DEBUG_MODE)) { debugger.cleanup((IPLaunch)launch); } if (e.getStatus().getCode() != IStatus.CANCEL) throw e; } finally { monitor.done(); } }
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (!(launch instanceof IPLaunch)) { throw new CoreException(new Status(IStatus.ERROR, PTPLaunchPlugin.PLUGIN_ID, Messages.ParallelLaunchConfigurationDelegate_Invalid_launch_object)); } if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask("", 250); //$NON-NLS-1$ monitor.setTaskName(NLS.bind(Messages.ParallelLaunchConfigurationDelegate_3, configuration.getName())); if (monitor.isCanceled()) return; IPDebugger debugger = null; monitor.worked(10); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_4); AttributeManager attrManager = getAttributeManager(configuration, mode); // All copy pre-"job submission" occurs here copyExecutable(configuration, monitor); doPreLaunchSynchronization(configuration, monitor); //switch perspective switchPerspective(DebugUITools.getLaunchPerspective(configuration.getType(), mode)); try { if (mode.equals(ILaunchManager.DEBUG_MODE)) { // show ptp debug view showPTPDebugView(IPTPDebugUIConstants.ID_VIEW_PARALLELDEBUG); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_6); /* * Create the debugger extension, then the connection point for the debug server. * The debug server is launched via the submitJob() command. */ IPDebugConfiguration debugConfig = getDebugConfig(configuration); debugger = debugConfig.getDebugger(); debugger.initialize(configuration, attrManager, monitor); if (monitor.isCanceled()) { return; } debugger.getLaunchAttributes(configuration, attrManager); attrManager.addAttribute(JobAttributes.getDebugFlagAttributeDefinition().create(true)); attrManager.addAttribute(JobAttributes.getDebuggerIdAttributeDefinition().create(debugConfig.getID())); } monitor.worked(10); monitor.subTask(Messages.ParallelLaunchConfigurationDelegate_7); submitJob(configuration, mode, (IPLaunch)launch, attrManager, debugger, monitor); monitor.worked(10); } catch (CoreException e) { if (debugger != null) { debugger.cleanup((IPLaunch)launch); } if (e.getStatus().getCode() != IStatus.CANCEL) throw e; } finally { monitor.done(); } }
diff --git a/result-spi/src/main/java/no/schibstedsok/searchportal/result/BasicSearchResultItem.java b/result-spi/src/main/java/no/schibstedsok/searchportal/result/BasicSearchResultItem.java index c90aa4a03..1f78e2343 100644 --- a/result-spi/src/main/java/no/schibstedsok/searchportal/result/BasicSearchResultItem.java +++ b/result-spi/src/main/java/no/schibstedsok/searchportal/result/BasicSearchResultItem.java @@ -1,203 +1,207 @@ // Copyright (2006-2007) Schibsted Søk AS package no.schibstedsok.searchportal.result; import no.schibstedsok.searchportal.result.StringChopper; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import no.schibstedsok.searchportal.result.StringChopper; /** * A simple implementation of a search result item. * Is not multi-thread safe. * Mutates on setter methods. * Delegates all fields (of all types) to the one map. * * @author <a href="mailto:[email protected]">Magnus Eklund</a> * @version <tt>$Id$</tt> */ public class BasicSearchResultItem implements ResultItem { private static final String URL_KEY = "url"; private final HashMap<String,Serializable> fields = new HashMap<String,Serializable>(); /** * */ public BasicSearchResultItem(){} /** * * @param copy */ public BasicSearchResultItem(final ResultItem copy){ for(String fieldName : copy.getFieldNames()){ fields.put(fieldName, copy.getObjectField(fieldName)); } } /** * * @param field * @param value * @return */ public BasicSearchResultItem addField(final String field, final String value) { fields.put(field, value); return this; } /** * * @param field * @return */ public String getField(final String field) { final String fieldValue = (String) fields.get(field); if (fieldValue != null && (fieldValue.equals(" ") || fieldValue.equals(" "))) { return null; } else { return fieldValue; } } /** * * @param field * @return */ public Serializable getObjectField(final String field) { return fields.get(field); } /** * * @param field * @param value * @return */ public BasicSearchResultItem addObjectField(final String field, final Serializable value) { fields.put(field, value); return this; } /** * * @param field * @return */ public Integer getInteger(final String field) { final String fieldValue = (String) fields.get(field); return null != fieldValue ? Integer.parseInt(fieldValue) : null; } /** * * @param field * @param maxLength * @return */ public String getField(final String field, final int maxLength) { final String fieldValue = (String) fields.get(field); if (fieldValue != null) { if (fieldValue.equals(" ")) { return null; } else { return StringChopper.chop(fieldValue, maxLength); } } return fieldValue; } /** Returns a defensive copy of the field names existing in this resultItem. * * @return */ public Collection<String> getFieldNames() { return Collections.unmodifiableSet(fields.keySet()); } /** Returns a live copy of the field's collection. * * @param field * @return */ public Collection<String> getMultivaluedField(final String field) { return (Collection<String>) fields.get(field); } /** * * @param field * @param value * @return */ public BasicSearchResultItem addToMultivaluedField(final String field, final String value) { if (! fields.containsKey(field)) { fields.put(field, new ArrayList<String>()); } final Collection<String> previousValues = (Collection<String>) fields.get(field); previousValues.add(value); return this; } public boolean equals(final Object obj) { boolean result = false; if( obj instanceof ResultItem ){ final ResultItem other = (ResultItem) obj; // FIXME very specific undocumented stuff here if (other.getField("recordid") != null && getField("recordid") != null) { result = getField("recordid").equals(other.getField("recordid")); }else{ result = true; for(String fieldName : other.getFieldNames()){ - result &= other.getObjectField(fieldName).equals(getObjectField(fieldName)); - } + if (other.getObjectField(fieldName) == null) { + result &= null == getObjectField(fieldName); + } else { + result &= other.getObjectField(fieldName).equals(getObjectField(fieldName)); + } + } } }else{ result = super.equals(obj); } return result; } public int hashCode() { // FIXME very specific undocumented stuff here if (getField("recordid") != null) { return getField("recordid").hashCode(); } else { // there nothing else to this object than the fields map. return fields.hashCode(); } } public String getUrl() { return getField(URL_KEY); } public ResultItem setUrl(final String url) { return addField(URL_KEY, url); } }
true
true
public boolean equals(final Object obj) { boolean result = false; if( obj instanceof ResultItem ){ final ResultItem other = (ResultItem) obj; // FIXME very specific undocumented stuff here if (other.getField("recordid") != null && getField("recordid") != null) { result = getField("recordid").equals(other.getField("recordid")); }else{ result = true; for(String fieldName : other.getFieldNames()){ result &= other.getObjectField(fieldName).equals(getObjectField(fieldName)); } } }else{ result = super.equals(obj); } return result; }
public boolean equals(final Object obj) { boolean result = false; if( obj instanceof ResultItem ){ final ResultItem other = (ResultItem) obj; // FIXME very specific undocumented stuff here if (other.getField("recordid") != null && getField("recordid") != null) { result = getField("recordid").equals(other.getField("recordid")); }else{ result = true; for(String fieldName : other.getFieldNames()){ if (other.getObjectField(fieldName) == null) { result &= null == getObjectField(fieldName); } else { result &= other.getObjectField(fieldName).equals(getObjectField(fieldName)); } } } }else{ result = super.equals(obj); } return result; }
diff --git a/src/main/java/org/jenkinci/plugins/mock_slave/MockSlaveLauncher.java b/src/main/java/org/jenkinci/plugins/mock_slave/MockSlaveLauncher.java index e865820..c5613d3 100644 --- a/src/main/java/org/jenkinci/plugins/mock_slave/MockSlaveLauncher.java +++ b/src/main/java/org/jenkinci/plugins/mock_slave/MockSlaveLauncher.java @@ -1,91 +1,91 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinci.plugins.mock_slave; import hudson.EnvVars; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.remoting.Which; import hudson.slaves.ComputerLauncher; import hudson.slaves.SlaveComputer; import hudson.util.ProcessTree; import hudson.util.StreamCopyThread; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import java.util.logging.Logger; import org.kohsuke.stapler.DataBoundConstructor; public class MockSlaveLauncher extends ComputerLauncher { private static final Logger LOGGER = Logger.getLogger(MockSlaveLauncher.class.getName()); public final int latency; public final int bandwidth; @DataBoundConstructor public MockSlaveLauncher(int latency, int bandwidth) { this.latency = latency; this.bandwidth = bandwidth; } @Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { listener.getLogger().println("Launching"); ProcessBuilder pb = new ProcessBuilder("java", "-jar", Which.jarFile(Which.class).getAbsolutePath()); final EnvVars cookie = EnvVars.createCookie(); pb.environment().putAll(cookie); final Process proc = pb.start(); new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start(); InputStream is = proc.getInputStream(); OutputStream os = proc.getOutputStream(); if (latency > 0 || bandwidth > 0) { - listener.getLogger().printf("throttling with latency=%dms overhead=%dbpss%n", latency, bandwidth); + listener.getLogger().printf("throttling with latency=%dms bandwidth=%dbps%n", latency, bandwidth); Throttler t = new Throttler(latency, bandwidth, is, os); is = t.is(); os = t.os(); } computer.setChannel(is, os, listener.getLogger(), new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { try { ProcessTree.get().killAll(proc, cookie); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "interrupted", e); } } }); LOGGER.log(Level.INFO, "slave agent launched for {0}", computer.getDisplayName()); } @Extension public static class DescriptorImpl extends Descriptor<ComputerLauncher> { public String getDisplayName() { return "Mock Slave Launcher"; } } }
true
true
@Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { listener.getLogger().println("Launching"); ProcessBuilder pb = new ProcessBuilder("java", "-jar", Which.jarFile(Which.class).getAbsolutePath()); final EnvVars cookie = EnvVars.createCookie(); pb.environment().putAll(cookie); final Process proc = pb.start(); new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start(); InputStream is = proc.getInputStream(); OutputStream os = proc.getOutputStream(); if (latency > 0 || bandwidth > 0) { listener.getLogger().printf("throttling with latency=%dms overhead=%dbpss%n", latency, bandwidth); Throttler t = new Throttler(latency, bandwidth, is, os); is = t.is(); os = t.os(); } computer.setChannel(is, os, listener.getLogger(), new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { try { ProcessTree.get().killAll(proc, cookie); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "interrupted", e); } } }); LOGGER.log(Level.INFO, "slave agent launched for {0}", computer.getDisplayName()); }
@Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { listener.getLogger().println("Launching"); ProcessBuilder pb = new ProcessBuilder("java", "-jar", Which.jarFile(Which.class).getAbsolutePath()); final EnvVars cookie = EnvVars.createCookie(); pb.environment().putAll(cookie); final Process proc = pb.start(); new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start(); InputStream is = proc.getInputStream(); OutputStream os = proc.getOutputStream(); if (latency > 0 || bandwidth > 0) { listener.getLogger().printf("throttling with latency=%dms bandwidth=%dbps%n", latency, bandwidth); Throttler t = new Throttler(latency, bandwidth, is, os); is = t.is(); os = t.os(); } computer.setChannel(is, os, listener.getLogger(), new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { try { ProcessTree.get().killAll(proc, cookie); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "interrupted", e); } } }); LOGGER.log(Level.INFO, "slave agent launched for {0}", computer.getDisplayName()); }
diff --git a/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java b/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java index 1ed4866..820603a 100644 --- a/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java +++ b/src/main/java/fr/univnantes/atal/web/trashnao/security/TokenVerifier.java @@ -1,55 +1,56 @@ package fr.univnantes.atal.web.trashnao.security; import fr.univnantes.atal.web.trashnao.app.Constants; import fr.univnantes.atal.web.trashnao.model.User; import fr.univnantes.atal.web.trashnao.persistence.PMF; import java.io.InputStreamReader; import java.net.URL; import java.util.Map; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; public class TokenVerifier { static private ObjectMapper mapper = new ObjectMapper(); static private PersistenceManager pm = PMF.get().getPersistenceManager(); static public User getUser(HttpServletRequest request) { String accessToken = request.getParameter("access_token"); if (accessToken == null) { return null; } else { try { URL url = new URL( "https://www.googleapis.com/oauth2/v1/tokeninfo" + "?access_token=" + accessToken); Map<String, String> userData = mapper.readValue( new InputStreamReader(url.openStream(), "UTF-8"), new TypeReference<Map<String, String>>() { }); - if (userData.containsKey("error") + if (userData.get("audience") == null + || userData.containsKey("error") || !userData.get("audience") - .equals(Constants.clientId)) { + .equals(Constants.CLIENT_ID)) { return null; } else { String email = userData.get("email"), userId = userData.get("user_id"); User user; try { user = pm.getObjectById(User.class, email); } catch (JDOObjectNotFoundException ex) { user = new User(email, userId); pm.makePersistent(user); } return user; } } catch (Exception ex) { return null; } } } }
false
true
static public User getUser(HttpServletRequest request) { String accessToken = request.getParameter("access_token"); if (accessToken == null) { return null; } else { try { URL url = new URL( "https://www.googleapis.com/oauth2/v1/tokeninfo" + "?access_token=" + accessToken); Map<String, String> userData = mapper.readValue( new InputStreamReader(url.openStream(), "UTF-8"), new TypeReference<Map<String, String>>() { }); if (userData.containsKey("error") || !userData.get("audience") .equals(Constants.clientId)) { return null; } else { String email = userData.get("email"), userId = userData.get("user_id"); User user; try { user = pm.getObjectById(User.class, email); } catch (JDOObjectNotFoundException ex) { user = new User(email, userId); pm.makePersistent(user); } return user; } } catch (Exception ex) { return null; } } }
static public User getUser(HttpServletRequest request) { String accessToken = request.getParameter("access_token"); if (accessToken == null) { return null; } else { try { URL url = new URL( "https://www.googleapis.com/oauth2/v1/tokeninfo" + "?access_token=" + accessToken); Map<String, String> userData = mapper.readValue( new InputStreamReader(url.openStream(), "UTF-8"), new TypeReference<Map<String, String>>() { }); if (userData.get("audience") == null || userData.containsKey("error") || !userData.get("audience") .equals(Constants.CLIENT_ID)) { return null; } else { String email = userData.get("email"), userId = userData.get("user_id"); User user; try { user = pm.getObjectById(User.class, email); } catch (JDOObjectNotFoundException ex) { user = new User(email, userId); pm.makePersistent(user); } return user; } } catch (Exception ex) { return null; } } }
diff --git a/src/java/org/rapidcontext/core/data/HtmlSerializer.java b/src/java/org/rapidcontext/core/data/HtmlSerializer.java index 281de31..2f4962a 100644 --- a/src/java/org/rapidcontext/core/data/HtmlSerializer.java +++ b/src/java/org/rapidcontext/core/data/HtmlSerializer.java @@ -1,135 +1,135 @@ /* * RapidContext <http://www.rapidcontext.com/> * Copyright (c) 2007-2010 Per Cederberg. * All rights reserved. * * This program is free software: you can redistribute it and/or * modify it under the terms of the BSD license. * * 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 RapidContext LICENSE.txt file for more details. */ package org.rapidcontext.core.data; import org.apache.commons.lang.StringEscapeUtils; /** * A data object serializer for HTML. This class only attempts to * render a human-readable version of a data object, without any * efforts of making the result machine readable. It is only useful * for debugging or similar. The following basic requirements must be * met in order to serialize a data object:<p> * * <ul> * <li>No circular references are permitted. * <li>String, Integer, Boolean and Data objects are supported. * <li>Any Data object should be either an array or a map. * </ul> * * @author Per Cederberg, Dynabyte AB * @version 1.0 */ public class HtmlSerializer { /** * Serializes an object into an HTML representation. The string * returned can be used (without escaping) inside an HTML page. * * @param obj the object to convert, or null * * @return an HTML representation */ public static String serialize(Object obj) { StringBuilder buffer = new StringBuilder(); serialize(obj, buffer); return buffer.toString(); } /** * Serializes an object into an HTML representation. * * @param obj the object to convert * @param buffer the string buffer to append into */ private static void serialize(Object obj, StringBuilder buffer) { if (obj == null) { buffer.append("<code>N/A</code>"); } else if (obj instanceof Data) { serialize((Data) obj, buffer); } else { serialize(obj.toString(), buffer); } } /** * Serializes a data object into an HTML representation. If the * data contains array data, only the array values will be used. * Otherwise the key-value pairs will be listed in a table. * * @param data the data object to convert * @param buffer the string buffer to append into */ private static void serialize(Data data, StringBuilder buffer) { String[] keys; if (data == null) { buffer.append("<code>N/A</code>"); } else if (data.arraySize() >= 0) { buffer.append("<ol>\n"); for (int i = 0; i < data.arraySize(); i++) { buffer.append("<li>"); serialize(data.get(i), buffer); buffer.append("</li>\n"); } buffer.append("</ol>\n"); } else { keys = data.keys(); buffer.append("<table>\n<tbody>\n"); for (int i = 0; i < keys.length; i++) { buffer.append("<tr>\n<th>"); serialize(keys[i], buffer); buffer.append("</th>\n<td>"); serialize(data.get(keys[i]), buffer); buffer.append("</td>\n</tr>\n"); } - buffer.append("<tbody>\n<table>\n"); + buffer.append("</tbody>\n</table>\n"); } } /** * Serializes a text string into an HTML representation. If the * string contains a newline character, it will be wrapped in a * pre-tag. Otherwise it will only be properly HTML escaped. This * method also makes some rudimentary efforts to detect HTTP * links. * * @param str the text string to convert * @param buffer the string buffer to append into */ private static void serialize(String str, StringBuilder buffer) { if (str == null) { buffer.append("<code>N/A</code>"); } else { String html = StringEscapeUtils.escapeHtml(str); if (str.startsWith("http:")) { int pos = str.startsWith("http://") ? 0 : 5; buffer.append("<a href='"); buffer.append(html.substring(pos)); buffer.append("'>"); buffer.append(html.substring(pos)); buffer.append("</a>"); } else if (str.indexOf("\n") >= 0) { buffer.append("<pre>"); buffer.append(html.toString()); buffer.append("</pre>"); } else { buffer.append(html.toString()); } } } }
true
true
private static void serialize(Data data, StringBuilder buffer) { String[] keys; if (data == null) { buffer.append("<code>N/A</code>"); } else if (data.arraySize() >= 0) { buffer.append("<ol>\n"); for (int i = 0; i < data.arraySize(); i++) { buffer.append("<li>"); serialize(data.get(i), buffer); buffer.append("</li>\n"); } buffer.append("</ol>\n"); } else { keys = data.keys(); buffer.append("<table>\n<tbody>\n"); for (int i = 0; i < keys.length; i++) { buffer.append("<tr>\n<th>"); serialize(keys[i], buffer); buffer.append("</th>\n<td>"); serialize(data.get(keys[i]), buffer); buffer.append("</td>\n</tr>\n"); } buffer.append("<tbody>\n<table>\n"); } }
private static void serialize(Data data, StringBuilder buffer) { String[] keys; if (data == null) { buffer.append("<code>N/A</code>"); } else if (data.arraySize() >= 0) { buffer.append("<ol>\n"); for (int i = 0; i < data.arraySize(); i++) { buffer.append("<li>"); serialize(data.get(i), buffer); buffer.append("</li>\n"); } buffer.append("</ol>\n"); } else { keys = data.keys(); buffer.append("<table>\n<tbody>\n"); for (int i = 0; i < keys.length; i++) { buffer.append("<tr>\n<th>"); serialize(keys[i], buffer); buffer.append("</th>\n<td>"); serialize(data.get(keys[i]), buffer); buffer.append("</td>\n</tr>\n"); } buffer.append("</tbody>\n</table>\n"); } }
diff --git a/deegree-datastores/deegree-tilestores/deegree-tilestore-cache/src/main/java/org/deegree/tile/persistence/cache/CachingTileStoreProvider.java b/deegree-datastores/deegree-tilestores/deegree-tilestore-cache/src/main/java/org/deegree/tile/persistence/cache/CachingTileStoreProvider.java index b80078446d..35413b5900 100644 --- a/deegree-datastores/deegree-tilestores/deegree-tilestore-cache/src/main/java/org/deegree/tile/persistence/cache/CachingTileStoreProvider.java +++ b/deegree-datastores/deegree-tilestores/deegree-tilestore-cache/src/main/java/org/deegree/tile/persistence/cache/CachingTileStoreProvider.java @@ -1,138 +1,138 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ Occam Labs UG (haftungsbeschränkt) Godesberger Allee 139, 53175 Bonn Germany http://www.occamlabs.de/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.tile.persistence.cache; import static org.deegree.commons.xml.jaxb.JAXBUtils.unmarshall; import java.io.File; import java.net.URL; import java.util.Collections; import java.util.List; import net.sf.ehcache.CacheManager; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.config.ResourceInitException; import org.deegree.commons.config.ResourceManager; import org.deegree.tile.persistence.TileStore; import org.deegree.tile.persistence.TileStoreManager; import org.deegree.tile.persistence.TileStoreProvider; /** * The <code>GeoTIFFTileStoreProvider</code> provides a <code>TileMatrixSet</code> out of a GeoTIFF file (tiled * BIGTIFF). * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author: mschneider $ * * @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $ */ public class CachingTileStoreProvider implements TileStoreProvider { private static final URL SCHEMA = CachingTileStoreProvider.class.getResource( "/META-INF/schemas/datasource/tile/cache/3.2.0/cache.xsd" ); private DeegreeWorkspace workspace; @Override public void init( DeegreeWorkspace workspace ) { this.workspace = workspace; } @Override public CachingTileStore create( URL configUrl ) throws ResourceInitException { try { org.deegree.tile.persistence.cache.jaxb.CachingTileStore cfg; cfg = (org.deegree.tile.persistence.cache.jaxb.CachingTileStore) unmarshall( "org.deegree.tile.persistence.cache.jaxb", SCHEMA, configUrl, workspace ); TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); TileStore ts = mgr.get( cfg.getTileStoreId() ); if ( ts == null ) { throw new ResourceInitException( "The tile store with id " + cfg.getTileStoreId() + " is not available." ); } String cache = cfg.getCacheConfiguration(); File f = new File( cache ); if ( !f.isAbsolute() ) { - f = new File( new File( configUrl.toURI() ), cache ); + f = new File( new File( configUrl.toURI() ).getParentFile(), cache ); } CacheManager cmgr = new CacheManager( f.toURI().toURL() ); return new CachingTileStore( ts, cmgr, cfg.getCacheName() ); } catch ( Throwable e ) { throw new ResourceInitException( "Unable to create tile store.", e ); } } @SuppressWarnings("unchecked") @Override public Class<? extends ResourceManager>[] getDependencies() { return new Class[] {}; } @Override public String getConfigNamespace() { return "http://www.deegree.org/datasource/tile/cache"; } @Override public URL getConfigSchema() { return SCHEMA; } @Override public List<File> getTileStoreDependencies( File config ) { try { org.deegree.tile.persistence.cache.jaxb.CachingTileStore p; p = (org.deegree.tile.persistence.cache.jaxb.CachingTileStore) unmarshall( "org.deegree.tile.persistence.cache.jaxb", SCHEMA, config.toURI().toURL(), workspace ); return Collections.<File> singletonList( new File( config.getParentFile(), p.getTileStoreId() + ".xml" ) ); } catch ( Throwable e ) { // ignore here, will be parsed again anyway } return Collections.<File> emptyList(); } }
true
true
public CachingTileStore create( URL configUrl ) throws ResourceInitException { try { org.deegree.tile.persistence.cache.jaxb.CachingTileStore cfg; cfg = (org.deegree.tile.persistence.cache.jaxb.CachingTileStore) unmarshall( "org.deegree.tile.persistence.cache.jaxb", SCHEMA, configUrl, workspace ); TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); TileStore ts = mgr.get( cfg.getTileStoreId() ); if ( ts == null ) { throw new ResourceInitException( "The tile store with id " + cfg.getTileStoreId() + " is not available." ); } String cache = cfg.getCacheConfiguration(); File f = new File( cache ); if ( !f.isAbsolute() ) { f = new File( new File( configUrl.toURI() ), cache ); } CacheManager cmgr = new CacheManager( f.toURI().toURL() ); return new CachingTileStore( ts, cmgr, cfg.getCacheName() ); } catch ( Throwable e ) { throw new ResourceInitException( "Unable to create tile store.", e ); } }
public CachingTileStore create( URL configUrl ) throws ResourceInitException { try { org.deegree.tile.persistence.cache.jaxb.CachingTileStore cfg; cfg = (org.deegree.tile.persistence.cache.jaxb.CachingTileStore) unmarshall( "org.deegree.tile.persistence.cache.jaxb", SCHEMA, configUrl, workspace ); TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); TileStore ts = mgr.get( cfg.getTileStoreId() ); if ( ts == null ) { throw new ResourceInitException( "The tile store with id " + cfg.getTileStoreId() + " is not available." ); } String cache = cfg.getCacheConfiguration(); File f = new File( cache ); if ( !f.isAbsolute() ) { f = new File( new File( configUrl.toURI() ).getParentFile(), cache ); } CacheManager cmgr = new CacheManager( f.toURI().toURL() ); return new CachingTileStore( ts, cmgr, cfg.getCacheName() ); } catch ( Throwable e ) { throw new ResourceInitException( "Unable to create tile store.", e ); } }
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java index 902b45c0..9c35ef5d 100644 --- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java +++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/routing/hierarchical/management/Cluster.java @@ -1,1893 +1,1893 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * 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 de.tuilmenau.ics.fog.routing.hierarchical.management; import java.math.BigInteger; import java.util.HashMap; import java.util.LinkedList; import de.tuilmenau.ics.fog.bus.Bus; import de.tuilmenau.ics.fog.packets.hierarchical.clustering.RequestClusterMembership; import de.tuilmenau.ics.fog.packets.hierarchical.routing.RouteReport; import de.tuilmenau.ics.fog.routing.hierarchical.election.Elector; import de.tuilmenau.ics.fog.routing.hierarchical.HRMConfig; import de.tuilmenau.ics.fog.routing.hierarchical.HRMController; import de.tuilmenau.ics.fog.routing.hierarchical.RoutingEntry; import de.tuilmenau.ics.fog.routing.hierarchical.RoutingTable; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID; import de.tuilmenau.ics.fog.ui.Logging; /** * This class represents a cluster head at a defined hierarchy level. * At base hierarchy level, multiple Cluster instances may exist. However, at higher hierarchy levels, exactly one Cluster instance may exist. * Each Cluster instance may manage an unlimited amount of cluster members (-> ClusterMember). */ public class Cluster extends ClusterMember { /** * For using this class within (de-)serialization. */ private static final long serialVersionUID = -7486131336574637721L; /** * This is the cluster counter, which allows for globally (related to a physical simulation machine) unique cluster IDs. */ public static long sNextFreeClusterID = 1; /** * Stores a reference to the local coordinator instance if the local router is also the coordinator for this cluster */ private Coordinator mCoordinator = null; /** * Stores the connect inferior local coordinators. */ private LinkedList<Coordinator> mInferiorLocalCoordinators = new LinkedList<Coordinator>(); //TODO: register and auto-remove if coordinator is invalidated /** * Stores the connect inferior local coordinators. */ private LinkedList<CoordinatorProxy> mInferiorRemoteCoordinators = new LinkedList<CoordinatorProxy>(); //TODO: register and auto-remove if coordinatorProxy is invalidated /** * Stores a description of former GUICoordinatorIDs */ private String mDescriptionFormerGUICoordinatorIDs = ""; /** * Stores a list of the already used addresses */ private LinkedList<Integer> mUsedAddresses = new LinkedList<Integer>(); /** * Stores a list of the already reserved addresses */ private HashMap<Integer, ComChannel> mAddressReservations = new HashMap<Integer, ComChannel>(); /** * Stores how many address broadcasts were already sent */ private int mSentAddressBroadcast = 0; /** * Stores the local HRMID of the last address distribution event */ private HRMID mHRMIDLastDistribution = null; /** * Stores a description about the HRMID allocations */ private String mDescriptionHRMIDAllocation = new String(); /** * Stores the timeout for the next address distribution */ private double mAddressDistributionTimeout = 0; /** * Stores how many clusters were created per hierarchy level */ public static int mCreatedClusters[] = new int[HRMConfig.Hierarchy.HEIGHT]; /** * This is the constructor of a cluster object. At first such a cluster is identified by its cluster * ID and the hierarchical level. Later on - once a coordinator is found, it is additionally identified * by a token the coordinator sends to all participants. In contrast to the cluster token the identity is used * to filter potential participants that may be used for the election of a coordinator. * * Constructor * * @param pHRMController the local HRMController instance * @param pHierarchyLevel the hierarchy level * @param pClusterID the unique ID of this cluster, a value of "-1" triggers the creation of a new ID */ private Cluster(HRMController pHRMController, HierarchyLevel pHierarchyLevel, Long pClusterID) { super(pHRMController, pHierarchyLevel, null, -1, null); Logging.log(this, "CONSTRUCTOR got ClusterID: " + pClusterID); // set the ClusterID if ((pClusterID == null) || (pClusterID < 0)){ // create an ID for the cluster setClusterID(createClusterID()); Logging.log(this, "ClusterID - created unique clusterID " + getClusterID() + "(" + getGUIClusterID() + ")"); }else{ // use the ClusterID from outside setClusterID(pClusterID); Logging.log(this, "ClusterID - using pre-defined clusterID " + getClusterID() + "(" + getGUIClusterID() + ")"); } synchronized (mCreatedClusters) { mCreatedClusters[getHierarchyLevel().getValue()]++; } } /** * Factory function: create a cluster * * @param pHRMController the local HRMController instance * @param pHierarchyLevel the hierarchy level * @param pClusterID the unique ID of this cluster, a value of "-1" triggers the creation of a new ID * * @return the new Cluster object */ static public Cluster create(HRMController pHRMController, HierarchyLevel pHierarchyLevel, Long pClusterID) { Cluster tResult = new Cluster(pHRMController, pHierarchyLevel, pClusterID); Logging.log(tResult, "\n\n\n################ CREATED CLUSTER at hierarchy level: " + (tResult.getHierarchyLevel().getValue())); // register at HRMController's internal database pHRMController.registerCluster(tResult); // creates new elector object, which is responsible for election processes tResult.mElector = new Elector(pHRMController, tResult); return tResult; } /** * Factory function: create a base hierarchy level cluster * * @param pHrmController the local HRMController instance * * @return the new Cluster object */ static public Cluster createBaseCluster(HRMController pHrmController) { return create(pHrmController, HierarchyLevel.createBaseLevel(), null); } /** * Generates a new ClusterID * * @return the ClusterID */ static public synchronized long createClusterID() { // get the current unique ID counter long tResult = sNextFreeClusterID * idMachineMultiplier(); // make sure the next ID isn't equal sNextFreeClusterID++; return tResult; } /** * Counts all registered clusters * * @return the number of already created clusters */ public static long countCreatedClusters() { return (sNextFreeClusterID - 1); } /** * Creates a ClusterName object which describes this cluster * * @return the new ClusterName object */ public ClusterName createClusterName() { ClusterName tResult = null; tResult = new ClusterName(mHRMController, getHierarchyLevel(), getClusterID(), getCoordinatorID()); return tResult; } /** * Determines the coordinator of this cluster. It is "null" if the election was lost or hasn't finished yet. * * @return the cluster's coordinator */ @Override public Coordinator getCoordinator() { return mCoordinator; } /** * Determines if a coordinator is known. * * @return true if the coordinator is elected and known, otherwise false */ public boolean hasLocalCoordinator() { return (mCoordinator != null); } /** * Returns how many address broadcasts were already sent * * @return the number of broadcasts */ public int countAddressBroadcasts() { return mSentAddressBroadcast; } /** * EVENT: a cluster member requested explicitly a formerly assigned HRMID * * @param pComChannel the comm. channel to the cluster member * @param pHRMID the requested HRMID */ public void eventReceivedRequestedHRMID(ComChannel pComChannel, HRMID pHRMID) { boolean DEBUG = HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_DISTRIBUTION; if (DEBUG){ Logging.warn(this, "Handling RequestHRMID with requested HRMID " + pHRMID.toString() + " for: " + pComChannel); } HRMID tOldAssignedHRMID = pComChannel.getPeerHRMID(); if((getHRMID() != null) && ((!getHRMID().isZero()) || (getHierarchyLevel().isHighest()))){ int tRequestedAddress = pHRMID.getLevelAddress(getHierarchyLevel()); if (DEBUG){ Logging.warn(this, "Peer requested address: " + tRequestedAddress); } synchronized (mUsedAddresses) { synchronized (mAddressReservations) { if((!mAddressReservations.keySet().contains(tRequestedAddress)) || (mAddressReservations.get(tRequestedAddress).equals(pComChannel))){ HRMID tNewOldHRMID = getHRMID().clone(); tNewOldHRMID.setLevelAddress(getHierarchyLevel().getValue(), tRequestedAddress); if (DEBUG){ Logging.warn(this, " ..assignment of requested address " + tRequestedAddress + " is POSSIBLE"); } ComChannel tFormerOwner = null; /** * add as "reserved" address */ mAddressReservations.put(tRequestedAddress, pComChannel); /** * revoke the address from the old cluster member */ if(mUsedAddresses.contains(tRequestedAddress)){ LinkedList<ComChannel> tChannels = getComChannels(); for(ComChannel tChannel : tChannels){ if(!tChannel.equals(pComChannel)){ HRMID tAssignedHRMID = tChannel.getPeerHRMID(); if((tAssignedHRMID != null) && (tAssignedHRMID.equals(tNewOldHRMID))){ tFormerOwner = tChannel; if (DEBUG){ Logging.warn(this, " ..revoking requested address " + tNewOldHRMID + " from: " + tChannel); } tChannel.signalRevokeAssignedHRMIDs(); tChannel.setPeerHRMID(null); } } } } /** * assign the address to the requesting cluster member */ if (DEBUG){ Logging.warn(this, " ..assigning requested address " + tNewOldHRMID + " to: " + pComChannel); } pComChannel.setPeerHRMID(tNewOldHRMID); pComChannel.distributeAssignHRMID(tNewOldHRMID, true); /** * assign a new HRMID to the former owner channel */ if(tFormerOwner != null){ tFormerOwner.setPeerHRMID(null); eventClusterMemberNeedsHRMID(tFormerOwner, this + "eventRequestedHRMID() for: " + pComChannel); } }else{ if (DEBUG){ Logging.warn(this, " ..assignment of requested address " + tRequestedAddress + " is IMPOSSIBLE, enforcing the assignment of " + tOldAssignedHRMID); Logging.warn(this, " ..current reservations are: " + mAddressReservations); } pComChannel.distributeAssignHRMID(tOldAssignedHRMID, true); } } } }else{ if (DEBUG){ Logging.warn(this, "eventRequestedHRMID() skipped because the own HRMID is invalid: " + getHRMID()); } } } /** * EVENT: cluster needs HRMIDs * This function sets a timer for a new address distribution */ public synchronized void eventClusterNeedsHRMIDs() { Logging.log(this, "EVENT: cluster needs new HRMIDs"); mAddressDistributionTimeout = mHRMController.getSimulationTime() + HRMConfig.Addressing.DELAY_ADDRESS_DISTRIBUTION; } /** * Checks if it is time to distribute address * * @return true or false */ public boolean isTimeToDistributeAddresses() { boolean tResult = false; /** * avoid address distribution until hierarchy seems to be stable */ if(mHRMController.getTimeWithStableHierarchy() > 2 * HRMConfig.Hierarchy.COORDINATOR_ANNOUNCEMENTS_INTERVAL){ if (mAddressDistributionTimeout > 0){ /** * make sure we wait for some time after we distribute addresses */ if(mAddressDistributionTimeout < mHRMController.getSimulationTime()){ tResult = true; } } } return tResult; } /** * DISTRIBUTE: distribute addresses among cluster members if: * + an HRMID was received from a superior coordinator, used to distribute HRMIDs downwards the hierarchy, * + we were announced as coordinator * This function is called for distributing HRMIDs among the cluster members. * Moreover, it implements the recursive address distribution. * */ public void distributeAddresses() { boolean DEBUG = HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_DISTRIBUTION; // reset timer for address distribution mAddressDistributionTimeout = 0; HRMID tOwnHRMID = getHRMID(); boolean tClusterIsTopOfHierarchy = getHierarchyLevel().isHighest(); boolean tNewL0HRMID = false; if((tOwnHRMID != null) || (tClusterIsTopOfHierarchy)){ // lock in order to avoid parallel execution of eventReceivedRequestHRMID synchronized (mUsedAddresses) { // do we have a new HRMID since the last call? // if ((mHRMIDLastDistribution == null) || (!mHRMIDLastDistribution.equals(tOwnHRMID))){ // update the stored HRMID mHRMIDLastDistribution = tOwnHRMID; /** * reset list of already used addresses */ mUsedAddresses.clear(); /** * Distribute addresses */ if ((tClusterIsTopOfHierarchy) || ((tOwnHRMID != null) && ((HRMConfig.Addressing.DISTRIBUTE_RELATIVE_ADDRESSES) || (!tOwnHRMID.isRelativeAddress()) /* we already have been assigned a valid HRMID? */))){ mSentAddressBroadcast++; if(DEBUG){ Logging.warn(this, "#### DISTRIBUTING ADDRESSES [" + mSentAddressBroadcast + "] to entities on level " + getHierarchyLevel().getValue() + "/" + (HRMConfig.Hierarchy.HEIGHT - 1)); } /** * Assign ourself an HRMID address */ // are we at the base level? if(getHierarchyLevel().isBaseLevel()) { // get the old L0 HRMID HRMID tOldL0HRMID = getL0HRMID(); /** * Check we should actually assign a new L0 HRMID */ if((tOldL0HRMID == null) || (tOldL0HRMID.isZero()) || (tOldL0HRMID.isRelativeAddress()) || (!tOldL0HRMID.isCluster(getHRMID()))){ // create new HRMID for ourself HRMID tThisNodesAddress = allocateClusterMemberAddress(); if((tThisNodesAddress != null) && (!tThisNodesAddress.equals(getL0HRMID()))){ // inform HRM controller about the address change if(getL0HRMID() != null){ // free only if the assigned new address has a different used cluster address if(tThisNodesAddress.getLevelAddress(getHierarchyLevel()) != getL0HRMID().getLevelAddress(getHierarchyLevel())){ mDescriptionHRMIDAllocation += "\n ..revoked " + getL0HRMID().toString() + " for " + this + ", cause=distributeAddresses() [" + mSentAddressBroadcast + "]"; freeClusterMemberAddress(getL0HRMID().getLevelAddress(getHierarchyLevel())); } } mDescriptionHRMIDAllocation += "\n .." + tThisNodesAddress.toString() + " for " + this + ", cause=distributeAddresses() [" + mSentAddressBroadcast + "]"; if(DEBUG){ Logging.warn(this, " ..setting local HRMID " + tThisNodesAddress.toString()); } // store the new HRMID for this node if(DEBUG){ Logging.warn(this, "distributeAddresses() [" + mSentAddressBroadcast + "] sets new L0HRMID: " + tThisNodesAddress); } setL0HRMID(tThisNodesAddress); tNewL0HRMID = true; }else{ if(tThisNodesAddress == null){ throw new RuntimeException(this + "::distributeAddresses() got a zero HRMID from allocateClusterMemberAddress()"); } // free the allocated address again freeClusterMemberAddress(tThisNodesAddress.getLevelAddress(getHierarchyLevel())); } }else{ int tUsedOldAddress = tOldL0HRMID.getLevelAddress(getHierarchyLevel()); // do a refresh here -> otherwise, the local L0 might not been updated in case the clustering switched to an alternative/parallel cluster if(DEBUG){ Logging.warn(this, " ..refreshing L0 HRMID: " + tOldL0HRMID + " (used addr.: " + tUsedOldAddress + ")"); } mUsedAddresses.add(tUsedOldAddress); setL0HRMID(tOldL0HRMID); } } if(tClusterIsTopOfHierarchy){ setHRMID(this, new HRMID(0)); } /** * Distribute AssignHRMID packets among the cluster members */ LinkedList<ComChannel> tComChannels = getComChannels(); if(DEBUG){ Logging.warn(this, " ..distributing HRMIDs among cluster members: " + tComChannels); } int i = 0; for(ComChannel tComChannel : tComChannels) { /** * Trigger: cluster member needs HRMID */ eventClusterMemberNeedsHRMID(tComChannel, "distributeAddresses() [" + mSentAddressBroadcast + "]"); if(DEBUG){ Logging.warn(this, " ..[" + i + "]: assigned " + tComChannel.getPeerHRMID() + " to: " + tComChannel); } i++; } /** * Announce the local node HRMIDs if we are at base hierarchy level */ if(tNewL0HRMID){ LinkedList<ClusterMember> tL0ClusterMembers = mHRMController.getAllL0ClusterMembers(); for(ClusterMember tL0ClusterMember : tL0ClusterMembers){ if(DEBUG){ Logging.warn(this, "distributeAddresses() [" + mSentAddressBroadcast + "] triggers an AnnounceHRMID for: " + tL0ClusterMember + " with HRMIDs: " + mHRMController.getHRMIDs()); } tL0ClusterMember.distributeAnnounceHRMIDs(); } } } // }else{ // Logging.log(this, "distributeAddresses() skipped because the own HRMID is still the same: " + getHRMID()); // } } }else{ mDescriptionHRMIDAllocation += "\n ..aborted distributeAddresses() because of own HRMID: " + tOwnHRMID; if(DEBUG){ Logging.warn(this, "distributeAddresses() skipped because the own HRMID is still invalid: " + getHRMID()); } } } /** * EVENT: new HRMID assigned * The function is called when an address update was received. * * @param pSourceComChannel the source comm. channel * @param pHRMID the new HRMID * @param pIsFirmAddress is this address firm? * * @return true if the signaled address was accepted, other (a former address is requested from the peer) false */ @Override public boolean eventAssignedHRMID(ComChannel pSourceComChannel, HRMID pHRMID, boolean pIsFirmAddress) { boolean DEBUG = HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_DISTRIBUTION; boolean tResult = false; if (DEBUG){ Logging.log(this, "Handling AssignHRMID with assigned HRMID " + pHRMID.toString()); } if((pHRMID != null) && (!pHRMID.isZero())){ // setHRMID() tResult = super.eventAssignedHRMID(pSourceComChannel, pHRMID, pIsFirmAddress); if(tResult){ /** * Automatic address distribution via this cluster */ if (hasLocalCoordinator()){ // we should automatically continue the address distribution? if (HRMController.GUI_USER_CTRL_ADDRESS_DISTRUTION){ if (DEBUG){ Logging.log(this, " ..continuing the address distribution process via this cluster"); } distributeAddresses(); applyAddressToAlternativeClusters(pHRMID); } }else{ if (DEBUG){ Logging.log(this, " ..stopping address propagation here"); } } } } return tResult; } /** * Assign new HRMID for being addressable. * * @param pCaller the caller who assigns the new HRMID * @param pHRMID the new HRMID */ @Override public void setHRMID(Object pCaller, HRMID pHRMID) { Logging.log(this, "Got new HRMID: " + pHRMID + ", caller=" + pCaller); /** * Do we have a new HRMID? */ freeAllClusterMemberAddresses("setHRMID() for " + pHRMID); /** * Set the new HRMID */ super.setHRMID(pCaller, pHRMID); // /** // * Update the local HRG: find other active Cluster instances and store a local loopback link to them // */ // LinkedList<Cluster> tSiblings = mHRMController.getAllClusters(getHierarchyLevel()); // // iterate over all siblings // for(Cluster tSibling : tSiblings){ // if(tSibling.isActiveCluster()){ // Logging.log(this, " ..found active sibling: " + tSibling); // HRMID tSiblingAddress = tSibling.getHRMID(); // HRMID tSiblingL0Address = tSibling.getL0HRMID(); // // has the sibling a valid address? // if((tSiblingAddress != null) && (!tSiblingAddress.isZero())){ // // avoid recursion // if(!tSibling.equals(this)){ // // create the new reported routing table entry // RoutingEntry tRoutingEntryToSibling = RoutingEntry.create(getL0HRMID() /* this cluster */, tSiblingAddress /* the sibling */, tSiblingL0Address, 0 /* loopback route */, RoutingEntry.NO_UTILIZATION, RoutingEntry.NO_DELAY, RoutingEntry.INFINITE_DATARATE); // // register the new HRG entry // mHRMController.registerCluster2ClusterLinkHRG(getHRMID(), tSiblingAddress, tRoutingEntryToSibling); // } // } // } // } } /** * Resets the list of used cluster addresses * * @param pCause the cause for this reset */ private void freeAllClusterMemberAddresses(String pCause) { /** * Reset the list of used addresses because we got a new HRMID */ synchronized (mUsedAddresses) { Logging.log(this, "Resetting list of used addresses: " + mUsedAddresses); mUsedAddresses.clear(); synchronized (mAddressReservations) { mAddressReservations.clear(); } mDescriptionHRMIDAllocation += "\n ..reset list of used cluster addresses" + ", cause=" + pCause; } } /** * Allocates a new HRMID for a cluster member. * * @return the allocated HRMID for the cluster member */ private HRMID allocateClusterMemberAddress() { HRMID tResult = (getHRMID() != null ? getHRMID().clone() : null); if(getHierarchyLevel().isHighest()){ tResult = new HRMID(0); } if(tResult != null){ /** * Search for the lowest free address */ int tUsedAddress = 0; synchronized (mUsedAddresses) { // iterate over all possible addresses for(tUsedAddress = 1; tUsedAddress < 1024 /* TODO: 2 ^ digits from HRMConfig */; tUsedAddress++){ // have we found a free address? if((!mUsedAddresses.contains(tUsedAddress)) && (!mAddressReservations.keySet().contains(tUsedAddress))){ /** * NEW HRMID: update address usage */ mUsedAddresses.add(tUsedAddress); Logging.log(this, "Allocated ClusterMember address: " + tUsedAddress); break; } } } // transform the member number to a BigInteger BigInteger tAddress = BigInteger.valueOf(tUsedAddress); // set the member number for the given hierarchy level tResult.setLevelAddress(getHierarchyLevel(), tAddress); // some debug outputs if (HRMConfig.DebugOutput.GUI_HRMID_UPDATES){ Logging.log(this, "Set " + tAddress + " on hierarchy level " + getHierarchyLevel().getValue() + " for HRMID " + tResult.toString()); Logging.log(this, "Created for a cluster member the NEW HRMID=" + tResult.toString()); } } return tResult; } /** * Frees an allocated cluster member address. * * @param pAddress the address which should be freed */ private void freeClusterMemberAddress(int pAddress) { synchronized (mUsedAddresses) { if(mUsedAddresses.contains(pAddress)){ mUsedAddresses.remove(new Integer(pAddress)); synchronized (mAddressReservations) { mAddressReservations.remove(new Integer(pAddress)); } Logging.log(this, "Freed ClusterMember address: " + pAddress); } } } /** * Returns the list of used addresses * * @return the list */ @SuppressWarnings("unchecked") public LinkedList<Integer> getUsedAddresses() { LinkedList<Integer> tResult = null; Logging.log(this, "Having allocated these HRMIDs: " + mDescriptionHRMIDAllocation); synchronized (mUsedAddresses) { tResult = (LinkedList<Integer>) mUsedAddresses.clone(); } return tResult; } /** * Returns the list of used addresses * * @return the list */ @SuppressWarnings("unchecked") public HashMap<Integer, ComChannel> getReservedAddresses() { HashMap<Integer, ComChannel> tResult = null; Logging.log(this, "Having reserved these HRMIDs: " + mDescriptionHRMIDAllocation); synchronized (mAddressReservations) { tResult = (HashMap<Integer, ComChannel>) mAddressReservations.clone(); } return tResult; } /** * EVENT: cluster member needs HRMID * * @param pComChannel the comm. channel towards the cluster member, which needs a new HRMID * @param pCause the cause for this event */ private void eventClusterMemberNeedsHRMID(ComChannel pComChannel, String pCause) { boolean DEBUG = HRMConfig.DebugOutput.GUI_SHOW_ADDRESS_DISTRIBUTION; if(DEBUG){ Logging.warn(this, "EVENT: Cluster_Member_Needs_HRMID for: " + pComChannel + ", cause=" + pCause); Logging.warn(this, " ..used address: " + mUsedAddresses); } //TODO: auto - abort if getHRMID() == null /** * AUTO ADDRESS DISTRIBUTION */ if (HRMController.GUI_USER_CTRL_ADDRESS_DISTRUTION){ /** * get the old HRMID */ HRMID tOldHRMIDForPeer = pComChannel.getPeerHRMID(); /** * look for old reservations */ if(mAddressReservations.containsValue(pComChannel)){ for(Integer tUsedAddress : mAddressReservations.keySet()){ if(mAddressReservations.get(tUsedAddress).equals(pComChannel)){ HRMID tHRMID = getHRMID().clone(); tHRMID.setLevelAddress(getHierarchyLevel().getValue(), tUsedAddress); tOldHRMIDForPeer = tHRMID; break; } } } int tOldUsedAddress = (tOldHRMIDForPeer != null ? tOldHRMIDForPeer.getLevelAddress(getHierarchyLevel()) : -1); HRMID tHRMIDForPeer = null; /** * Check old assignment */ if(DEBUG){ Logging.warn(this, " ..old peer HRMID: " + tOldHRMIDForPeer + "(lvl.: " + (tOldHRMIDForPeer != null ? tOldHRMIDForPeer.getHierarchyLevel() : "-1") + ") for " + pComChannel); } if(!HRMConfig.Addressing.REUSE_ADDRESSES){ if(DEBUG){ Logging.warn(this, " ..reseting the old HRMID to null because address reusage is disabled"); } tOldHRMIDForPeer = null; } /** * OLD HRMID: update address usage */ boolean tOldAddrAlreadyUsed = mUsedAddresses.contains(tOldUsedAddress); /** * Check if we should actually assign a NEW HRMID */ boolean tOldAddrReservered = ((mAddressReservations.keySet().contains(tOldUsedAddress)) && (!mAddressReservations.get(tOldUsedAddress).equals(pComChannel))); boolean tOldAddressHasInvalidLvl = ((tOldHRMIDForPeer != null ? tOldHRMIDForPeer.getHierarchyLevel() : -1) != getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.warn(this, " .." + tOldHRMIDForPeer + " => already used: " + tOldAddrAlreadyUsed + ", reserved for other: " + tOldAddrReservered + (tOldAddrReservered ? "(" + mAddressReservations.get(tOldUsedAddress).getPeer() + ")": "") + ", invalid hier. lvl.: " + tOldAddressHasInvalidLvl); } if((tOldHRMIDForPeer == null) || (tOldHRMIDForPeer.isZero()) || (tOldHRMIDForPeer.isRelativeAddress()) || (tOldAddrReservered) || (tOldAddressHasInvalidLvl) || (tOldAddrAlreadyUsed) || ((!tOldHRMIDForPeer.isCluster(getHRMID()) && (!getHierarchyLevel().isHighest())))){ HRMID tNewHRMIDForPeer = allocateClusterMemberAddress(); if(tNewHRMIDForPeer != null){ mDescriptionHRMIDAllocation += "\n .." + tNewHRMIDForPeer.toString() + " for " + pComChannel + ", cause=" + pCause; /** * Abort if we shouldn't distribute relative addresses */ if((!HRMConfig.Addressing.DISTRIBUTE_RELATIVE_ADDRESSES) && (tNewHRMIDForPeer.isRelativeAddress())){ //Logging.warn(this, "eventClusterMemberNeedsHRMID() aborted because the relative address shouldn't be distributed: " + tNewHRMIDForPeer); mDescriptionHRMIDAllocation += "\n ..revoked " + tNewHRMIDForPeer.toString() + " for " + pComChannel + ", cause=" + pCause; freeClusterMemberAddress(tNewHRMIDForPeer.getLevelAddress(getHierarchyLevel())); return; } // store the HRMID under which the peer will be addressable from now pComChannel.setPeerHRMID(tNewHRMIDForPeer); // register this new HRMID in the local HRS and create a mapping to the right L2Address if(!tNewHRMIDForPeer.isClusterAddress()){ if(DEBUG){ Logging.warn(this, " ..creating MAPPING " + tNewHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address() + ", L2 route=" + mHRMController.getHRS().getL2RouteViaNetworkInterface(pComChannel.getPeerL2Address(), getBaseHierarchyLevelNetworkInterface())); } mHRMController.getHRS().mapHRMID(tNewHRMIDForPeer, pComChannel.getPeerL2Address(), mHRMController.getHRS().getL2RouteViaNetworkInterface(pComChannel.getPeerL2Address(), getBaseHierarchyLevelNetworkInterface())); } /** * USE NEW HRMID */ tHRMIDForPeer = tNewHRMIDForPeer; }else{ Logging.err(this, "::eventClusterMemberNeedsHRMID() got the invalid new cluster member address [" + tNewHRMIDForPeer + "] for: " + pComChannel); } }else{ mDescriptionHRMIDAllocation += "\n ..reassigned " + tOldHRMIDForPeer.toString() + " for " + pComChannel + ", cause=" + pCause; if(DEBUG){ Logging.warn(this, " ..reassigning " + tOldHRMIDForPeer.toString() + " for " + pComChannel); } /** * USE OLD HRMID */ tHRMIDForPeer = tOldHRMIDForPeer; if(!mUsedAddresses.contains(tOldUsedAddress)){ if(DEBUG){ Logging.warn(this, " ..mark the address as used in this cluster"); } // add the peer address to the used addresses mUsedAddresses.add(tOldUsedAddress); } } // send the packet in every case if(tHRMIDForPeer != null){ if(DEBUG){ if ((pComChannel.getPeerHRMID() != null) && (!pComChannel.getPeerHRMID().equals(tHRMIDForPeer))){ Logging.warn(this, " ..replacing HRMID " + pComChannel.getPeerHRMID().toString() + " and assign new HRMID " + tHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address()); }else Logging.warn(this, " ..assigning new HRMID " + tHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address()); } pComChannel.distributeAssignHRMID(tHRMIDForPeer, false); }else{ mDescriptionHRMIDAllocation += "\n ..invalid HRMID for " + pComChannel + ", cause=" + pCause; Logging.warn(this, "eventClusterMemberNeedsHRMID() detected invalid cluster HRMID and cannot signal new HRMID to: " + pComChannel); } }else{ if(DEBUG){ Logging.warn(this, "Address distribution is deactivated, no new assigned HRMID for: " + pComChannel); } } } /** * EVENT: all cluster addresses are invalid */ public void eventAllClusterAddressesInvalid() { Logging.log(this, "EVENT: all cluster addresses got declared invalid"); setHRMID(this, null); /** * Revoke all HRMIDs from the cluster members */ LinkedList<ComChannel> tComChannels = getComChannels(); int i = 0; for (ComChannel tComChannel : tComChannels){ /** * Unregister all HRMID-2-L2Address mappings */ for(HRMID tHRMIDForPeer:tComChannel.getAssignedPeerHRMIDs()){ // register this new HRMID in the local HRS and create a mapping to the right L2Address Logging.log(this, " ..removing MAPPING " + tHRMIDForPeer.toString() + " to " + tComChannel.getPeerL2Address()); mHRMController.getHRS().unmapHRMID(tHRMIDForPeer); } /** * Revoke all assigned HRMIDs from peers */ Logging.log(this, " ..[" + i + "]: revoking HRMIDs via: " + tComChannel); tComChannel.signalRevokeAssignedHRMIDs(); i++; } /** * Reset the list of used addresses */ freeAllClusterMemberAddresses("eventAllClusterAddressesInvalid()"); } /** * EVENT: new local coordinator, triggered by the Coordinator * * @param pCoordinator the new coordinator, which is located on this node */ public void eventNewLocalCoordinator(Coordinator pCoordinator) { Logging.log(this, "EVENT: new local coordinator: " + pCoordinator + ", old one is: " + mCoordinator); // set the coordinator mCoordinator = pCoordinator; /** * Update cluster activation */ if(pCoordinator != null){ // mark this cluster as active setClusterWithValidCoordinator(true); }else{ // mark this cluster as inactive setClusterWithValidCoordinator(false); } // update the stored unique ID for the coordinator if (pCoordinator != null){ setSuperiorCoordinatorID(pCoordinator.getCoordinatorID()); setCoordinatorID(pCoordinator.getCoordinatorID()); // update the descriptive string about the coordinator setSuperiorCoordinatorDescription(mCoordinator.toLocation()); }else{ setSuperiorCoordinatorID(0); setCoordinatorID(0); setSuperiorCoordinatorDescription(""); } } /** * Detects the local neighborhood. * IMPORTANT: This is the main function for determining capacities and link usage */ @Override public void detectNeighborhood() { double tStartTime = mHRMController.getSimulationTime(); String tTimeStr = ""; if(hasClusterValidCoordinator()){ if(getHierarchyLevel().isBaseLevel()){ super.detectNeighborhood(); tTimeStr += "\n -> super.detectNeighborhood: " + (mHRMController.getSimulationTime() - tStartTime); if(countConnectedRemoteClusterMembers() > 1){ if(getBaseHierarchyLevelNetworkInterface() != null){ // get the physical BUS Bus tPhysicalBus = (Bus)getBaseHierarchyLevelNetworkInterface().getBus(); // iterate over all comm. channels for(ComChannel tOuterChannel : getComChannels()){ HRMID tOuterHRMID = tOuterChannel.getPeerHRMID(); for(ComChannel tInnerChannel : getComChannels()){ HRMID tInnerHRMID = tInnerChannel.getPeerHRMID(); if((tOuterHRMID != null) && (tInnerHRMID != null)){ if(!tOuterHRMID.equals(tInnerHRMID)){ //Logging.log(this, " .." + tOuterHRMID + " is BUS neighbor of: " + tInnerHRMID); RoutingEntry tEntryForward = RoutingEntry.createRouteToDirectNeighbor(tOuterHRMID, tInnerHRMID, tInnerHRMID, tPhysicalBus.getUtilization(), tPhysicalBus.getDelayMSec(), tPhysicalBus.getAvailableDataRate(), this + "::detectNeighborhood()"); tEntryForward.setNextHopL2Address(tInnerChannel.getPeerL2Address()); mHRMController.registerAutoHRG(tEntryForward); tTimeStr += "\n -> registerAutoHRG forward: " + (mHRMController.getSimulationTime() - tStartTime); RoutingEntry tEntryBackward = RoutingEntry.createRouteToDirectNeighbor(tInnerHRMID, tOuterHRMID, tOuterHRMID, tPhysicalBus.getUtilization(), tPhysicalBus.getDelayMSec(), tPhysicalBus.getAvailableDataRate(), this + "::detectNeighborhood()"); tEntryBackward.setNextHopL2Address(tOuterChannel.getPeerL2Address()); mHRMController.registerAutoHRG(tEntryBackward); tTimeStr += "\n -> registerAutoHRG backward: " + (mHRMController.getSimulationTime() - tStartTime); } } } } } } }else{ Logging.err(this, "detectNeighborhood() expects base hierarchy level"); } } double tDuration = mHRMController.getSimulationTime() - tStartTime; if(tDuration > 0.5){ Logging.err(this, "detectNeighborhood took " + tDuration + " sec." + tTimeStr); } } /** * Returns the machine-local ClusterID (excluding the machine specific multiplier) * * @return the machine-local ClusterID */ public long getGUIClusterID() { if (getClusterID() != null) return getClusterID() / idMachineMultiplier(); else return -1; } /** * EVENT: coordinator lost */ public void eventCoordinatorLost() { Logging.log(this, "EVENT: coordinator was lost"); // reset timer for address distribution mAddressDistributionTimeout = 0; /** * Revoke HRMID of physical node if we are on base hierarchy level */ if(getHierarchyLevel().isBaseLevel()){ if(getL0HRMID() != null){ Logging.log(this, "Unregistering physical node HRMID: " + getL0HRMID()); mDescriptionHRMIDAllocation += "\n ..revoked " + getL0HRMID().toString() + " for " + this + ", cause=eventCoordinatorLost()"; freeClusterMemberAddress(getL0HRMID().getLevelAddress(getHierarchyLevel())); mHRMController.unregisterHRMID(this, getL0HRMID(), this + "::eventCoordinatorLost()"); } } // store the former coordinator ID mDescriptionFormerGUICoordinatorIDs += " " + Long.toString(getGUICoordinatorID()); // unregister coordinator eventNewLocalCoordinator(null); } /** * Returns a description of the former GUICoordinatorIDs * * @return the description */ public String getDescriptionFormerGUICoordinatorIDs() { return mDescriptionFormerGUICoordinatorIDs; } /** * Returns the comm. channel to a given peer entity * * @param pPeer the peer entitiy * * @return the found comm. channel */ public ComChannel getComChannelToMember(ControlEntity pPeer) { ComChannel tResult = null; LinkedList<ComChannel> tChannels = getComChannels(); for(ComChannel tComChannel : tChannels){ if(pPeer.equals(tComChannel.getPeer())){ tResult = tComChannel; break; } } return tResult; } /** * TODO: move this to the coordinator * EVENT: RouteReport from an inferior entity received, triggered by the comm. channel * * @param pComChannel the source comm. channel * @param pRouteReportPacket the packet (use packet for better debugging here) * @param pDeprecatedRoutingTable the routing table with deprecated entries */ public void eventReceivedRouteReport(ComChannel pSourceComChannel, RouteReport pRouteReportPacket, RoutingTable pDeprecatedRoutingTable) { boolean DEBUG = HRMConfig.DebugOutput.SHOW_REPORT_PHASE; // if(getHierarchyLevel().isBaseLevel()){ // DEBUG = true; // } if(DEBUG){ Logging.log(this, "EVENT: ReceivedRouteReport: " + pRouteReportPacket + " from " + pSourceComChannel.getPeerL2Address()); } /** * mark deprecated entries for a near deletion */ if((pDeprecatedRoutingTable != null) && (pDeprecatedRoutingTable.size() > 0)){ Logging.warn(this, "Found deprecated reported routing table: " + pDeprecatedRoutingTable); for(RoutingEntry tDeprecatedEntry : pDeprecatedRoutingTable){ if(HRMConfig.DebugOutput.GUI_SHOW_ROUTE_DEPRECATIONS){ Logging.warn(this, " ..found deprecated reported routing entry: " + tDeprecatedEntry); } /** * Set the timeout for deprecated reported routes to a short time period */ tDeprecatedEntry.setTimeout(mHRMController.getSimulationTime() + HRMConfig.Routing.ROUTE_TIMEOUT + HRMConfig.Hierarchy.MAX_E2E_DELAY); /** * Mark as reported entry */ tDeprecatedEntry.setReportedLink(pSourceComChannel.getPeerHRMID()); /** * Update the HRG in such a way that the deprecated will be removed automatically very soon if no other inferior coordinator reports the same route with a high timeout (the route is still known as active there) */ int tHopCount = tDeprecatedEntry.getHopCount(); switch(tHopCount) { case 0: // it's an inter-cluster link because local loopbacks aren't sent as report tDeprecatedEntry.extendCause(this + "::eventReceivedRouteReport()(0 hops) from " + pSourceComChannel.getPeerHRMID()); mHRMController.registerAutoHRG(tDeprecatedEntry); break; case 1: default: // 2+ // do we have an intra-cluster link? if((!tDeprecatedEntry.getDest().isClusterAddress()) && (tDeprecatedEntry.getDest().equals(tDeprecatedEntry.getLastNextHop()))){ tDeprecatedEntry.extendCause(this + "::eventReceivedRouteReport()(1 hop) from " + pSourceComChannel.getPeerHRMID()); mHRMController.registerLinkHRG(tDeprecatedEntry.getSource(), tDeprecatedEntry.getLastNextHop(), tDeprecatedEntry); }else{ // strange, an inter-cluster link with ONE hop?! } break; } } DEBUG = true; } /** * Iterate over all reported routes and derive new data for the HRG */ RoutingTable tNewReportedRoutingTable = pRouteReportPacket.getRoutes(); for(RoutingEntry tEntry : tNewReportedRoutingTable){ if(DEBUG){ Logging.log(this, " ..received route: " + tEntry); } double tBefore = HRMController.getRealTime(); /** * make sure a relative timeout is set in the reported routing table entry */ if(tEntry.getTimeout() <= 0){ tEntry.setTimeout(HRMConfig.Routing.ROUTE_TIMEOUT + HRMConfig.Hierarchy.MAX_E2E_DELAY); } /** * Set the timeout for reported routes: use the previously stored relative timeout value from the reporter and form an absolute timeout */ tEntry.setTimeout(mHRMController.getSimulationTime() + tEntry.getTimeout()); /** * Mark as reported entry */ tEntry.setReportedLink(pSourceComChannel.getPeerHRMID()); /** * Update the HRG */ int tHopCount = tEntry.getHopCount(); switch(tHopCount) { case 0: // it's an inter-cluster link because local loopbacks aren't sent as report tEntry.extendCause(this + "::eventReceivedRouteReport()(0 hops) from " + pSourceComChannel.getPeerHRMID()); /** * Check if the reported link is already reported by a local inferior coordinator. * * For example, the local coordinator 1.0.0 exists and the foreign coordinator 2.0.0 reports a link from (1.0.0 <==> 2.0.0). * In this case, the local coordinator 1.0.0 has already registered the corresponding HRG links. */ // HRMID tFromCluster = tEntry.getNextHop().getForeignCluster(tEntry.getSource()); // HRMID tToCluster = tEntry.getSource().getForeignCluster(tEntry.getNextHop()); // boolean tLinkAlreadyKnown = false; // LinkedList<Coordinator> tLocalInferiorCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1); // for(Coordinator tCoordinator : tLocalInferiorCoordinators){ // if((tFromCluster.equals(tCoordinator.getHRMID())) || (tToCluster.equals(tCoordinator.getHRMID()))){ // if(DEBUG){ // Logging.log(this, " ..route already known between " + tFromCluster + " and " + tToCluster + ", route=" + tEntry); // } // tLinkAlreadyKnown = true; // } // } // if(!tLinkAlreadyKnown){ mHRMController.registerAutoHRG(tEntry); // }else{ // if(DEBUG){ // Logging.log(this, " ..dropping uninteresting reported route: " + tEntry); // } // } break; case 1: default: // 2+ // do we have an intra-cluster link? if((!tEntry.getDest().isClusterAddress()) && (tEntry.getDest().equals(tEntry.getLastNextHop()))){ tEntry.extendCause(this + "::eventReceivedRouteReport()(1 hop) from " + pSourceComChannel.getPeerHRMID()); mHRMController.registerLinkHRG(tEntry.getSource(), tEntry.getLastNextHop(), tEntry); }else{ // strange, an inter-cluster link with ONE hop?! } break; } double tSpentTime = HRMController.getRealTime() - tBefore; if(tSpentTime > 30){ Logging.log(this, " ..eventReceivedRouteReport() for entry with " + tHopCount + " hops took " + tSpentTime + " ms for processing " + tEntry + " of route report: " + pRouteReportPacket); } // /** // * Does the next hop lead to a foreign cluster? // */ // if(tDestHRMID.isClusterAddress()){ // // is it a route from a physical node to the next one, which belongs to the destination cluster? // if(pRoutingEntry.isRouteToDirectNeighbor()){ // // register automatically new links in the HRG based on pRoutingEntry // registerAutoHRG(pRoutingEntry); // } // }else{ // pRoutingEntry.extendCause(this + "::addHRMRoute()_2"); // if(HRMConfig.DebugOutput.GUI_SHOW_HRG_UPDATES){ // Logging.log(this, " ..registering (" + mCallsAddHRMRoute + ") nodeHRMID-2-nodeHRMID HRG link for: " + pRoutingEntry); // } // registerLinkHRG(pRoutingEntry.getSource(), pRoutingEntry.getNextHop(), pRoutingEntry); // } // HRMID tDestHRMID = tEntry.getDest(); // HRMID tOwnClusterAddress = getHRMID(); // if(tDestHRMID != null){ // // search for cluster destinations // if(tDestHRMID.isClusterAddress()){ // // avoid recursion // if(!tDestHRMID.equals(tOwnClusterAddress)){ // if(HRMConfig.DebugOutput.SHOW_SHARE_PHASE){ // Logging.log(this, " ..route between clusters found"); // } // // /** // * Store/update link in the HRG // */ //// mHRMController.registerCluster2ClusterLinkHRG(tEntry.getSource(), tDestHRMID, tEntry); // } // } // }else{ // Logging.err(this, "Invalid route received: " + tEntry); // } } } /** * Returns all known inferior remote coordinators * * @return the list of known inferior coordinators */ public LinkedList<CoordinatorProxy> getAllInferiorRemoteCoordinators() { LinkedList<CoordinatorProxy> tResult = null; synchronized (mInferiorRemoteCoordinators) { tResult = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } return tResult; } /** * EVENT: "lost cluster member", triggered by Elector in case a member left the election * @param pComChannel the comm. channel of the lost cluster member * @param pCause the cause for the call */ public synchronized void eventClusterMemberLost(ComChannel pComChannel, String pCause) { Logging.log(this, "EVENT: lost cluster member behind: " + pComChannel + "\n cause=" + pCause); /** * Unregister all HRMID-2-L2Address mappings */ for(HRMID tHRMIDForPeer : pComChannel.getAssignedPeerHRMIDs()){ // unregister the old HRMID fom the local HRS and remove the mapping to the corresponding L2Address Logging.log(this, " ..removing MAPPING " + tHRMIDForPeer.toString() + " to " + pComChannel.getPeerL2Address()); mHRMController.getHRS().unmapHRMID(tHRMIDForPeer); } /** * Free the previously allocated cluster address */ HRMID tPeerHRMID = pComChannel.getPeerHRMID(); if((tPeerHRMID != null) && (!tPeerHRMID.isZero())){ mDescriptionHRMIDAllocation += "\n ..revoked " + tPeerHRMID.toString() + " for " + pComChannel + ", cause=eventClusterMemberLost()"; freeClusterMemberAddress(tPeerHRMID.getLevelAddress(getHierarchyLevel())); } /** * Unregister the comm. channel */ unregisterComChannel(pComChannel, this + "::eventClusterMemberLost()\n ^^^^" + pCause); ControlEntity tChannelPeer = pComChannel.getPeer(); if (tChannelPeer != null){ /** * Update ARG */ mHRMController.unregisterLinkARG(this, tChannelPeer); /** * Update locally stored database about inferior entities */ // does this comm. channel end at a local coordinator? if(tChannelPeer instanceof Coordinator){ synchronized (mInferiorLocalCoordinators) { if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, " ..removing local cluster member: " + tChannelPeer); } if(mInferiorLocalCoordinators.contains(tChannelPeer)){ mInferiorLocalCoordinators.remove(tChannelPeer); }else{ Logging.log(this, "Local inferior coordinator was already removed: " + tChannelPeer); } } }else // does this comm. channel end at a remote coordinator (a coordinator proxy)? if(tChannelPeer instanceof CoordinatorProxy){ synchronized (mInferiorRemoteCoordinators) { if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, " ..removing remote cluster member: " + tChannelPeer); } if(mInferiorRemoteCoordinators.contains(tChannelPeer)){ mInferiorRemoteCoordinators.remove(tChannelPeer); }else{ Logging.log(this, "Remote inferior coordinator was already removed: " + tChannelPeer); } } }else{ Logging.err(this, "Comm. channel peer has unsupported type: " + tChannelPeer); } } if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, " ..remaining comm. channels: " + getComChannels()); Logging.log(this, " ..remaining connected local coordinators: " + mInferiorLocalCoordinators); Logging.log(this, " ..remaining connected remote coordinators: " + mInferiorRemoteCoordinators); } // check necessity boolean tClusterStillNeeded = isClusterNeeded(); if(tClusterStillNeeded){ /** * Trigger: "lost candidate" for election */ if(isThisEntityValid()){ mElector.eventLostCandidate(pComChannel); } /** * Trigger: number of members changed */ eventNumberOfMembersChanged(); } } /** * EVENT: number of members have changed */ private void eventNumberOfMembersChanged() { if(getHierarchyLevel().isBaseLevel()){ if(HRMConfig.Hierarchy.AUTO_DETECT_AND_SEPRATE_GATEWAYS){ if(countConnectedRemoteClusterMembers() > 1){ if(!enforcesASSplit()){ Logging.warn(this, "This node is gateway - separate this cluster also as own L1 cluster"); setASSplit(true, true); } }else{ if(enforcesASSplit()){ Logging.warn(this, "This node is not anymore a gateway - merge the superior L1 cluster with the surrounding"); setASSplit(false, true); } } } } // it's time to update the GUI mHRMController.notifyGUI(this); } /** * Checks the necessity of the cluster */ private boolean isClusterNeeded() { boolean tResult = true; Logging.log(this, "Checking necessity of this cluster"); // no further external candidates available/known (all candidates are gone) or has the last local inferior coordinator left the area? if ((countConnectedClusterMembers() < 1 /* do we still have cluster members? */) || (mInferiorLocalCoordinators.size() == 0 /* has the last local coordinator left this cluster? */)){ Logging.log(this, "checkClusterNecessity() detected an unneeded cluster"); tResult = false; /** * TRIGGER: cluster invalid */ eventClusterRoleInvalid(); } return tResult; } /** * EVENT: cluster role invalid */ public synchronized void eventClusterRoleInvalid() { Logging.log(this, "============ EVENT: cluster role invalid"); if(isThisEntityValid()){ /** * Trigger: role invalid */ eventInvalidation(); /** * TRIGGER: event coordinator role invalid */ if (getCoordinator() != null){ Logging.log(this, " ..eventClusterRoleInvalid() invalidates now the local coordinator: " + getCoordinator()); getCoordinator().eventCoordinatorRoleInvalid(); }else{ Logging.log(this, "eventClusterInvalid() can't deactivate the coordinator because there is none"); } Logging.log(this, "============ EVENT: canceling all memberships"); Logging.log(this, " ..knowing these comm. channels: " + getComChannels()); LinkedList<ComChannel> tcomChannels = getComChannels(); for(ComChannel tComChannel: tcomChannels){ Logging.log(this, " ..cancelling: " + tComChannel); /** * Check if we have already received an ACK for the ClusterMembershipRequest packet */ if(!tComChannel.isOpen()){ // enforce "open" state for this comm. channel Logging.log(this, " ..enforcing OPEN state for this comm. channel: " + tComChannel); tComChannel.eventEstablished(); } /** * Destroy the channel */ unregisterComChannel(tComChannel, this + "::eventClusterRoleInvalid()"); } /** * Unregister from local databases */ Logging.log(this, "============ Destroying this cluster now..."); // unregister the HRMID for this node from the HRM controller if(getL0HRMID() != null){ mDescriptionHRMIDAllocation += "\n ..revoked " + getL0HRMID().toString() + " for " + this + ", cause=eventClusterRoleInvalid()"; freeClusterMemberAddress(getL0HRMID().getLevelAddress(getHierarchyLevel())); mHRMController.unregisterHRMID(this, getL0HRMID(), this + "::eventClusterRoleInvalid()"); } // unregister from HRMController's internal database mHRMController.unregisterCluster(this); }else{ Logging.warn(this, "This Cluster is already invalid"); } } /** * EVENT: detected additional cluster member, the event is triggered by the comm. channel * * @param pComChannel the comm. channel of the new cluster member */ public synchronized void eventClusterMemberJoined(ComChannel pComChannel) { Logging.log(this, "EVENT: joined cluster member, comm. channel: " + pComChannel); /** * Update ARG */ ControlEntity tChannelPeer = pComChannel.getPeer(); if (tChannelPeer != null){ if (tChannelPeer instanceof Coordinator){ mHRMController.registerLinkARG(this, tChannelPeer, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.LOCAL_CONNECTION)); }else if(tChannelPeer instanceof CoordinatorProxy){ mHRMController.registerLinkARG(this, tChannelPeer, new AbstractRoutingGraphLink(AbstractRoutingGraphLink.LinkType.REMOTE_CONNECTION)); }else{ Logging.err(this, "Peer (" + pComChannel.getPeer() + " is unsuported for channel: " + pComChannel); } }else{ if(!getHierarchyLevel().isBaseLevel()){ Logging.err(this, "Cannot link to invalid peer for channel: " + pComChannel); }else{ // we are at base hierarchy level: the peer object is a ClusterMember object at a foreign node, there doesn't exist a representation for this entity on this node } } /** * Trigger: comm. channel established */ eventComChannelEstablished(pComChannel); /** * Trigger: assign new HRMID */ if (hasLocalCoordinator()){ if(pComChannel.getPeerHRMID() == null){ eventClusterMemberNeedsHRMID(pComChannel, "eventClusterMemberJoined()"); }else{ Logging.log(this, "eventClusterMemberJoined() found an already existing peer HRMID for joined cluster member behind: " + pComChannel); } }else{ Logging.log(this, "Coordinator missing, we cannot assign a new HRMID to the joined cluster member behind comm. channel: " + pComChannel); } eventNumberOfMembersChanged(); } /** * Establishes a communication channel * * @param pComSession the parent comm. session for the new channel * @param pRemoteEndPointName the remote EP describing ClusterName * @param pLocalEndpointName the local EP describing ClusterName * @param pPeer the control entity which represents the peer */ private void establishComChannel(ComSession pComSession, ClusterName pRemoteEndPointName, ClusterName pLocalEndpointName, ControlEntity pPeer) { Logging.log(this, "Establishing comm. channel to peer=" + pPeer + "(remoteEP=" + pRemoteEndPointName + ", localEP=" + pLocalEndpointName +")"); /** * Create communication channel */ Logging.log(this, " ..creating new communication channel"); ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, this, pComSession, pPeer); tComChannel.setRemoteClusterName(pLocalEndpointName); tComChannel.setPeerPriority(pPeer.getPriority()); /** * Send "RequestClusterMembership" along the comm. session * HINT: we cannot use the created channel because the remote side doesn't know anything about the new comm. channel yet) */ RequestClusterMembership tRequestClusterMembership = new RequestClusterMembership(mHRMController.getNodeL2Address(), pComSession.getPeerL2Address(), createClusterName(), pRemoteEndPointName); //tRequestClusterMembership.activateTracking(); Logging.log(this, " ..sending membership request: " + tRequestClusterMembership); tComChannel.storePacket(tRequestClusterMembership, true); if (pComSession.write(tRequestClusterMembership)){ Logging.log(this, " ..requested successfully for membership of: " + pPeer); }else{ Logging.err(this, " ..failed to request for membership of: " + pPeer); } } /** * Distributes cluster membership requests * * HINT: This function has to be called in a separate thread because it starts new connections and calls blocking functions * */ private int mCountDistributeMembershipRequests = 0; public synchronized void updateClusterMembers() { boolean DEBUG = HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS; boolean tChanges = false; mCountDistributeMembershipRequests ++; /************************************* * Update local coordinators ************************************/ if(DEBUG){ Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR LOCAL COORDINATORS STARTED (call nr: " + mCountDistributeMembershipRequests + ")"); } if(isThisEntityValid()){ LinkedList<Coordinator> tCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.log(this, " ..inferior local coordinators: " + tCoordinators.size()); } /** * Copy list of inferior local coordinators */ LinkedList<Coordinator> tOldInferiorLocalCoordinators = null; synchronized (mInferiorLocalCoordinators) { tOldInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone(); } /** * Iterate over all found inferior local coordinators */ synchronized (tOldInferiorLocalCoordinators) { if(mCountDistributeMembershipRequests > 1){ if(DEBUG){ Logging.log(this, " ..having connections to these inferior local coordinators: " + tOldInferiorLocalCoordinators.toString()); } } for (Coordinator tCoordinator : tCoordinators){ if (!tOldInferiorLocalCoordinators.contains(tCoordinator)){ if(DEBUG){ Logging.log(this, " ..found inferior local coordinator [NEW]: " + tCoordinator); } // add this local coordinator to the list of connected coordinators synchronized (mInferiorLocalCoordinators) { if(!mInferiorLocalCoordinators.contains(tCoordinator)){ mInferiorLocalCoordinators.add(tCoordinator); }else{ Logging.err(this, "Cannot add a duplicate of the local inferior coordinator: " + tCoordinator); } } if(DEBUG){ Logging.log(this, " ..get/create communication session"); } ComSession tComSession = mHRMController.getCreateComSession(mHRMController.getNodeL2Address(), this + "::updateClusterMembers()_1"); if (tComSession != null){ /** * Create coordinator name for this coordinator */ ClusterName tRemoteEndPointName = tCoordinator.createCoordinatorName(); ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID()); /** * Establish the comm. channel */ establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinator); tChanges = true; }else{ - Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator); + Logging.warn(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator); } }else{ if(DEBUG){ Logging.log(this, " ..found inferior local coordinator [already connected]: " + tCoordinator); } } } if(DEBUG){ Logging.log(this, " ..finished clustering of local inferior coordinators"); } /************************************ * Update remote coordinators ************************************/ if(mInferiorLocalCoordinators.size() > 0){ if(DEBUG){ Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR REMOTE COORDINATORS STARTED"); } LinkedList<CoordinatorProxy> tCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.log(this, " ..inferior remote coordinators: " + tCoordinatorProxies.size()); } /** * Copy list of known inferior remote coordinators */ LinkedList<CoordinatorProxy> tOldInferiorRemoteCoordinators = null; synchronized (mInferiorRemoteCoordinators) { tOldInferiorRemoteCoordinators = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } /************************************ * Drop old (invalid) remote coordinators ************************************/ synchronized (tOldInferiorRemoteCoordinators) { for(CoordinatorProxy tCoordintorProxy : tOldInferiorRemoteCoordinators){ if(DEBUG){ Logging.log(this, "Found inferior remote coordinator behind proxy: " + tCoordintorProxy); } if(!tCoordintorProxy.isThisEntityValid()){ if(DEBUG){ Logging.log(this, "Found already invalidated coordinator proxy: " + tCoordintorProxy); } ComChannel tComChannelToRemoteCoordinator = getComChannelToMember(tCoordintorProxy); if(tComChannelToRemoteCoordinator != null){ if(DEBUG){ Logging.log(this, " ..comm. channel is: " + tComChannelToRemoteCoordinator); Logging.log(this, " ..deactivating membership of: " + tCoordintorProxy); } //TODO: alternative is: tComChannelToRemoteCoordinator.setTimeout(this + "::updateClusterMembers()"); eventClusterMemberLost(tComChannelToRemoteCoordinator, this + "::updateClusterMembers() detected invalid remote coordinator behind: " + tCoordintorProxy); tChanges = true; } } } } /************************************ * Drop deprecated entry in list of connected remote coordinators ************************************/ synchronized (mInferiorRemoteCoordinators) { LinkedList<CoordinatorProxy> tAllCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().dec().getValue()); for(CoordinatorProxy tCoordintorProxy : tAllCoordinatorProxies){ if(mInferiorRemoteCoordinators.contains(tCoordintorProxy)){ if(tCoordintorProxy.isThisEntityValid()){ ComChannel tComChannelToRemoteCoordinator = getComChannelToMember(tCoordintorProxy); if(tComChannelToRemoteCoordinator == null){ if(DEBUG){ Logging.warn(this, "Found temporary invalided and returned coordinator proxy: " + tCoordintorProxy); } mInferiorRemoteCoordinators.remove(tCoordintorProxy); tOldInferiorRemoteCoordinators = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } } } } } /************************************* * Detect new remote coordinators ************************************/ if(tCoordinatorProxies.size() > 0){ synchronized (tOldInferiorRemoteCoordinators) { if(mCountDistributeMembershipRequests > 1){ if(DEBUG){ Logging.log(this, " ..having connections to these inferior remote coordinators: "); for(CoordinatorProxy tProxy : tOldInferiorRemoteCoordinators){ Logging.log(this, " ..: " + tProxy); } } } for (CoordinatorProxy tCoordinatorProxy : tCoordinatorProxies){ if (!tOldInferiorRemoteCoordinators.contains(tCoordinatorProxy)){ if(DEBUG){ Logging.log(this, " ..found remote inferior coordinator[NEW]: " + tCoordinatorProxy); } // add this remote coordinator to the list of connected coordinators synchronized (mInferiorRemoteCoordinators) { if(!mInferiorRemoteCoordinators.contains(tCoordinatorProxy)){ if(DEBUG){ Logging.log(this, " ..adding to connected remote inferior coordinators: " + tCoordinatorProxy); } mInferiorRemoteCoordinators.add(tCoordinatorProxy); }else{ Logging.err(this, "Cannot add a duplicate of the remote inferior coordinator: " + tCoordinatorProxy); } } ComSession tComSession = mHRMController.getCreateComSession(tCoordinatorProxy.getCoordinatorNodeL2Address(), this + "::updateClusterMembers()_2"); if (tComSession != null){ /** * Create coordinator name for this coordinator proxy */ ClusterName tRemoteEndPointName = tCoordinatorProxy.createCoordinatorName(); ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID()); /** * Establish the comm. channel */ establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinatorProxy); tChanges = true; }else{ Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + tCoordinatorProxy.getCoordinatorNodeL2Address() + " for remote coordinator: " + tCoordinatorProxy); } }else{ if(DEBUG){ Logging.log(this, " ..found inferior remote coordinator [already connected]: " + tCoordinatorProxy); } } } } }else{ /** * Trigger: detected local isolation */ eventDetectedIsolation(); } }else{ if(DEBUG){ Logging.log(this, " ..no local inferior coordinators existing"); } } } }else{ Logging.warn(this, "updateClusterMembers() skipped because cluster role is already invalidated"); } // finally, check the necessity of this cluster again if(!isClusterNeeded()){ tChanges = false; } /** * trigger election update if changes happened */ if(tChanges){ Logging.log(this, "updateClusterMembers[" + mCountDistributeMembershipRequests + "] triggers a re-election due to topology changes"); mElector.startElection(this + "::updateClusterMembers()[" + mCountDistributeMembershipRequests + "]"); }else{ Logging.log(this, "updateClusterMembers[" + mCountDistributeMembershipRequests + "] detected no topology changes"); } } /** * EVENT: detected isolation */ private void eventDetectedIsolation() { if(HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS){ Logging.log(this, "EVENT: detected local isolation"); } } /** * Defines the decoration text for the ARG viewer * * @return text for the control entity or null if no text is available */ @Override public String getText() { return null; } /** * Returns a descriptive string about this object * * @return the descriptive string */ public String toString() { return toLocation() + "(" + idToString() + ")"; } /** * Returns a location description about this instance * * @return the location description */ @Override public String toLocation() { String tResult = getClass().getSimpleName() + (getGUIClusterID() != -1 ? Long.toString(getGUIClusterID()) : "??") + "@" + mHRMController.getNodeGUIName() + "@" + getHierarchyLevel().getValue(); return tResult; } /** * Returns a string including the ClusterID, the coordinator ID, and the node priority * * @return the complex string */ private String idToString() { if ((getHRMID() == null) || (getHRMID().isRelativeAddress())){ return "Coordinator" + getGUICoordinatorID(); }else{ return "Coordinator" + getGUICoordinatorID() + ", HRMID=" + getHRMID().toString(); } } }
true
true
public synchronized void updateClusterMembers() { boolean DEBUG = HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS; boolean tChanges = false; mCountDistributeMembershipRequests ++; /************************************* * Update local coordinators ************************************/ if(DEBUG){ Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR LOCAL COORDINATORS STARTED (call nr: " + mCountDistributeMembershipRequests + ")"); } if(isThisEntityValid()){ LinkedList<Coordinator> tCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.log(this, " ..inferior local coordinators: " + tCoordinators.size()); } /** * Copy list of inferior local coordinators */ LinkedList<Coordinator> tOldInferiorLocalCoordinators = null; synchronized (mInferiorLocalCoordinators) { tOldInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone(); } /** * Iterate over all found inferior local coordinators */ synchronized (tOldInferiorLocalCoordinators) { if(mCountDistributeMembershipRequests > 1){ if(DEBUG){ Logging.log(this, " ..having connections to these inferior local coordinators: " + tOldInferiorLocalCoordinators.toString()); } } for (Coordinator tCoordinator : tCoordinators){ if (!tOldInferiorLocalCoordinators.contains(tCoordinator)){ if(DEBUG){ Logging.log(this, " ..found inferior local coordinator [NEW]: " + tCoordinator); } // add this local coordinator to the list of connected coordinators synchronized (mInferiorLocalCoordinators) { if(!mInferiorLocalCoordinators.contains(tCoordinator)){ mInferiorLocalCoordinators.add(tCoordinator); }else{ Logging.err(this, "Cannot add a duplicate of the local inferior coordinator: " + tCoordinator); } } if(DEBUG){ Logging.log(this, " ..get/create communication session"); } ComSession tComSession = mHRMController.getCreateComSession(mHRMController.getNodeL2Address(), this + "::updateClusterMembers()_1"); if (tComSession != null){ /** * Create coordinator name for this coordinator */ ClusterName tRemoteEndPointName = tCoordinator.createCoordinatorName(); ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID()); /** * Establish the comm. channel */ establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinator); tChanges = true; }else{ Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator); } }else{ if(DEBUG){ Logging.log(this, " ..found inferior local coordinator [already connected]: " + tCoordinator); } } } if(DEBUG){ Logging.log(this, " ..finished clustering of local inferior coordinators"); } /************************************ * Update remote coordinators ************************************/ if(mInferiorLocalCoordinators.size() > 0){ if(DEBUG){ Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR REMOTE COORDINATORS STARTED"); } LinkedList<CoordinatorProxy> tCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.log(this, " ..inferior remote coordinators: " + tCoordinatorProxies.size()); } /** * Copy list of known inferior remote coordinators */ LinkedList<CoordinatorProxy> tOldInferiorRemoteCoordinators = null; synchronized (mInferiorRemoteCoordinators) { tOldInferiorRemoteCoordinators = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } /************************************ * Drop old (invalid) remote coordinators ************************************/ synchronized (tOldInferiorRemoteCoordinators) { for(CoordinatorProxy tCoordintorProxy : tOldInferiorRemoteCoordinators){ if(DEBUG){ Logging.log(this, "Found inferior remote coordinator behind proxy: " + tCoordintorProxy); } if(!tCoordintorProxy.isThisEntityValid()){ if(DEBUG){ Logging.log(this, "Found already invalidated coordinator proxy: " + tCoordintorProxy); } ComChannel tComChannelToRemoteCoordinator = getComChannelToMember(tCoordintorProxy); if(tComChannelToRemoteCoordinator != null){ if(DEBUG){ Logging.log(this, " ..comm. channel is: " + tComChannelToRemoteCoordinator); Logging.log(this, " ..deactivating membership of: " + tCoordintorProxy); } //TODO: alternative is: tComChannelToRemoteCoordinator.setTimeout(this + "::updateClusterMembers()"); eventClusterMemberLost(tComChannelToRemoteCoordinator, this + "::updateClusterMembers() detected invalid remote coordinator behind: " + tCoordintorProxy); tChanges = true; } } } } /************************************ * Drop deprecated entry in list of connected remote coordinators ************************************/ synchronized (mInferiorRemoteCoordinators) { LinkedList<CoordinatorProxy> tAllCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().dec().getValue()); for(CoordinatorProxy tCoordintorProxy : tAllCoordinatorProxies){ if(mInferiorRemoteCoordinators.contains(tCoordintorProxy)){ if(tCoordintorProxy.isThisEntityValid()){ ComChannel tComChannelToRemoteCoordinator = getComChannelToMember(tCoordintorProxy); if(tComChannelToRemoteCoordinator == null){ if(DEBUG){ Logging.warn(this, "Found temporary invalided and returned coordinator proxy: " + tCoordintorProxy); } mInferiorRemoteCoordinators.remove(tCoordintorProxy); tOldInferiorRemoteCoordinators = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } } } } } /************************************* * Detect new remote coordinators ************************************/ if(tCoordinatorProxies.size() > 0){ synchronized (tOldInferiorRemoteCoordinators) { if(mCountDistributeMembershipRequests > 1){ if(DEBUG){ Logging.log(this, " ..having connections to these inferior remote coordinators: "); for(CoordinatorProxy tProxy : tOldInferiorRemoteCoordinators){ Logging.log(this, " ..: " + tProxy); } } } for (CoordinatorProxy tCoordinatorProxy : tCoordinatorProxies){ if (!tOldInferiorRemoteCoordinators.contains(tCoordinatorProxy)){ if(DEBUG){ Logging.log(this, " ..found remote inferior coordinator[NEW]: " + tCoordinatorProxy); } // add this remote coordinator to the list of connected coordinators synchronized (mInferiorRemoteCoordinators) { if(!mInferiorRemoteCoordinators.contains(tCoordinatorProxy)){ if(DEBUG){ Logging.log(this, " ..adding to connected remote inferior coordinators: " + tCoordinatorProxy); } mInferiorRemoteCoordinators.add(tCoordinatorProxy); }else{ Logging.err(this, "Cannot add a duplicate of the remote inferior coordinator: " + tCoordinatorProxy); } } ComSession tComSession = mHRMController.getCreateComSession(tCoordinatorProxy.getCoordinatorNodeL2Address(), this + "::updateClusterMembers()_2"); if (tComSession != null){ /** * Create coordinator name for this coordinator proxy */ ClusterName tRemoteEndPointName = tCoordinatorProxy.createCoordinatorName(); ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID()); /** * Establish the comm. channel */ establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinatorProxy); tChanges = true; }else{ Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + tCoordinatorProxy.getCoordinatorNodeL2Address() + " for remote coordinator: " + tCoordinatorProxy); } }else{ if(DEBUG){ Logging.log(this, " ..found inferior remote coordinator [already connected]: " + tCoordinatorProxy); } } } } }else{ /** * Trigger: detected local isolation */ eventDetectedIsolation(); } }else{ if(DEBUG){ Logging.log(this, " ..no local inferior coordinators existing"); } } } }else{ Logging.warn(this, "updateClusterMembers() skipped because cluster role is already invalidated"); } // finally, check the necessity of this cluster again if(!isClusterNeeded()){ tChanges = false; } /** * trigger election update if changes happened */ if(tChanges){ Logging.log(this, "updateClusterMembers[" + mCountDistributeMembershipRequests + "] triggers a re-election due to topology changes"); mElector.startElection(this + "::updateClusterMembers()[" + mCountDistributeMembershipRequests + "]"); }else{ Logging.log(this, "updateClusterMembers[" + mCountDistributeMembershipRequests + "] detected no topology changes"); } }
public synchronized void updateClusterMembers() { boolean DEBUG = HRMConfig.DebugOutput.SHOW_CLUSTERING_STEPS; boolean tChanges = false; mCountDistributeMembershipRequests ++; /************************************* * Update local coordinators ************************************/ if(DEBUG){ Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR LOCAL COORDINATORS STARTED (call nr: " + mCountDistributeMembershipRequests + ")"); } if(isThisEntityValid()){ LinkedList<Coordinator> tCoordinators = mHRMController.getAllCoordinators(getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.log(this, " ..inferior local coordinators: " + tCoordinators.size()); } /** * Copy list of inferior local coordinators */ LinkedList<Coordinator> tOldInferiorLocalCoordinators = null; synchronized (mInferiorLocalCoordinators) { tOldInferiorLocalCoordinators = (LinkedList<Coordinator>) mInferiorLocalCoordinators.clone(); } /** * Iterate over all found inferior local coordinators */ synchronized (tOldInferiorLocalCoordinators) { if(mCountDistributeMembershipRequests > 1){ if(DEBUG){ Logging.log(this, " ..having connections to these inferior local coordinators: " + tOldInferiorLocalCoordinators.toString()); } } for (Coordinator tCoordinator : tCoordinators){ if (!tOldInferiorLocalCoordinators.contains(tCoordinator)){ if(DEBUG){ Logging.log(this, " ..found inferior local coordinator [NEW]: " + tCoordinator); } // add this local coordinator to the list of connected coordinators synchronized (mInferiorLocalCoordinators) { if(!mInferiorLocalCoordinators.contains(tCoordinator)){ mInferiorLocalCoordinators.add(tCoordinator); }else{ Logging.err(this, "Cannot add a duplicate of the local inferior coordinator: " + tCoordinator); } } if(DEBUG){ Logging.log(this, " ..get/create communication session"); } ComSession tComSession = mHRMController.getCreateComSession(mHRMController.getNodeL2Address(), this + "::updateClusterMembers()_1"); if (tComSession != null){ /** * Create coordinator name for this coordinator */ ClusterName tRemoteEndPointName = tCoordinator.createCoordinatorName(); ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID()); /** * Establish the comm. channel */ establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinator); tChanges = true; }else{ Logging.warn(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + mHRMController.getNodeName() + " for local coordinator: " + tCoordinator); } }else{ if(DEBUG){ Logging.log(this, " ..found inferior local coordinator [already connected]: " + tCoordinator); } } } if(DEBUG){ Logging.log(this, " ..finished clustering of local inferior coordinators"); } /************************************ * Update remote coordinators ************************************/ if(mInferiorLocalCoordinators.size() > 0){ if(DEBUG){ Logging.log(this, "\n\n\n################ REQUESTING MEMBERSHIP FOR REMOTE COORDINATORS STARTED"); } LinkedList<CoordinatorProxy> tCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().getValue() - 1); if(DEBUG){ Logging.log(this, " ..inferior remote coordinators: " + tCoordinatorProxies.size()); } /** * Copy list of known inferior remote coordinators */ LinkedList<CoordinatorProxy> tOldInferiorRemoteCoordinators = null; synchronized (mInferiorRemoteCoordinators) { tOldInferiorRemoteCoordinators = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } /************************************ * Drop old (invalid) remote coordinators ************************************/ synchronized (tOldInferiorRemoteCoordinators) { for(CoordinatorProxy tCoordintorProxy : tOldInferiorRemoteCoordinators){ if(DEBUG){ Logging.log(this, "Found inferior remote coordinator behind proxy: " + tCoordintorProxy); } if(!tCoordintorProxy.isThisEntityValid()){ if(DEBUG){ Logging.log(this, "Found already invalidated coordinator proxy: " + tCoordintorProxy); } ComChannel tComChannelToRemoteCoordinator = getComChannelToMember(tCoordintorProxy); if(tComChannelToRemoteCoordinator != null){ if(DEBUG){ Logging.log(this, " ..comm. channel is: " + tComChannelToRemoteCoordinator); Logging.log(this, " ..deactivating membership of: " + tCoordintorProxy); } //TODO: alternative is: tComChannelToRemoteCoordinator.setTimeout(this + "::updateClusterMembers()"); eventClusterMemberLost(tComChannelToRemoteCoordinator, this + "::updateClusterMembers() detected invalid remote coordinator behind: " + tCoordintorProxy); tChanges = true; } } } } /************************************ * Drop deprecated entry in list of connected remote coordinators ************************************/ synchronized (mInferiorRemoteCoordinators) { LinkedList<CoordinatorProxy> tAllCoordinatorProxies = mHRMController.getAllCoordinatorProxies(getHierarchyLevel().dec().getValue()); for(CoordinatorProxy tCoordintorProxy : tAllCoordinatorProxies){ if(mInferiorRemoteCoordinators.contains(tCoordintorProxy)){ if(tCoordintorProxy.isThisEntityValid()){ ComChannel tComChannelToRemoteCoordinator = getComChannelToMember(tCoordintorProxy); if(tComChannelToRemoteCoordinator == null){ if(DEBUG){ Logging.warn(this, "Found temporary invalided and returned coordinator proxy: " + tCoordintorProxy); } mInferiorRemoteCoordinators.remove(tCoordintorProxy); tOldInferiorRemoteCoordinators = (LinkedList<CoordinatorProxy>) mInferiorRemoteCoordinators.clone(); } } } } } /************************************* * Detect new remote coordinators ************************************/ if(tCoordinatorProxies.size() > 0){ synchronized (tOldInferiorRemoteCoordinators) { if(mCountDistributeMembershipRequests > 1){ if(DEBUG){ Logging.log(this, " ..having connections to these inferior remote coordinators: "); for(CoordinatorProxy tProxy : tOldInferiorRemoteCoordinators){ Logging.log(this, " ..: " + tProxy); } } } for (CoordinatorProxy tCoordinatorProxy : tCoordinatorProxies){ if (!tOldInferiorRemoteCoordinators.contains(tCoordinatorProxy)){ if(DEBUG){ Logging.log(this, " ..found remote inferior coordinator[NEW]: " + tCoordinatorProxy); } // add this remote coordinator to the list of connected coordinators synchronized (mInferiorRemoteCoordinators) { if(!mInferiorRemoteCoordinators.contains(tCoordinatorProxy)){ if(DEBUG){ Logging.log(this, " ..adding to connected remote inferior coordinators: " + tCoordinatorProxy); } mInferiorRemoteCoordinators.add(tCoordinatorProxy); }else{ Logging.err(this, "Cannot add a duplicate of the remote inferior coordinator: " + tCoordinatorProxy); } } ComSession tComSession = mHRMController.getCreateComSession(tCoordinatorProxy.getCoordinatorNodeL2Address(), this + "::updateClusterMembers()_2"); if (tComSession != null){ /** * Create coordinator name for this coordinator proxy */ ClusterName tRemoteEndPointName = tCoordinatorProxy.createCoordinatorName(); ClusterName tLocalEndPointName = new ClusterName(mHRMController, tRemoteEndPointName.getHierarchyLevel().inc() /* at the remote side, a CoordinatorAsClusterMember is always located at one hierarchy level above the original coordinator object */, tRemoteEndPointName.getClusterID(), tRemoteEndPointName.getCoordinatorID()); /** * Establish the comm. channel */ establishComChannel(tComSession, tRemoteEndPointName, tLocalEndPointName, tCoordinatorProxy); tChanges = true; }else{ Logging.err(this, "distributeMembershipRequests() couldn't determine the comm. session to: " + tCoordinatorProxy.getCoordinatorNodeL2Address() + " for remote coordinator: " + tCoordinatorProxy); } }else{ if(DEBUG){ Logging.log(this, " ..found inferior remote coordinator [already connected]: " + tCoordinatorProxy); } } } } }else{ /** * Trigger: detected local isolation */ eventDetectedIsolation(); } }else{ if(DEBUG){ Logging.log(this, " ..no local inferior coordinators existing"); } } } }else{ Logging.warn(this, "updateClusterMembers() skipped because cluster role is already invalidated"); } // finally, check the necessity of this cluster again if(!isClusterNeeded()){ tChanges = false; } /** * trigger election update if changes happened */ if(tChanges){ Logging.log(this, "updateClusterMembers[" + mCountDistributeMembershipRequests + "] triggers a re-election due to topology changes"); mElector.startElection(this + "::updateClusterMembers()[" + mCountDistributeMembershipRequests + "]"); }else{ Logging.log(this, "updateClusterMembers[" + mCountDistributeMembershipRequests + "] detected no topology changes"); } }
diff --git a/src/main/java/com/alexrnl/subtitlecorrector/common/Subtitle.java b/src/main/java/com/alexrnl/subtitlecorrector/common/Subtitle.java index 75c433f..22f1111 100644 --- a/src/main/java/com/alexrnl/subtitlecorrector/common/Subtitle.java +++ b/src/main/java/com/alexrnl/subtitlecorrector/common/Subtitle.java @@ -1,165 +1,173 @@ package com.alexrnl.subtitlecorrector.common; import com.alexrnl.commons.utils.object.AutoCompare; import com.alexrnl.commons.utils.object.AutoHashCode; import com.alexrnl.commons.utils.object.Field; /** * Class describing a simple subtitle. * @author Alex */ public class Subtitle implements Comparable<Subtitle>, Cloneable { /** Timestamp (in milliseconds) for beginning of subtitle display */ private long begin; /** Timestamp (in milliseconds) for end of subtitle display */ private long end; /** The content of the subtitle */ private String content; /** * Constructor #1.<br /> * Default constructor. */ public Subtitle () { this(0, 0, null); } /** * Constructor #2.<br /> * @param begin * the beginning of the subtitle display (in milliseconds). * @param end * the end of the subtitle display (in milliseconds). * @param content * the content of the subtitle. */ public Subtitle (final long begin, final long end, final String content) { super(); this.begin = begin; this.end = end; this.content = content; } /** * Return the attribute begin. * @return the attribute begin. */ @Field public long getBegin () { return begin; } /** * Set the attribute begin. * @param begin * the attribute begin. */ public void setBegin (final long begin) { this.begin = begin; } /** * Return the attribute end. * @return the attribute end. */ @Field public long getEnd () { return end; } /** * Set the attribute end. * @param end * the attribute end. */ public void setEnd (final long end) { this.end = end; } /** * Return the attribute content. * @return the attribute content. */ @Field public String getContent () { return content; } /** * Set the attribute content. * @param content * the attribute content. */ public void setContent (final String content) { this.content = content; } /** * Computes the display duration of the subtitle. * @return the duration. */ public long getDuration () { return end - begin; } /** * Check the validity of the subtitle.<br /> * A subtitle is valid if the end time is greater (or equal) to the begin time. * @return <true>true</true> if the subtitle is valid. */ public boolean isValid () { return begin < end; } @Override public int hashCode () { return AutoHashCode.getInstance().hashCode(this); } @Override public boolean equals (final Object obj) { if (!(obj instanceof Subtitle)) { return false; } return AutoCompare.getInstance().compare(this, (Subtitle) obj); } /** * Return the text representation of the subtitle as follow: * * <pre> * [begin, end] content * </pre> */ @Override public String toString () { return "[" + begin + ", " + end + "] " + content; } /** * Compare the subtitles based on their begin times, then end times, and finally their content. */ @Override public int compareTo (final Subtitle sub) { final int beginCmp = Long.valueOf(begin).compareTo(sub.getBegin()); if (beginCmp != 0) { return beginCmp; } final int endCmp = Long.valueOf(end).compareTo(sub.getEnd()); if (endCmp != 0) { return endCmp; } + // Finally, compare subtitle content + if (content == null && sub.getContent() == null) { + return 0; + } else if (content == null) { + return 1; + } else if (sub.getContent() == null) { + return -1; + } return content.compareTo(sub.getContent()); } @Override public Subtitle clone () throws CloneNotSupportedException { final Subtitle clone = (Subtitle) super.clone(); clone.setBegin(begin); clone.setEnd(end); clone.setContent(content); return clone; } }
true
true
public int compareTo (final Subtitle sub) { final int beginCmp = Long.valueOf(begin).compareTo(sub.getBegin()); if (beginCmp != 0) { return beginCmp; } final int endCmp = Long.valueOf(end).compareTo(sub.getEnd()); if (endCmp != 0) { return endCmp; } return content.compareTo(sub.getContent()); }
public int compareTo (final Subtitle sub) { final int beginCmp = Long.valueOf(begin).compareTo(sub.getBegin()); if (beginCmp != 0) { return beginCmp; } final int endCmp = Long.valueOf(end).compareTo(sub.getEnd()); if (endCmp != 0) { return endCmp; } // Finally, compare subtitle content if (content == null && sub.getContent() == null) { return 0; } else if (content == null) { return 1; } else if (sub.getContent() == null) { return -1; } return content.compareTo(sub.getContent()); }
diff --git a/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java b/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java index d3cdab9..5df5b39 100644 --- a/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java +++ b/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java @@ -1,889 +1,891 @@ /** * 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.spreadsheetimport; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.api.context.Context; import org.openmrs.module.spreadsheetimport.objects.NameValue; /** * */ public class DatabaseBackend { /** Logger for this class and subclasses */ protected static final Log log = LogFactory.getLog(SpreadsheetImportUtil.class); /** * Make name pretty */ public static String makePrettyName(String name) { String result = ""; boolean capitalizeNext = true; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (c == '_') { result += " "; capitalizeNext = true; } else if (capitalizeNext) { result += Character.toUpperCase(c); capitalizeNext = false; } else { result += c; } } return result; } /** * Convert table_name.column_name to Table Name: Column Name */ public static String makePrettyTableDotColumn(String tableDotColumn) { int index = tableDotColumn.indexOf("."); String table = tableDotColumn.substring(0, index); String column = tableDotColumn.substring(index + 1); return makePrettyName(table) + ": " + makePrettyName(column); } /** * Map: key = tableName.column, value = Table: Column */ private static Map<String, String> tableColumnMap = null; private static Map<String, List<String>> tableColumnListMap = null; public static Map<String, List<String>> getTableColumnListMap() throws Exception { if (tableColumnListMap == null) reverseEngineerDatabaseTable(); return tableColumnListMap; } public static Map<String, String> getTableColumnMap() throws Exception { if (tableColumnMap == null) reverseEngineerDatabaseTable(); return tableColumnMap; } private static void reverseEngineerDatabaseTable() throws Exception { tableColumnMap = new TreeMap<String, String>(); tableColumnListMap = new TreeMap<String, List<String>>(); Connection conn = null; Exception exception = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); // All tables DatabaseMetaData dmd = conn.getMetaData(); ResultSet rs = dmd.getTables(null, null, "", null); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); // All columns List<String> columnNames = new ArrayList<String>(); ResultSet rsColumns = dmd.getColumns(null, null, tableName, ""); while (rsColumns.next()) { columnNames.add(rsColumns.getString("COLUMN_NAME")); } rsColumns.close(); // // Remove imported keys ResultSet rsImportedKeys = dmd.getImportedKeys(null, null, tableName); while (rsImportedKeys.next()) { String columnName = rsImportedKeys.getString("FKCOLUMN_NAME"); if (columnNames.contains(columnName) && "obs".equalsIgnoreCase(tableName) && !"value_coded".equalsIgnoreCase(columnName)) { // hack: only allow obs.value_coded to go through columnNames.remove(columnName); } } rsImportedKeys.close(); List<String> clonedColumns = new ArrayList<String>(); clonedColumns.addAll(columnNames); // Add to map for (String columnName : clonedColumns) { String tableDotColumn = tableName + "." + columnName; tableColumnMap.put(tableDotColumn, makePrettyTableDotColumn(tableDotColumn)); } // Remove primary key ResultSet rsPrimaryKeys = dmd.getPrimaryKeys(null, null, tableName); while (rsPrimaryKeys.next()) { String columnName = rsPrimaryKeys.getString("COLUMN_NAME"); if (columnNames.contains(columnName)) { columnNames.remove(columnName); } } rsPrimaryKeys.close(); tableColumnListMap.put(tableName, columnNames); } } catch (Exception e) { log.debug(e.toString()); exception = e; } finally { if (conn != null) { try { conn.close(); } catch (Exception e) {} } } if (exception != null) { throw exception; } } public static List<NameValue> getMapNameToAllowedValue(String tableName) throws Exception { List<NameValue> retVal = new ArrayList<NameValue>(); // Map<String, String> result = new LinkedHashMap<String, String>(); Connection conn = null; Statement s = null; Exception exception = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); s = conn.createStatement(); // Primary key String primaryKey = tableName + "_id"; // Guess DatabaseMetaData dmd = conn.getMetaData(); ResultSet rsPrimaryKeys = dmd.getPrimaryKeys(null, null, tableName); if (rsPrimaryKeys.next()) { primaryKey = rsPrimaryKeys.getString("COLUMN_NAME"); } rsPrimaryKeys.close(); ResultSet rs = null; // Try 0: if table is person, then look for person_name if ("person".equals(tableName)) { try { rs = s.executeQuery("SELECT CONCAT(given_name, ' ', family_name) name, `person_name`.`person_id` primary_key FROM `users` INNER JOIN `person_name` on `users`.`person_id` = `person_name`.`person_id` INNER JOIN `user_role` on `users`.`user_id` = `user_role`.`user_id` WHERE `user_role`.`role` = 'Provider'"); } catch (Exception e) { log.debug(e.toString()); } } // Try 1: name field in tableName if (rs == null) { try { rs = s.executeQuery("select name, " + primaryKey + " from " + tableName + " order by name"); } catch (Exception e) { log.debug(e.toString()); } } // Try 2: name field in table_name if (rs == null) { try { rs = s.executeQuery("select name, " + primaryKey + " from " + tableName + "_name order by name"); } catch (Exception e) { log.debug(e.toString()); } } // Try 3: just use table_id as both key and value if (rs == null) { rs = s.executeQuery("select " + primaryKey + ", " + primaryKey + " from " + tableName); } while (rs.next()) { NameValue nameValue = new NameValue(); nameValue.setName(rs.getString(1)); nameValue.setValue(rs.getString(2)); retVal.add(nameValue); } rs.close(); } catch (Exception e) { log.debug(e.toString()); exception = e; } finally { if (s != null) { try { s.close(); } catch (Exception e) {} } if (conn != null) { try { conn.close(); } catch (Exception e) {} } } if (exception != null) { throw exception; } else { return retVal; } } public static Map<String, String> getMapOfImportedKeyTableNameToColumnNamesForTable(String tableName) throws Exception { Map<String, String> result = new HashMap<String, String>(); Connection conn = null; Exception exception = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); // Not NULLable columns DatabaseMetaData dmd = conn.getMetaData(); List<String> columnNames = new ArrayList<String>(); ResultSet rsColumns = dmd.getColumns(null, null, tableName, ""); while (rsColumns.next()) { if (!rsColumns.getString("IS_NULLABLE").equals("YES")) { columnNames.add(rsColumns.getString("COLUMN_NAME")); } } rsColumns.close(); // Imported keys ResultSet rsImportedKeys = dmd.getImportedKeys(null, null, tableName); while (rsImportedKeys.next()) { String columnName = rsImportedKeys.getString("FKCOLUMN_NAME"); if (columnNames.contains(columnName)) { result.put(rsImportedKeys.getString("PKTABLE_NAME"), columnName); } } rsImportedKeys.close(); } catch (Exception e) { log.debug(e.toString()); exception = e; } finally { if (conn != null) { try { conn.close(); } catch (Exception e) {} } } if (exception != null) { throw exception; } else { return result; } } public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData, boolean rollbackTransaction) throws Exception { Connection conn = null; Statement s = null; Exception exception = null; String sql = null; String encounterId = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); conn.setAutoCommit(false); s = conn.createStatement(); List<String> importedTables = new ArrayList<String>(); // Import for (UniqueImport uniqueImport : rowData.keySet()) { String tableName = uniqueImport.getTableName(); boolean isEncounter = "encounter".equals(tableName); boolean isPerson = "person".equals(tableName); boolean isPatientIdentifier = "patient_identifier".equals(tableName); boolean isObservation = "obs".equals(tableName); boolean skip = false; // SPECIAL TREATMENT // for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter // otherwise, we need to create a new encounter if (isEncounter) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { Object columnValue = column.getValue(); if (!columnValue.equals("")) { column.setGeneratedKey(columnValue.toString()); skip = true; importedTables.add("encounter"); // fake as just imported encounter break; } } if (skip) continue; } if (isPerson) { boolean isIdentifierExist = false; // SPECIAL TREATMENT 1 // if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead // note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436) UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null); if (rowData.containsKey(patientIdentifier)) { Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData.get(patientIdentifier); for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) { String columnName = patientIdentifierColumn.getColumnName(); if ("identifier".equals(columnName)) { isIdentifierExist = true; sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue(); ResultSet rs = s.executeQuery(sql); if (rs.next()) { String patientId = rs.getString(1); // no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(patientId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("patient_identifier"); // fake as just imported patient_identifier importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } rs.close(); break; } } } if (skip) continue; // now, if we proceed to this point, it means patient identifier, if exists, does not match, and in that case, no point to match with person name // SPECIAL TREATMENT 2 // if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead UniqueImport personName = new UniqueImport("person_name", null); if (rowData.containsKey(personName) && !isIdentifierExist) { Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName); // getting gender, birthdate from person Object gender = null; Object birthdate = null; for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) { String columnName = personColumn.getColumnName(); if ("birth_date".equals(columnName)) birthdate = personColumn.getValue(); if ("gender".equals(columnName)) gender = personColumn.getValue(); } // getting first name, last name, middle name from person Object givenName = null; Object familyName = null; Object middleName = null; for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) { String columnName = personNameColumn.getColumnName(); if ("given_name".equals(columnName)) givenName = personNameColumn.getValue(); if ("family_name".equals(columnName)) familyName = personNameColumn.getValue(); if ("middle_name".equals(columnName)) middleName = personNameColumn.getValue(); } // find matching person name sql = "select person.person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName); ResultSet rs = s.executeQuery(sql); String personId = null; if (rs.next()) { // matched => no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(personId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } } if (skip) continue; } if (isPatientIdentifier && importedTables.contains("patient_identifier")) continue; // Data from columns Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); String columnNames = ""; String columnValues = ""; Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null; Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null; boolean isFirst = true; for (SpreadsheetImportTemplateColumn column : columnSet) { // special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id if (isEncounter) { columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); // inject date_created columnNames += "date_created"; columnValues += "now()"; // find encounter_datetime based on observation date time java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis()); Set<UniqueImport> uniqueImports = rowData.keySet(); for (UniqueImport u : uniqueImports) { if ("obs".equals(u.getTableName())) { Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u); for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) { if ("obs_datetime".equals(obsColumn.getColumnName())) { String obsColumnValue = obsColumn.getValue().toString(); obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length()-1); Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue); if (obsColumnValueDate.before(encounterDatetime)) encounterDatetime = obsColumnValueDate; } } } } columnNames += ", encounter_datetime"; columnValues += ",'" + encounterDatetime.toString() + "'"; isFirst = false; break; } // Check for duplicates if (column.getDisallowDuplicateValue()) { sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue(); if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } ResultSet rs = s.executeQuery(sql); boolean foundDuplicate = rs.next(); rs.close(); if (foundDuplicate) { throw new SpreadsheetImportDuplicateValueException(column); } } if (isFirst) { // Should be same for all columns in unique import columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); isFirst = false; } else { columnNames += ","; columnValues += ","; } columnNames += column.getColumnName(); columnValues += column.getValue().toString(); } // Data from pre-specified values for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnPrespecifiedValue.getColumnName(); columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue(); } // Data from columns import before if (!columnColumnsImportBefore.isEmpty()) { // Set up Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>(); for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) { String primaryKeyColumnName = columnColumn.getColumnName(); String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey(); if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) { String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey.get(primaryKeyColumnName); if (!mapGeneratedKey.equals(columnGeneratedKey)) { throw new SpreadsheetImportUnhandledCaseException(); } } else { mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey); } // TODO: I believe patient and person are only tables with this relationship, if not, then this // needs to be generalized if (primaryKeyColumnName.equals("patient_id") && importedTables.contains("person") && !importedTables.contains("patient")) { sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")"; if (log.isDebugEnabled()) { log.debug(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); // ResultSet rs = s.getGeneratedKeys(); // rs.next(); // if (!columnGeneratedKey.equals(rs.getString(1))) { // throw new SpreadsheetImportUnhandledCaseException(); // } importedTables.add("patient"); } } // Add columns for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnName; columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName); } } // SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time if (isObservation) { boolean hasDatetime = false; for (SpreadsheetImportTemplateColumn column : columnSet) { if ("obs_datetime".equals(column.getColumnName())) { hasDatetime = true; break; } } if (!hasDatetime) { columnNames += ",obs_datetime"; columnValues += ",now()"; - } + } + columnNames += ", date_created"; + columnValues += ",now()"; } // SPECIAL TREATMENT: if this is patient identifier, then set location_id to NULL, to avoid CONSTRAINT `patient_identifier_ibfk_2` FOREIGN KEY (`location_id`) REFERENCES `location` (`location_id`)) if (isPatientIdentifier) { columnNames += ", location_id"; columnValues += ", NULL"; } // creator columnNames += ",creator"; columnValues += "," + Context.getAuthenticatedUser().getId(); // uuid DatabaseMetaData dmd = conn.getMetaData(); ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid"); if (rsColumns.next()) { columnNames += ",uuid"; columnValues += ",uuid()"; } rsColumns.close(); // Insert tableName sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values (" + columnValues + ")"; if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = s.getGeneratedKeys(); rs.next(); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(rs.getString(1)); } // SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller if (isEncounter) encounterId = rs.getString(1); rs.close(); importedTables.add(uniqueImport.getTableName()); } } catch (SQLSyntaxErrorException e) { throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); } catch (Exception e) { log.debug(e.toString()); exception = e; throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); // TODO: for web debug purpose only, should comment out later } finally { if (s != null) { try { s.close(); } catch (Exception e) {} } if (conn != null) { if (rollbackTransaction) { conn.rollback(); } else { conn.commit(); } try { conn.close(); } catch (Exception e) {} } } if (exception != null) { throw exception; } return encounterId; } public static void validateData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData) throws SQLException, SpreadsheetImportTemplateValidationException { Connection conn = null; Statement s = null; String sql = null; SQLException exception = null; ResultSet rs = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); s = conn.createStatement(); for (UniqueImport uniqueImport : rowData.keySet()) { if ("obs".equals(uniqueImport.getTableName())) { Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) { String columnName = obsColumn.getColumnName(); String conceptId = getPrespecifiedConceptIdFromObsColumn(obsColumn); if (conceptId == null) throw new SpreadsheetImportTemplateValidationException("no prespecified concept ID"); if ("value_coded".equals(columnName)) { // verify the answers are the concepts which are possible answers //sql = "select answer_concept from concept_answer join concept_name on concept_answer.answer_concept = concept_name.concept_id where concept_name.name = '" + obsColumn.getValue() + "' and concept_answer.concept_id = '" + conceptId + "'"; sql = "select answer_concept from concept_answer where answer_concept = '" + obsColumn.getValue() + "' and concept_id = '" + conceptId + "'"; rs = s.executeQuery(sql); if (!rs.next()) throw new SpreadsheetImportTemplateValidationException("invalid concept answer for the prespecified concept ID " + conceptId); } else if ("value_text".equals(columnName)) { // verify the number of characters is less than the allowed length } else if ("value_numeric".equals(columnName)) { // verify it's within the range specified in the concept definition sql = "select hi_absolute, low_absolute from concept_numeric where concept_id = '" + conceptId + "'"; rs = s.executeQuery(sql); if (!rs.next()) throw new SpreadsheetImportTemplateValidationException("prespecified concept ID " + conceptId + " is not a numeric concept"); double hiAbsolute = rs.getDouble(1); double lowAbsolute = rs.getDouble(2); double value = 0.0; try { value = Double.parseDouble(obsColumn.getValue().toString()); } catch (NumberFormatException nfe) { throw new SpreadsheetImportTemplateValidationException("concept value is not a number"); } if (hiAbsolute < value || lowAbsolute > value) throw new SpreadsheetImportTemplateValidationException("concept value " + value + " of column " + columnName + " is out of range " + lowAbsolute + " - " + hiAbsolute); } else if ("value_datetime".equals(columnName) || "obs_datetime".equals(columnName)) { // verify datetime is defined and it can not be in the future String value = obsColumn.getValue().toString(); String date = value.substring(1, value.length()-1); if (Date.valueOf(date).after(new Date(System.currentTimeMillis()))) throw new SpreadsheetImportTemplateValidationException("date is in the future"); } } } else if ("patient_identifier".equals(uniqueImport.getTableName())) { Set<SpreadsheetImportTemplateColumn> piColumns = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn piColumn : piColumns) { String columnName = piColumn.getColumnName(); if (!"identifier".equals(columnName)) continue; String pitId = getPrespecifiedPatientIdentifierTypeIdFromPatientIdentifierColumn(piColumn); if (pitId == null) throw new SpreadsheetImportTemplateValidationException("no prespecified patient identifier type ID"); sql = "select format from patient_identifier_type where patient_identifier_type_id = " + pitId; rs = s.executeQuery(sql); if (!rs.next()) throw new SpreadsheetImportTemplateValidationException("invalid prespcified patient identifier type ID"); String format = rs.getString(1); if (format != null && format.trim().length() != 0) { String value = piColumn.getValue().toString(); value = value.substring(1, value.length()-1); Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(value); if (!matcher.matches()) throw new SpreadsheetImportTemplateValidationException("Patient ID is not conforming to patient identifier type"); } } } } } catch (SQLException e) { log.debug(e.toString()); exception = e; } catch (IllegalAccessException e) { log.debug(e.toString()); } catch (InstantiationException e) { log.debug(e.toString()); } catch (ClassNotFoundException e) { log.debug(e.toString()); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) {} if (s != null) { try { s.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } if (exception != null) { throw exception; } } public static Locale getCurrentUserLocale() { Connection conn = null; Statement s = null; String language = "en_GB"; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); Integer userId = Context.getAuthenticatedUser().getId(); s = conn.createStatement(); ResultSet rs = s.executeQuery("select property_value from user_property where user_id=" + userId.toString()); if (rs.next()) language = rs.getString(1); } catch (Exception e) { log.debug(e.toString()); } Locale locale = new Locale(language); return locale; } private static String getPrespecifiedConceptIdFromObsColumn(SpreadsheetImportTemplateColumn obsColumn) { Set<SpreadsheetImportTemplateColumnPrespecifiedValue> prespecifiedColumns = obsColumn.getColumnPrespecifiedValues(); for (SpreadsheetImportTemplateColumnPrespecifiedValue prespecifiedColumn : prespecifiedColumns) { String prespecifiedColumnName = prespecifiedColumn.getColumnName(); if ("concept_id".equals(prespecifiedColumnName)) return prespecifiedColumn.getPrespecifiedValue().getValue(); } return null; } private static String getPrespecifiedPatientIdentifierTypeIdFromPatientIdentifierColumn(SpreadsheetImportTemplateColumn piColumn) { Set<SpreadsheetImportTemplateColumnPrespecifiedValue> prespecifiedColumns = piColumn.getColumnPrespecifiedValues(); for (SpreadsheetImportTemplateColumnPrespecifiedValue prespecifiedColumn : prespecifiedColumns) { String prespecifiedColumnName = prespecifiedColumn.getColumnName(); if ("identifier_type".equals(prespecifiedColumnName)) return prespecifiedColumn.getPrespecifiedValue().getValue(); } return null; } }
true
true
public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData, boolean rollbackTransaction) throws Exception { Connection conn = null; Statement s = null; Exception exception = null; String sql = null; String encounterId = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); conn.setAutoCommit(false); s = conn.createStatement(); List<String> importedTables = new ArrayList<String>(); // Import for (UniqueImport uniqueImport : rowData.keySet()) { String tableName = uniqueImport.getTableName(); boolean isEncounter = "encounter".equals(tableName); boolean isPerson = "person".equals(tableName); boolean isPatientIdentifier = "patient_identifier".equals(tableName); boolean isObservation = "obs".equals(tableName); boolean skip = false; // SPECIAL TREATMENT // for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter // otherwise, we need to create a new encounter if (isEncounter) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { Object columnValue = column.getValue(); if (!columnValue.equals("")) { column.setGeneratedKey(columnValue.toString()); skip = true; importedTables.add("encounter"); // fake as just imported encounter break; } } if (skip) continue; } if (isPerson) { boolean isIdentifierExist = false; // SPECIAL TREATMENT 1 // if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead // note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436) UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null); if (rowData.containsKey(patientIdentifier)) { Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData.get(patientIdentifier); for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) { String columnName = patientIdentifierColumn.getColumnName(); if ("identifier".equals(columnName)) { isIdentifierExist = true; sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue(); ResultSet rs = s.executeQuery(sql); if (rs.next()) { String patientId = rs.getString(1); // no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(patientId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("patient_identifier"); // fake as just imported patient_identifier importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } rs.close(); break; } } } if (skip) continue; // now, if we proceed to this point, it means patient identifier, if exists, does not match, and in that case, no point to match with person name // SPECIAL TREATMENT 2 // if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead UniqueImport personName = new UniqueImport("person_name", null); if (rowData.containsKey(personName) && !isIdentifierExist) { Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName); // getting gender, birthdate from person Object gender = null; Object birthdate = null; for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) { String columnName = personColumn.getColumnName(); if ("birth_date".equals(columnName)) birthdate = personColumn.getValue(); if ("gender".equals(columnName)) gender = personColumn.getValue(); } // getting first name, last name, middle name from person Object givenName = null; Object familyName = null; Object middleName = null; for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) { String columnName = personNameColumn.getColumnName(); if ("given_name".equals(columnName)) givenName = personNameColumn.getValue(); if ("family_name".equals(columnName)) familyName = personNameColumn.getValue(); if ("middle_name".equals(columnName)) middleName = personNameColumn.getValue(); } // find matching person name sql = "select person.person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName); ResultSet rs = s.executeQuery(sql); String personId = null; if (rs.next()) { // matched => no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(personId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } } if (skip) continue; } if (isPatientIdentifier && importedTables.contains("patient_identifier")) continue; // Data from columns Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); String columnNames = ""; String columnValues = ""; Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null; Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null; boolean isFirst = true; for (SpreadsheetImportTemplateColumn column : columnSet) { // special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id if (isEncounter) { columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); // inject date_created columnNames += "date_created"; columnValues += "now()"; // find encounter_datetime based on observation date time java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis()); Set<UniqueImport> uniqueImports = rowData.keySet(); for (UniqueImport u : uniqueImports) { if ("obs".equals(u.getTableName())) { Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u); for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) { if ("obs_datetime".equals(obsColumn.getColumnName())) { String obsColumnValue = obsColumn.getValue().toString(); obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length()-1); Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue); if (obsColumnValueDate.before(encounterDatetime)) encounterDatetime = obsColumnValueDate; } } } } columnNames += ", encounter_datetime"; columnValues += ",'" + encounterDatetime.toString() + "'"; isFirst = false; break; } // Check for duplicates if (column.getDisallowDuplicateValue()) { sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue(); if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } ResultSet rs = s.executeQuery(sql); boolean foundDuplicate = rs.next(); rs.close(); if (foundDuplicate) { throw new SpreadsheetImportDuplicateValueException(column); } } if (isFirst) { // Should be same for all columns in unique import columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); isFirst = false; } else { columnNames += ","; columnValues += ","; } columnNames += column.getColumnName(); columnValues += column.getValue().toString(); } // Data from pre-specified values for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnPrespecifiedValue.getColumnName(); columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue(); } // Data from columns import before if (!columnColumnsImportBefore.isEmpty()) { // Set up Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>(); for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) { String primaryKeyColumnName = columnColumn.getColumnName(); String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey(); if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) { String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey.get(primaryKeyColumnName); if (!mapGeneratedKey.equals(columnGeneratedKey)) { throw new SpreadsheetImportUnhandledCaseException(); } } else { mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey); } // TODO: I believe patient and person are only tables with this relationship, if not, then this // needs to be generalized if (primaryKeyColumnName.equals("patient_id") && importedTables.contains("person") && !importedTables.contains("patient")) { sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")"; if (log.isDebugEnabled()) { log.debug(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); // ResultSet rs = s.getGeneratedKeys(); // rs.next(); // if (!columnGeneratedKey.equals(rs.getString(1))) { // throw new SpreadsheetImportUnhandledCaseException(); // } importedTables.add("patient"); } } // Add columns for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnName; columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName); } } // SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time if (isObservation) { boolean hasDatetime = false; for (SpreadsheetImportTemplateColumn column : columnSet) { if ("obs_datetime".equals(column.getColumnName())) { hasDatetime = true; break; } } if (!hasDatetime) { columnNames += ",obs_datetime"; columnValues += ",now()"; } } // SPECIAL TREATMENT: if this is patient identifier, then set location_id to NULL, to avoid CONSTRAINT `patient_identifier_ibfk_2` FOREIGN KEY (`location_id`) REFERENCES `location` (`location_id`)) if (isPatientIdentifier) { columnNames += ", location_id"; columnValues += ", NULL"; } // creator columnNames += ",creator"; columnValues += "," + Context.getAuthenticatedUser().getId(); // uuid DatabaseMetaData dmd = conn.getMetaData(); ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid"); if (rsColumns.next()) { columnNames += ",uuid"; columnValues += ",uuid()"; } rsColumns.close(); // Insert tableName sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values (" + columnValues + ")"; if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = s.getGeneratedKeys(); rs.next(); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(rs.getString(1)); } // SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller if (isEncounter) encounterId = rs.getString(1); rs.close(); importedTables.add(uniqueImport.getTableName()); } } catch (SQLSyntaxErrorException e) { throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); } catch (Exception e) { log.debug(e.toString()); exception = e; throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); // TODO: for web debug purpose only, should comment out later } finally { if (s != null) { try { s.close(); } catch (Exception e) {} } if (conn != null) { if (rollbackTransaction) { conn.rollback(); } else { conn.commit(); } try { conn.close(); } catch (Exception e) {} } } if (exception != null) { throw exception; } return encounterId; }
public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData, boolean rollbackTransaction) throws Exception { Connection conn = null; Statement s = null; Exception exception = null; String sql = null; String encounterId = null; try { // Connect to db Class.forName("com.mysql.jdbc.Driver").newInstance(); Properties p = Context.getRuntimeProperties(); String url = p.getProperty("connection.url"); conn = DriverManager.getConnection(url, p.getProperty("connection.username"), p.getProperty("connection.password")); conn.setAutoCommit(false); s = conn.createStatement(); List<String> importedTables = new ArrayList<String>(); // Import for (UniqueImport uniqueImport : rowData.keySet()) { String tableName = uniqueImport.getTableName(); boolean isEncounter = "encounter".equals(tableName); boolean isPerson = "person".equals(tableName); boolean isPatientIdentifier = "patient_identifier".equals(tableName); boolean isObservation = "obs".equals(tableName); boolean skip = false; // SPECIAL TREATMENT // for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter // otherwise, we need to create a new encounter if (isEncounter) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { Object columnValue = column.getValue(); if (!columnValue.equals("")) { column.setGeneratedKey(columnValue.toString()); skip = true; importedTables.add("encounter"); // fake as just imported encounter break; } } if (skip) continue; } if (isPerson) { boolean isIdentifierExist = false; // SPECIAL TREATMENT 1 // if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead // note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436) UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null); if (rowData.containsKey(patientIdentifier)) { Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData.get(patientIdentifier); for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) { String columnName = patientIdentifierColumn.getColumnName(); if ("identifier".equals(columnName)) { isIdentifierExist = true; sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue(); ResultSet rs = s.executeQuery(sql); if (rs.next()) { String patientId = rs.getString(1); // no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(patientId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("patient_identifier"); // fake as just imported patient_identifier importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } rs.close(); break; } } } if (skip) continue; // now, if we proceed to this point, it means patient identifier, if exists, does not match, and in that case, no point to match with person name // SPECIAL TREATMENT 2 // if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead UniqueImport personName = new UniqueImport("person_name", null); if (rowData.containsKey(personName) && !isIdentifierExist) { Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName); // getting gender, birthdate from person Object gender = null; Object birthdate = null; for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) { String columnName = personColumn.getColumnName(); if ("birth_date".equals(columnName)) birthdate = personColumn.getValue(); if ("gender".equals(columnName)) gender = personColumn.getValue(); } // getting first name, last name, middle name from person Object givenName = null; Object familyName = null; Object middleName = null; for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) { String columnName = personNameColumn.getColumnName(); if ("given_name".equals(columnName)) givenName = personNameColumn.getValue(); if ("family_name".equals(columnName)) familyName = personNameColumn.getValue(); if ("middle_name".equals(columnName)) middleName = personNameColumn.getValue(); } // find matching person name sql = "select person.person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName); ResultSet rs = s.executeQuery(sql); String personId = null; if (rs.next()) { // matched => no need to insert person, use the found patient_id as person_id Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(personId); } importedTables.add("person"); // fake as just imported person importedTables.add("patient"); // fake as just imported patient importedTables.add("person_name"); // fake as just imported person_name importedTables.add("person_address"); // fake as just imported person_address skip = true; } } if (skip) continue; } if (isPatientIdentifier && importedTables.contains("patient_identifier")) continue; // Data from columns Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); String columnNames = ""; String columnValues = ""; Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null; Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null; boolean isFirst = true; for (SpreadsheetImportTemplateColumn column : columnSet) { // special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id if (isEncounter) { columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); // inject date_created columnNames += "date_created"; columnValues += "now()"; // find encounter_datetime based on observation date time java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis()); Set<UniqueImport> uniqueImports = rowData.keySet(); for (UniqueImport u : uniqueImports) { if ("obs".equals(u.getTableName())) { Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u); for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) { if ("obs_datetime".equals(obsColumn.getColumnName())) { String obsColumnValue = obsColumn.getValue().toString(); obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length()-1); Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue); if (obsColumnValueDate.before(encounterDatetime)) encounterDatetime = obsColumnValueDate; } } } } columnNames += ", encounter_datetime"; columnValues += ",'" + encounterDatetime.toString() + "'"; isFirst = false; break; } // Check for duplicates if (column.getDisallowDuplicateValue()) { sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue(); if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } ResultSet rs = s.executeQuery(sql); boolean foundDuplicate = rs.next(); rs.close(); if (foundDuplicate) { throw new SpreadsheetImportDuplicateValueException(column); } } if (isFirst) { // Should be same for all columns in unique import columnPrespecifiedValueSet = column.getColumnPrespecifiedValues(); columnColumnsImportBefore = column.getColumnColumnsImportBefore(); isFirst = false; } else { columnNames += ","; columnValues += ","; } columnNames += column.getColumnName(); columnValues += column.getValue().toString(); } // Data from pre-specified values for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnPrespecifiedValue.getColumnName(); columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue(); } // Data from columns import before if (!columnColumnsImportBefore.isEmpty()) { // Set up Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>(); for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) { String primaryKeyColumnName = columnColumn.getColumnName(); String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey(); if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) { String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey.get(primaryKeyColumnName); if (!mapGeneratedKey.equals(columnGeneratedKey)) { throw new SpreadsheetImportUnhandledCaseException(); } } else { mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey); } // TODO: I believe patient and person are only tables with this relationship, if not, then this // needs to be generalized if (primaryKeyColumnName.equals("patient_id") && importedTables.contains("person") && !importedTables.contains("patient")) { sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")"; if (log.isDebugEnabled()) { log.debug(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); // ResultSet rs = s.getGeneratedKeys(); // rs.next(); // if (!columnGeneratedKey.equals(rs.getString(1))) { // throw new SpreadsheetImportUnhandledCaseException(); // } importedTables.add("patient"); } } // Add columns for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) { if (isFirst) isFirst = false; else { columnNames += ","; columnValues += ","; } columnNames += columnName; columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName); } } // SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time if (isObservation) { boolean hasDatetime = false; for (SpreadsheetImportTemplateColumn column : columnSet) { if ("obs_datetime".equals(column.getColumnName())) { hasDatetime = true; break; } } if (!hasDatetime) { columnNames += ",obs_datetime"; columnValues += ",now()"; } columnNames += ", date_created"; columnValues += ",now()"; } // SPECIAL TREATMENT: if this is patient identifier, then set location_id to NULL, to avoid CONSTRAINT `patient_identifier_ibfk_2` FOREIGN KEY (`location_id`) REFERENCES `location` (`location_id`)) if (isPatientIdentifier) { columnNames += ", location_id"; columnValues += ", NULL"; } // creator columnNames += ",creator"; columnValues += "," + Context.getAuthenticatedUser().getId(); // uuid DatabaseMetaData dmd = conn.getMetaData(); ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid"); if (rsColumns.next()) { columnNames += ",uuid"; columnValues += ",uuid()"; } rsColumns.close(); // Insert tableName sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values (" + columnValues + ")"; if (log.isDebugEnabled()) { log.debug(sql); System.out.println(sql); } s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = s.getGeneratedKeys(); rs.next(); for (SpreadsheetImportTemplateColumn column : columnSet) { column.setGeneratedKey(rs.getString(1)); } // SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller if (isEncounter) encounterId = rs.getString(1); rs.close(); importedTables.add(uniqueImport.getTableName()); } } catch (SQLSyntaxErrorException e) { throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); } catch (Exception e) { log.debug(e.toString()); exception = e; throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage()); // TODO: for web debug purpose only, should comment out later } finally { if (s != null) { try { s.close(); } catch (Exception e) {} } if (conn != null) { if (rollbackTransaction) { conn.rollback(); } else { conn.commit(); } try { conn.close(); } catch (Exception e) {} } } if (exception != null) { throw exception; } return encounterId; }
diff --git a/src/frontend/edu/brown/hstore/SpecExecScheduler.java b/src/frontend/edu/brown/hstore/SpecExecScheduler.java index f80a6e70f..81621f504 100644 --- a/src/frontend/edu/brown/hstore/SpecExecScheduler.java +++ b/src/frontend/edu/brown/hstore/SpecExecScheduler.java @@ -1,127 +1,127 @@ package edu.brown.hstore; import java.util.Iterator; import java.util.Queue; import org.apache.log4j.Logger; import org.voltdb.CatalogContext; import org.voltdb.catalog.Procedure; import edu.brown.hstore.internal.InternalMessage; import edu.brown.hstore.internal.StartTxnMessage; import edu.brown.hstore.internal.WorkFragmentMessage; import edu.brown.hstore.specexec.AbstractConflictChecker; import edu.brown.hstore.specexec.TableConflictChecker; import edu.brown.hstore.txns.AbstractTransaction; import edu.brown.hstore.txns.LocalTransaction; import edu.brown.logging.LoggerUtil; import edu.brown.logging.LoggerUtil.LoggerBoolean; /** * Special scheduler that can figure out what the next best single-partition * to speculatively execute at a partition based on the current distributed transaction * @author pavlo */ public class SpecExecScheduler { private static final Logger LOG = Logger.getLogger(SpecExecScheduler.class); private static final LoggerBoolean debug = new LoggerBoolean(LOG.isDebugEnabled()); private static final LoggerBoolean trace = new LoggerBoolean(LOG.isTraceEnabled()); static { LoggerUtil.attachObserver(LOG, debug, trace); } private final CatalogContext catalogContext; private final int partitionId; private final Queue<InternalMessage> work_queue; private final AbstractConflictChecker checker; /** * Constructor * @param catalogContext * @param partitionId * @param work_queue */ public SpecExecScheduler(CatalogContext catalogContext, int partitionId, Queue<InternalMessage> work_queue) { this.partitionId = partitionId; this.work_queue = work_queue; this.catalogContext = catalogContext; this.checker = new TableConflictChecker(this.catalogContext); } /** * Find the next non-conflicting txn that we can speculatively execute. * Note that if we find one, it will be immediately removed from the queue * and returned. If you do this and then find out for some reason that you * can't execute the StartTxnMessage that is returned, you must be sure * to requeue it back. * @param dtxn The current distributed txn at this partition. * @return */ public StartTxnMessage next(AbstractTransaction dtxn) { Procedure dtxnProc = this.catalogContext.getProcedureById(dtxn.getProcedureId()); if (dtxnProc == null || this.checker.ignoreProcedure(dtxnProc)) { if (debug.get()) LOG.debug(String.format("%s - Ignoring current distributed txn because no conflict information exists [%s]", dtxn, dtxnProc)); return (null); } // If this is a LocalTransaction and all of the remote partitions that it needs are // on the same site, then we won't bother with trying to pick something out // because there is going to be very small wait times. if (dtxn instanceof LocalTransaction && ((LocalTransaction)dtxn).isPredictAllLocal()) { if (debug.get()) LOG.debug(String.format("%s - Ignoring current distributed txn because all of the partitions that " + "it is using are on the same HStoreSite [%s]", dtxn, dtxnProc)); return (null); } // Now peek in the queue looking for single-partition txns that do not // conflict with the current dtxn StartTxnMessage next = null; Iterator<InternalMessage> it = this.work_queue.iterator(); while (it.hasNext()) { InternalMessage msg = it.next(); // Any WorkFragmentMessage has to be for our current dtxn, // so we want to never speculative execute stuff because we will // always want to immediately execute that if (msg instanceof WorkFragmentMessage) { if (debug.get()) LOG.debug(String.format("%s - Not choosing a txn to speculatively execute because there " + "are still WorkFragments in the queue", dtxn)); return (null); } // A StartTxnMessage will have a fully initialized LocalTransaction handle // that we can examine and execute right away if necessary else if (msg instanceof StartTxnMessage) { StartTxnMessage txn_msg = (StartTxnMessage)msg; LocalTransaction ts = txn_msg.getTransaction(); if (debug.get()) LOG.debug(String.format("Examining whether %s conflicts with current dtxn %s", ts, dtxn)); if (ts.isPredictSinglePartition() == false) { if (trace.get()) LOG.trace(String.format("%s - Skipping %s because it is not single-partitioned", dtxn, ts)); continue; } - if (this.checker.canExecute(dtxn, ts, this.partitionId) == false) { + if (this.checker.canExecute(dtxn, ts, this.partitionId)) { next = txn_msg; break; } } } // WHILE // We found somebody to execute right now! // Make sure that we set the speculative flag to true! if (next != null) { it.remove(); LocalTransaction next_ts = next.getTransaction(); next_ts.setSpeculative(true); if (debug.get()) LOG.debug(dtxn + " - Found next non-conflicting speculative txn " + next); } return (next); } }
true
true
public StartTxnMessage next(AbstractTransaction dtxn) { Procedure dtxnProc = this.catalogContext.getProcedureById(dtxn.getProcedureId()); if (dtxnProc == null || this.checker.ignoreProcedure(dtxnProc)) { if (debug.get()) LOG.debug(String.format("%s - Ignoring current distributed txn because no conflict information exists [%s]", dtxn, dtxnProc)); return (null); } // If this is a LocalTransaction and all of the remote partitions that it needs are // on the same site, then we won't bother with trying to pick something out // because there is going to be very small wait times. if (dtxn instanceof LocalTransaction && ((LocalTransaction)dtxn).isPredictAllLocal()) { if (debug.get()) LOG.debug(String.format("%s - Ignoring current distributed txn because all of the partitions that " + "it is using are on the same HStoreSite [%s]", dtxn, dtxnProc)); return (null); } // Now peek in the queue looking for single-partition txns that do not // conflict with the current dtxn StartTxnMessage next = null; Iterator<InternalMessage> it = this.work_queue.iterator(); while (it.hasNext()) { InternalMessage msg = it.next(); // Any WorkFragmentMessage has to be for our current dtxn, // so we want to never speculative execute stuff because we will // always want to immediately execute that if (msg instanceof WorkFragmentMessage) { if (debug.get()) LOG.debug(String.format("%s - Not choosing a txn to speculatively execute because there " + "are still WorkFragments in the queue", dtxn)); return (null); } // A StartTxnMessage will have a fully initialized LocalTransaction handle // that we can examine and execute right away if necessary else if (msg instanceof StartTxnMessage) { StartTxnMessage txn_msg = (StartTxnMessage)msg; LocalTransaction ts = txn_msg.getTransaction(); if (debug.get()) LOG.debug(String.format("Examining whether %s conflicts with current dtxn %s", ts, dtxn)); if (ts.isPredictSinglePartition() == false) { if (trace.get()) LOG.trace(String.format("%s - Skipping %s because it is not single-partitioned", dtxn, ts)); continue; } if (this.checker.canExecute(dtxn, ts, this.partitionId) == false) { next = txn_msg; break; } } } // WHILE // We found somebody to execute right now! // Make sure that we set the speculative flag to true! if (next != null) { it.remove(); LocalTransaction next_ts = next.getTransaction(); next_ts.setSpeculative(true); if (debug.get()) LOG.debug(dtxn + " - Found next non-conflicting speculative txn " + next); } return (next); }
public StartTxnMessage next(AbstractTransaction dtxn) { Procedure dtxnProc = this.catalogContext.getProcedureById(dtxn.getProcedureId()); if (dtxnProc == null || this.checker.ignoreProcedure(dtxnProc)) { if (debug.get()) LOG.debug(String.format("%s - Ignoring current distributed txn because no conflict information exists [%s]", dtxn, dtxnProc)); return (null); } // If this is a LocalTransaction and all of the remote partitions that it needs are // on the same site, then we won't bother with trying to pick something out // because there is going to be very small wait times. if (dtxn instanceof LocalTransaction && ((LocalTransaction)dtxn).isPredictAllLocal()) { if (debug.get()) LOG.debug(String.format("%s - Ignoring current distributed txn because all of the partitions that " + "it is using are on the same HStoreSite [%s]", dtxn, dtxnProc)); return (null); } // Now peek in the queue looking for single-partition txns that do not // conflict with the current dtxn StartTxnMessage next = null; Iterator<InternalMessage> it = this.work_queue.iterator(); while (it.hasNext()) { InternalMessage msg = it.next(); // Any WorkFragmentMessage has to be for our current dtxn, // so we want to never speculative execute stuff because we will // always want to immediately execute that if (msg instanceof WorkFragmentMessage) { if (debug.get()) LOG.debug(String.format("%s - Not choosing a txn to speculatively execute because there " + "are still WorkFragments in the queue", dtxn)); return (null); } // A StartTxnMessage will have a fully initialized LocalTransaction handle // that we can examine and execute right away if necessary else if (msg instanceof StartTxnMessage) { StartTxnMessage txn_msg = (StartTxnMessage)msg; LocalTransaction ts = txn_msg.getTransaction(); if (debug.get()) LOG.debug(String.format("Examining whether %s conflicts with current dtxn %s", ts, dtxn)); if (ts.isPredictSinglePartition() == false) { if (trace.get()) LOG.trace(String.format("%s - Skipping %s because it is not single-partitioned", dtxn, ts)); continue; } if (this.checker.canExecute(dtxn, ts, this.partitionId)) { next = txn_msg; break; } } } // WHILE // We found somebody to execute right now! // Make sure that we set the speculative flag to true! if (next != null) { it.remove(); LocalTransaction next_ts = next.getTransaction(); next_ts.setSpeculative(true); if (debug.get()) LOG.debug(dtxn + " - Found next non-conflicting speculative txn " + next); } return (next); }
diff --git a/src/java/com/idega/block/cal/data/AttendanceMarkBMPBean.java b/src/java/com/idega/block/cal/data/AttendanceMarkBMPBean.java index 8e733f3..8e92156 100644 --- a/src/java/com/idega/block/cal/data/AttendanceMarkBMPBean.java +++ b/src/java/com/idega/block/cal/data/AttendanceMarkBMPBean.java @@ -1,70 +1,70 @@ /* * Created on Mar 16, 2004 */ package com.idega.block.cal.data; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.ejb.FinderException; import com.idega.data.GenericEntity; /** * Description: <br> * Copyright: Idega Software 2004 <br> * Company: Idega Software <br> * @author <a href="mailto:[email protected]">Birna Iris Jonsdottir</a> */ public class AttendanceMarkBMPBean extends GenericEntity implements com.idega.block.cal.data.AttendanceMark{ public void insertStartData() throws Exception{ AttendanceMarkHome markHome = (AttendanceMarkHome) getIDOHome(AttendanceMark.class); final String [] data = { "x", "s", "v", "f", " " }; - final String [] description = { "M�tt(ur)", "Sein(n)", "Veik(ur)", "Fjarverandi", " "}; + final String [] description = { "Mætt(ur)", "Sein(n)", "Veik(ur)", "Fjarverandi", " "}; for (int i = 0; i < data.length; i++) { AttendanceMark mark = markHome.create(); mark.setMark(data[i]); mark.setMarkDescription(description[i]); mark.store(); } } public void initializeAttributes(){ addAttribute(getColumnNameMarkID()); addAttribute(getColumnNameMark(),"Mark",true,true,String.class); addAttribute(getColumnNameMarkDescription(),"Mark Description",true,true,String.class); } public static String getEntityTableName() { return "CAL_ATTENDANCE_MARK"; } public static String getColumnNameMarkID() { return "CAL_MARK_ID"; } public static String getColumnNameMark() { return "CAL_MARK"; } public static String getColumnNameMarkDescription() { return "CAL_MARK_DESCRIPTION"; } public String getEntityName() { return getEntityTableName(); } //GET public String getMark() { return getStringColumnValue(getColumnNameMark()); } public String getMarkDescription() { return getStringColumnValue(getColumnNameMarkDescription()); } //SET public void setMark(String mark) { setColumn(getColumnNameMark(),mark); } public void setMarkDescription(String markDescription) { setColumn(getColumnNameMarkDescription(),markDescription); } public Collection ejbFindMarks() throws FinderException{ List result = new ArrayList(super.idoFindAllIDsOrderedBySQL(getColumnNameMark())); return result; } }
true
true
public void insertStartData() throws Exception{ AttendanceMarkHome markHome = (AttendanceMarkHome) getIDOHome(AttendanceMark.class); final String [] data = { "x", "s", "v", "f", " " }; final String [] description = { "M�tt(ur)", "Sein(n)", "Veik(ur)", "Fjarverandi", " "}; for (int i = 0; i < data.length; i++) { AttendanceMark mark = markHome.create(); mark.setMark(data[i]); mark.setMarkDescription(description[i]); mark.store(); } }
public void insertStartData() throws Exception{ AttendanceMarkHome markHome = (AttendanceMarkHome) getIDOHome(AttendanceMark.class); final String [] data = { "x", "s", "v", "f", " " }; final String [] description = { "Mætt(ur)", "Sein(n)", "Veik(ur)", "Fjarverandi", " "}; for (int i = 0; i < data.length; i++) { AttendanceMark mark = markHome.create(); mark.setMark(data[i]); mark.setMarkDescription(description[i]); mark.store(); } }
diff --git a/src/net/minterval/versioning/GitTag.java b/src/net/minterval/versioning/GitTag.java index fca02ab..b579f5f 100644 --- a/src/net/minterval/versioning/GitTag.java +++ b/src/net/minterval/versioning/GitTag.java @@ -1,103 +1,103 @@ /* * Copyright (c) 2012 Corey Minter * (see LICENSE file) */ package net.minterval.versioning; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import org.apache.tools.ant.BuildException; /** * * @author cminter */ public class GitTag extends ExtTask { private static final String gitPathEnv= "GIT_EXE"; private static final String gitDirName= ".git"; private static final String dirtySuffix= "-dirty"; private static final String gitOpts= "describe --dirty --long --match \"%s*\""; private static final String gitPathAttr= "gitpath"; private static final String tagPrefixAttr= "tagprefix"; private static final String longVersionAttr= "longversionproperty"; private static final String shortVersionAttr= "shortversionproperty"; private static final String cleanAttr= "cleanproperty"; public GitTag() { setAttr(gitPathAttr, "git"); setAttr(tagPrefixAttr, "v-"); } @Override public void execute() throws BuildException { ensureProps(gitPathAttr, tagPrefixAttr, longVersionAttr, shortVersionAttr, cleanAttr); File baseDir= getProject().getBaseDir(); File gitDir= new File(baseDir, gitDirName); String longVersion= "none"; String shortVersion= "none"; Boolean clean= Boolean.TRUE; if (gitDir.exists()) { // use user's environment if supplied String commandPath= System.getenv(gitPathEnv); // otherwise fallback to build property if (commandPath == null) { commandPath= getAttr(gitPathAttr); } String commandOpts= String.format(gitOpts, getAttr(tagPrefixAttr)); String command= String.format("%s %s", commandPath, commandOpts); try { Process proc= Runtime.getRuntime().exec(command, null, baseDir); int status= proc.waitFor(); if (status != 0) { BufferedReader br= new BufferedReader(new InputStreamReader(proc.getErrorStream())); String errorOut= br.readLine(); String msg= String.format("failed executing '%s', %s (%d)", command, errorOut, status); throw new BuildException(msg); } BufferedReader br= new BufferedReader(new InputStreamReader(proc.getInputStream())); longVersion= br.readLine().substring(getAttr(tagPrefixAttr).length()); clean= Boolean.valueOf(! longVersion.endsWith(dirtySuffix)); String[] tagParts= longVersion.split("-"); StringBuilder tmpShortVersion= new StringBuilder(tagParts[0]); if (tagParts.length < 2) { tmpShortVersion.append(".0"); } else { tmpShortVersion.append('.').append(tagParts[1]); } shortVersion= tmpShortVersion.toString(); } catch (InterruptedException ie) { String msg= String.format("interrupted waiting for '%s' to finish", command); throw new BuildException(msg); } catch (IOException ioe) { String msg= String.format("failed reading output from command '%s', %s", command, ioe.getMessage()); throw new BuildException(msg); } - getProject().setNewProperty(getAttr(longVersionAttr), longVersion); - getProject().setNewProperty(getAttr(cleanAttr), clean.toString()); - getProject().setNewProperty(getAttr(shortVersionAttr), shortVersion); } + getProject().setNewProperty(getAttr(longVersionAttr), longVersion); + getProject().setNewProperty(getAttr(cleanAttr), clean.toString()); + getProject().setNewProperty(getAttr(shortVersionAttr), shortVersion); } public void setGitpath(final String value) { setAttr(gitPathAttr, value); } public void setTagprefix(final String value) { setAttr(tagPrefixAttr, value); } public void setLongversionproperty(final String value) { setAttr(longVersionAttr, value); } public void setShortversionproperty(final String value) { setAttr(shortVersionAttr, value); } public void setCleanproperty(final String value) { setAttr(cleanAttr, value); } }
false
true
public void execute() throws BuildException { ensureProps(gitPathAttr, tagPrefixAttr, longVersionAttr, shortVersionAttr, cleanAttr); File baseDir= getProject().getBaseDir(); File gitDir= new File(baseDir, gitDirName); String longVersion= "none"; String shortVersion= "none"; Boolean clean= Boolean.TRUE; if (gitDir.exists()) { // use user's environment if supplied String commandPath= System.getenv(gitPathEnv); // otherwise fallback to build property if (commandPath == null) { commandPath= getAttr(gitPathAttr); } String commandOpts= String.format(gitOpts, getAttr(tagPrefixAttr)); String command= String.format("%s %s", commandPath, commandOpts); try { Process proc= Runtime.getRuntime().exec(command, null, baseDir); int status= proc.waitFor(); if (status != 0) { BufferedReader br= new BufferedReader(new InputStreamReader(proc.getErrorStream())); String errorOut= br.readLine(); String msg= String.format("failed executing '%s', %s (%d)", command, errorOut, status); throw new BuildException(msg); } BufferedReader br= new BufferedReader(new InputStreamReader(proc.getInputStream())); longVersion= br.readLine().substring(getAttr(tagPrefixAttr).length()); clean= Boolean.valueOf(! longVersion.endsWith(dirtySuffix)); String[] tagParts= longVersion.split("-"); StringBuilder tmpShortVersion= new StringBuilder(tagParts[0]); if (tagParts.length < 2) { tmpShortVersion.append(".0"); } else { tmpShortVersion.append('.').append(tagParts[1]); } shortVersion= tmpShortVersion.toString(); } catch (InterruptedException ie) { String msg= String.format("interrupted waiting for '%s' to finish", command); throw new BuildException(msg); } catch (IOException ioe) { String msg= String.format("failed reading output from command '%s', %s", command, ioe.getMessage()); throw new BuildException(msg); } getProject().setNewProperty(getAttr(longVersionAttr), longVersion); getProject().setNewProperty(getAttr(cleanAttr), clean.toString()); getProject().setNewProperty(getAttr(shortVersionAttr), shortVersion); } }
public void execute() throws BuildException { ensureProps(gitPathAttr, tagPrefixAttr, longVersionAttr, shortVersionAttr, cleanAttr); File baseDir= getProject().getBaseDir(); File gitDir= new File(baseDir, gitDirName); String longVersion= "none"; String shortVersion= "none"; Boolean clean= Boolean.TRUE; if (gitDir.exists()) { // use user's environment if supplied String commandPath= System.getenv(gitPathEnv); // otherwise fallback to build property if (commandPath == null) { commandPath= getAttr(gitPathAttr); } String commandOpts= String.format(gitOpts, getAttr(tagPrefixAttr)); String command= String.format("%s %s", commandPath, commandOpts); try { Process proc= Runtime.getRuntime().exec(command, null, baseDir); int status= proc.waitFor(); if (status != 0) { BufferedReader br= new BufferedReader(new InputStreamReader(proc.getErrorStream())); String errorOut= br.readLine(); String msg= String.format("failed executing '%s', %s (%d)", command, errorOut, status); throw new BuildException(msg); } BufferedReader br= new BufferedReader(new InputStreamReader(proc.getInputStream())); longVersion= br.readLine().substring(getAttr(tagPrefixAttr).length()); clean= Boolean.valueOf(! longVersion.endsWith(dirtySuffix)); String[] tagParts= longVersion.split("-"); StringBuilder tmpShortVersion= new StringBuilder(tagParts[0]); if (tagParts.length < 2) { tmpShortVersion.append(".0"); } else { tmpShortVersion.append('.').append(tagParts[1]); } shortVersion= tmpShortVersion.toString(); } catch (InterruptedException ie) { String msg= String.format("interrupted waiting for '%s' to finish", command); throw new BuildException(msg); } catch (IOException ioe) { String msg= String.format("failed reading output from command '%s', %s", command, ioe.getMessage()); throw new BuildException(msg); } } getProject().setNewProperty(getAttr(longVersionAttr), longVersion); getProject().setNewProperty(getAttr(cleanAttr), clean.toString()); getProject().setNewProperty(getAttr(shortVersionAttr), shortVersion); }
diff --git a/src/com/dogcows/Editor.java b/src/com/dogcows/Editor.java index 57e1b77..ea68058 100644 --- a/src/com/dogcows/Editor.java +++ b/src/com/dogcows/Editor.java @@ -1,340 +1,340 @@ package com.dogcows; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import com.topcoder.client.contestant.ProblemComponentModel; import com.topcoder.shared.language.Language; import com.topcoder.shared.problem.DataType; import com.topcoder.shared.problem.Renderer; import com.topcoder.shared.problem.TestCase; /** * @author Charles McGarvey * The TopCoder Arena editor plug-in providing support for Vim. * * Distributable under the terms and conditions of the 2-clause BSD license; * see the file COPYING for a complete text of the license. */ public class Editor { /** * The problem ID number. */ private String id; /** * The name of the class. */ private String name; /** * The path of the current source file. */ private File sourceFile; /** * The path of the problem directory. */ private File directory; /** * Map languages names to file extensions. */ private static final Map<String,String> languageExtension = new HashMap<String,String>(); static { languageExtension.put("Java", "java"); languageExtension.put("C++", "cc"); languageExtension.put("C#", "cs"); languageExtension.put("VB", "vb"); languageExtension.put("Python", "py"); } /** * Construct an editor with the problem objects given us by the Arena. * @param component A container for the particulars of the problem. * @param language The currently selected language. * @param renderer A helper object to help format the problem statement. * @throws Exception If the editor could not set itself up. */ public Editor(ProblemComponentModel component, Language language, Renderer renderer) throws Exception { this.id = String.valueOf(component.getProblem().getProblemID()); this.name = component.getClassName(); // Make sure the top-level vimcoder directory exists. File topDir = VimCoder.getStorageDirectory(); if (!topDir.isDirectory()) { if (!topDir.mkdirs()) throw new IOException(topDir.getPath()); } // Make sure the problem directory exists. this.directory = new File(topDir, id); if (!directory.isDirectory()) { if (!directory.mkdirs()) throw new IOException(directory.getPath()); } String lang = language.getName(); String ext = languageExtension.get(lang); // Set up the terms used for the template expansion. HashMap<String,String> terms = new HashMap<String,String>(); terms.put("RETURNTYPE", component.getReturnType().getDescriptor(language).replaceAll("\\s+", "")); terms.put("CLASSNAME", name); terms.put("METHODNAME", component.getMethodName()); terms.put("METHODPARAMS", getMethodParams(component.getParamTypes(), component.getParamNames(), language)); terms.put("METHODPARAMNAMES", Util.join(component.getParamNames(), ", ")); terms.put("METHODPARAMSTREAMIN", Util.join(component.getParamNames(), " >> ")); - terms.put("METHODPARAMSTREAMOUT", Util.join(component.getParamNames(), " << ")); + terms.put("METHODPARAMSTREAMOUT", Util.join(component.getParamNames(), " << \", \" << ")); terms.put("METHODPARAMDECLARES", getMethodParamDeclarations(component.getParamTypes(), component.getParamNames(), language)); // Write the problem statement as an HTML file in the problem directory. File problemFile = new File(directory, "Problem.html"); if (!problemFile.canRead()) { FileWriter writer = new FileWriter(problemFile); try { writer.write(renderer.toHTML(language)); } finally { writer.close(); } } // Expand the template for the main class and write it to the current // source file. sourceFile = new File(directory, name + "." + ext); if (!sourceFile.canRead()) { String text = Util.expandTemplate(readTemplate(lang + "Template"), terms); FileWriter writer = new FileWriter(sourceFile); writer.write(text); writer.close(); } // Expand the driver template and write it to a source file. File driverFile = new File(directory, "driver." + ext); if (!driverFile.canRead()) { String text = Util.expandTemplate(readTemplate(lang + "Driver"), terms); FileWriter writer = new FileWriter(driverFile); writer.write(text); writer.close(); } // Write the test cases to a text file. The driver code can read this // file and perform the tests based on what it reads. File testcaseFile = new File(directory, "testcases.txt"); if (!testcaseFile.canRead()) { StringBuilder text = new StringBuilder(); if (component.hasTestCases()) { for (TestCase testCase : component.getTestCases()) { text.append(testCase.getOutput() + System.getProperty("line.separator")); for (String input : testCase.getInput()) { text.append(input + System.getProperty("line.separator")); } } } FileWriter writer = new FileWriter(testcaseFile); writer.write(text.toString()); writer.close(); } // Finally, expand the Makefile template and write it. File makeFile = new File(directory, "Makefile"); { String text = Util.expandTemplate(readTemplate(lang + "Makefile"), terms); FileWriter writer = new FileWriter(makeFile); writer.write(text); writer.close(); } } /** * Save the source code provided by the server, and tell the Vim server to * edit the current source file. * @param source The source code. * @throws Exception If the source couldn't be written or the Vim server * had a problem. */ public void setSource(String source) throws Exception { FileWriter writer = new FileWriter(new File(directory, name)); writer.write(source); writer.close(); sendVimCommand("--remote-tab-silent", sourceFile.getPath()); } /** * Read the source code from the current source file. * @return The source code. * @throws IOException If the source file could not be read. */ public String getSource() throws IOException { return Util.readFile(sourceFile) + "\n// Edited by " + VimCoder.version + "\n// " + VimCoder.website + "\n\n"; } /** * Send a command to the Vim server. * If the server isn't running, it will be started with the name * VIMCODER#### where #### is the problem ID. * @param command The command to send to the server. * @param argument A single argument for the remote command. * @throws Exception If the command could not be sent. */ private void sendVimCommand(String command, String argument) throws Exception { String[] arguments = {argument}; sendVimCommand(command, arguments); } /** * Send a command to the Vim server. * If the server isn't running, it will be started with the name * VIMCODER#### where #### is the problem ID. * @param command The command to send to the server. * @param argument Arguments for the remote command. * @throws Exception If the command could not be sent. */ private void sendVimCommand(String command, String[] arguments) throws Exception { String[] vimCommand = VimCoder.getVimCommand().split("\\s"); String[] flags = {"--servername", "VimCoder" + id, command}; vimCommand = Util.concat(vimCommand, flags); vimCommand = Util.concat(vimCommand, arguments); Process child = Runtime.getRuntime().exec(vimCommand, null, directory); /* FIXME: This is a pretty bad hack. The problem is that the Vim * process doesn't fork to the background on some systems, so we * can't wait on the child. At the same time, calling this method * before the previous child could finish initializing the server * may result in multiple editor windows popping up. We'd also * like to be able to get the return code from the child if we can. * The workaround here is to stall the thread for a little while or * until we see that the child exits. If the child never exits * before the timeout, we will assume it is not backgrounding and * that everything worked. This works as long as the Vim server is * able to start within the stall period. */ long expire = System.currentTimeMillis() + 250; while (System.currentTimeMillis() < expire) { Thread.yield(); try { int exitCode = child.exitValue(); if (exitCode != 0) throw new Exception("Vim process returned exit code " + exitCode + "."); break; } catch (IllegalThreadStateException exception) { // The child has not exited; intentionally ignoring exception. } } } /** * Read a template. * We first look in the storage directory. If we can't find one, we * look among the resources. * @param tName The name of the template. * @return The contents of the template file, or an empty string. */ private String readTemplate(String tName) { File templateFile = new File(VimCoder.getStorageDirectory(), tName); try { if (templateFile.canRead()) return Util.readFile(templateFile); return Util.readResource(tName); } catch (IOException exception) { return ""; } } /** * Convert an array of data types to an array of strings according to a * given language. * @param types The data types. * @param language The language to use in the conversion. * @return The array of string representations of the data types. */ private String[] getStringTypes(DataType[] types, Language language) { String[] strings = new String[types.length]; for (int i = 0; i < types.length; ++i) { strings[i] = types[i].getDescriptor(language).replaceAll("\\s+", ""); } return strings; } /** * Combine the data types and parameter names into a comma-separated list of * the method parameters. * The result could be used inside the parentheses of a method * declaration. * @param types The data types of the parameters. * @param names The names of the parameters. * @param language The language used for representing the data types. * @return The list of parameters. */ private String getMethodParams(DataType[] types, String[] names, Language language) { String[] typeStrings = getStringTypes(types, language); return Util.join(Util.combine(typeStrings, names, " "), ", "); } /** * Combine the data types and parameter names into a group of variable * declarations. * Each declaration is separated by a new line and terminated with a * semicolon. * @param types The data types of the parameters. * @param names The names of the parameters. * @param language The language used for representing the data types. * @return The parameters as a block of declarations. */ private String getMethodParamDeclarations(DataType[] types, String[] names, Language language) { final String end = ";" + System.getProperty("line.separator"); String[] typeStrings = getStringTypes(types, language); return Util.join(Util.combine(typeStrings, names, "\t"), end) + end; } }
true
true
public Editor(ProblemComponentModel component, Language language, Renderer renderer) throws Exception { this.id = String.valueOf(component.getProblem().getProblemID()); this.name = component.getClassName(); // Make sure the top-level vimcoder directory exists. File topDir = VimCoder.getStorageDirectory(); if (!topDir.isDirectory()) { if (!topDir.mkdirs()) throw new IOException(topDir.getPath()); } // Make sure the problem directory exists. this.directory = new File(topDir, id); if (!directory.isDirectory()) { if (!directory.mkdirs()) throw new IOException(directory.getPath()); } String lang = language.getName(); String ext = languageExtension.get(lang); // Set up the terms used for the template expansion. HashMap<String,String> terms = new HashMap<String,String>(); terms.put("RETURNTYPE", component.getReturnType().getDescriptor(language).replaceAll("\\s+", "")); terms.put("CLASSNAME", name); terms.put("METHODNAME", component.getMethodName()); terms.put("METHODPARAMS", getMethodParams(component.getParamTypes(), component.getParamNames(), language)); terms.put("METHODPARAMNAMES", Util.join(component.getParamNames(), ", ")); terms.put("METHODPARAMSTREAMIN", Util.join(component.getParamNames(), " >> ")); terms.put("METHODPARAMSTREAMOUT", Util.join(component.getParamNames(), " << ")); terms.put("METHODPARAMDECLARES", getMethodParamDeclarations(component.getParamTypes(), component.getParamNames(), language)); // Write the problem statement as an HTML file in the problem directory. File problemFile = new File(directory, "Problem.html"); if (!problemFile.canRead()) { FileWriter writer = new FileWriter(problemFile); try { writer.write(renderer.toHTML(language)); } finally { writer.close(); } } // Expand the template for the main class and write it to the current // source file. sourceFile = new File(directory, name + "." + ext); if (!sourceFile.canRead()) { String text = Util.expandTemplate(readTemplate(lang + "Template"), terms); FileWriter writer = new FileWriter(sourceFile); writer.write(text); writer.close(); } // Expand the driver template and write it to a source file. File driverFile = new File(directory, "driver." + ext); if (!driverFile.canRead()) { String text = Util.expandTemplate(readTemplate(lang + "Driver"), terms); FileWriter writer = new FileWriter(driverFile); writer.write(text); writer.close(); } // Write the test cases to a text file. The driver code can read this // file and perform the tests based on what it reads. File testcaseFile = new File(directory, "testcases.txt"); if (!testcaseFile.canRead()) { StringBuilder text = new StringBuilder(); if (component.hasTestCases()) { for (TestCase testCase : component.getTestCases()) { text.append(testCase.getOutput() + System.getProperty("line.separator")); for (String input : testCase.getInput()) { text.append(input + System.getProperty("line.separator")); } } } FileWriter writer = new FileWriter(testcaseFile); writer.write(text.toString()); writer.close(); } // Finally, expand the Makefile template and write it. File makeFile = new File(directory, "Makefile"); { String text = Util.expandTemplate(readTemplate(lang + "Makefile"), terms); FileWriter writer = new FileWriter(makeFile); writer.write(text); writer.close(); } }
public Editor(ProblemComponentModel component, Language language, Renderer renderer) throws Exception { this.id = String.valueOf(component.getProblem().getProblemID()); this.name = component.getClassName(); // Make sure the top-level vimcoder directory exists. File topDir = VimCoder.getStorageDirectory(); if (!topDir.isDirectory()) { if (!topDir.mkdirs()) throw new IOException(topDir.getPath()); } // Make sure the problem directory exists. this.directory = new File(topDir, id); if (!directory.isDirectory()) { if (!directory.mkdirs()) throw new IOException(directory.getPath()); } String lang = language.getName(); String ext = languageExtension.get(lang); // Set up the terms used for the template expansion. HashMap<String,String> terms = new HashMap<String,String>(); terms.put("RETURNTYPE", component.getReturnType().getDescriptor(language).replaceAll("\\s+", "")); terms.put("CLASSNAME", name); terms.put("METHODNAME", component.getMethodName()); terms.put("METHODPARAMS", getMethodParams(component.getParamTypes(), component.getParamNames(), language)); terms.put("METHODPARAMNAMES", Util.join(component.getParamNames(), ", ")); terms.put("METHODPARAMSTREAMIN", Util.join(component.getParamNames(), " >> ")); terms.put("METHODPARAMSTREAMOUT", Util.join(component.getParamNames(), " << \", \" << ")); terms.put("METHODPARAMDECLARES", getMethodParamDeclarations(component.getParamTypes(), component.getParamNames(), language)); // Write the problem statement as an HTML file in the problem directory. File problemFile = new File(directory, "Problem.html"); if (!problemFile.canRead()) { FileWriter writer = new FileWriter(problemFile); try { writer.write(renderer.toHTML(language)); } finally { writer.close(); } } // Expand the template for the main class and write it to the current // source file. sourceFile = new File(directory, name + "." + ext); if (!sourceFile.canRead()) { String text = Util.expandTemplate(readTemplate(lang + "Template"), terms); FileWriter writer = new FileWriter(sourceFile); writer.write(text); writer.close(); } // Expand the driver template and write it to a source file. File driverFile = new File(directory, "driver." + ext); if (!driverFile.canRead()) { String text = Util.expandTemplate(readTemplate(lang + "Driver"), terms); FileWriter writer = new FileWriter(driverFile); writer.write(text); writer.close(); } // Write the test cases to a text file. The driver code can read this // file and perform the tests based on what it reads. File testcaseFile = new File(directory, "testcases.txt"); if (!testcaseFile.canRead()) { StringBuilder text = new StringBuilder(); if (component.hasTestCases()) { for (TestCase testCase : component.getTestCases()) { text.append(testCase.getOutput() + System.getProperty("line.separator")); for (String input : testCase.getInput()) { text.append(input + System.getProperty("line.separator")); } } } FileWriter writer = new FileWriter(testcaseFile); writer.write(text.toString()); writer.close(); } // Finally, expand the Makefile template and write it. File makeFile = new File(directory, "Makefile"); { String text = Util.expandTemplate(readTemplate(lang + "Makefile"), terms); FileWriter writer = new FileWriter(makeFile); writer.write(text); writer.close(); } }
diff --git a/src/main/java/org/apache/james/jspf/terms/IP6Mechanism.java b/src/main/java/org/apache/james/jspf/terms/IP6Mechanism.java index 3ce2e16..de78db2 100644 --- a/src/main/java/org/apache/james/jspf/terms/IP6Mechanism.java +++ b/src/main/java/org/apache/james/jspf/terms/IP6Mechanism.java @@ -1,53 +1,50 @@ /**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.jspf.terms; import org.apache.james.jspf.util.Inet6Util; /** * This class represent the ip6 mechanism * */ public class IP6Mechanism extends IP4Mechanism { /** * ABNF: IP6 = "ip6" ":" ip6-network [ ip6-cidr-length ] */ public static final String REGEX = "[iI][pP][6]" + "\\:([0-9A-Fa-f\\:\\.]+)" + "(?:" + IP6_CIDR_LENGTH_REGEX + ")?"; /** * @see org.apache.james.jspf.terms.IP4Mechanism#isValidAddress(String) */ protected boolean isValidAddress(String ipString) { - // TODO: this check is not accurate ":CAFE::BABE" pass the test but is invalid - boolean res = Inet6Util.isValidIP6Address(ipString); - // System.err.println("IP6: " + ipString + " valid? "+res); - return res; + return Inet6Util.isValidIP6Address(ipString); } /** * @see org.apache.james.jspf.terms.IP4Mechanism#getMaxCidr() */ protected int getMaxCidr() { return 128; } }
true
true
protected boolean isValidAddress(String ipString) { // TODO: this check is not accurate ":CAFE::BABE" pass the test but is invalid boolean res = Inet6Util.isValidIP6Address(ipString); // System.err.println("IP6: " + ipString + " valid? "+res); return res; }
protected boolean isValidAddress(String ipString) { return Inet6Util.isValidIP6Address(ipString); }
diff --git a/src/main/java/org/atlasapi/equiv/handlers/EpisodeFilteringEquivalenceResultHandler.java b/src/main/java/org/atlasapi/equiv/handlers/EpisodeFilteringEquivalenceResultHandler.java index b07526aad..8b1d89806 100644 --- a/src/main/java/org/atlasapi/equiv/handlers/EpisodeFilteringEquivalenceResultHandler.java +++ b/src/main/java/org/atlasapi/equiv/handlers/EpisodeFilteringEquivalenceResultHandler.java @@ -1,78 +1,79 @@ package org.atlasapi.equiv.handlers; import java.util.Map; import org.atlasapi.equiv.ContentRef; import org.atlasapi.equiv.EquivalenceSummary; import org.atlasapi.equiv.EquivalenceSummaryStore; import org.atlasapi.equiv.results.EquivalenceResult; import org.atlasapi.equiv.results.description.ReadableDescription; import org.atlasapi.equiv.results.description.ResultDescription; import org.atlasapi.equiv.results.scores.ScoredCandidate; import org.atlasapi.media.entity.Item; import org.atlasapi.media.entity.ParentRef; import org.atlasapi.media.entity.Publisher; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; public class EpisodeFilteringEquivalenceResultHandler implements EquivalenceResultHandler<Item> { private final EquivalenceResultHandler<Item> delegate; private final EquivalenceSummaryStore summaryStore; public EpisodeFilteringEquivalenceResultHandler(EquivalenceResultHandler<Item> delegate, EquivalenceSummaryStore summaryStore) { this.delegate = delegate; this.summaryStore = summaryStore; } @Override public void handle(EquivalenceResult<Item> result) { ReadableDescription desc = (ReadableDescription) result.description().startStage(String.format("Episode parent filter")); ParentRef container = result.subject().getContainer(); if (container == null) { desc.appendText("Item has no Container").finishStage(); + delegate.handle(result); return; } String containerUri = container.getUri(); Optional<EquivalenceSummary> possibleSummary = summaryStore.summariesForUris(ImmutableSet.of(containerUri)).get(containerUri); if (!possibleSummary.isPresent()) { desc.appendText("Item Container summary not found").finishStage(); return; } ImmutableMap<Publisher,ContentRef> equivalents = possibleSummary.get().getEquivalents(); Map<Publisher, ScoredCandidate<Item>> strongEquivalences = filter(result.strongEquivalences(), equivalents, desc); desc.finishStage(); delegate.handle(new EquivalenceResult<Item>(result.subject(), result.rawScores(), result.combinedEquivalences(), strongEquivalences, desc)); } private Map<Publisher, ScoredCandidate<Item>> filter(Map<Publisher, ScoredCandidate<Item>> strongItems, final Map<Publisher,ContentRef> containerEquivalents, final ResultDescription desc) { return ImmutableMap.copyOf(Maps.filterValues(strongItems, new Predicate<ScoredCandidate<Item>>() { @Override public boolean apply(ScoredCandidate<Item> scoredCandidate) { Item candidate = scoredCandidate.candidate(); ParentRef candidateContainer = candidate.getContainer(); if (candidateContainer == null) { return true; } String candidateContainerUri = candidateContainer.getUri(); ContentRef validContainer = containerEquivalents.get(candidate.getPublisher()); if (validContainer == null || validContainer.getCanonicalUri().equals(candidateContainerUri)) { return true; } desc.appendText("%s removed. Unacceptable container: %s", scoredCandidate, candidateContainerUri); return false; } })); } }
true
true
public void handle(EquivalenceResult<Item> result) { ReadableDescription desc = (ReadableDescription) result.description().startStage(String.format("Episode parent filter")); ParentRef container = result.subject().getContainer(); if (container == null) { desc.appendText("Item has no Container").finishStage(); return; } String containerUri = container.getUri(); Optional<EquivalenceSummary> possibleSummary = summaryStore.summariesForUris(ImmutableSet.of(containerUri)).get(containerUri); if (!possibleSummary.isPresent()) { desc.appendText("Item Container summary not found").finishStage(); return; } ImmutableMap<Publisher,ContentRef> equivalents = possibleSummary.get().getEquivalents(); Map<Publisher, ScoredCandidate<Item>> strongEquivalences = filter(result.strongEquivalences(), equivalents, desc); desc.finishStage(); delegate.handle(new EquivalenceResult<Item>(result.subject(), result.rawScores(), result.combinedEquivalences(), strongEquivalences, desc)); }
public void handle(EquivalenceResult<Item> result) { ReadableDescription desc = (ReadableDescription) result.description().startStage(String.format("Episode parent filter")); ParentRef container = result.subject().getContainer(); if (container == null) { desc.appendText("Item has no Container").finishStage(); delegate.handle(result); return; } String containerUri = container.getUri(); Optional<EquivalenceSummary> possibleSummary = summaryStore.summariesForUris(ImmutableSet.of(containerUri)).get(containerUri); if (!possibleSummary.isPresent()) { desc.appendText("Item Container summary not found").finishStage(); return; } ImmutableMap<Publisher,ContentRef> equivalents = possibleSummary.get().getEquivalents(); Map<Publisher, ScoredCandidate<Item>> strongEquivalences = filter(result.strongEquivalences(), equivalents, desc); desc.finishStage(); delegate.handle(new EquivalenceResult<Item>(result.subject(), result.rawScores(), result.combinedEquivalences(), strongEquivalences, desc)); }
diff --git a/src/java/com/eviware/soapui/impl/wsdl/monitor/jettyproxy/TunnelServlet.java b/src/java/com/eviware/soapui/impl/wsdl/monitor/jettyproxy/TunnelServlet.java index 2d0f75f44..6c50a000e 100644 --- a/src/java/com/eviware/soapui/impl/wsdl/monitor/jettyproxy/TunnelServlet.java +++ b/src/java/com/eviware/soapui/impl/wsdl/monitor/jettyproxy/TunnelServlet.java @@ -1,229 +1,232 @@ /* * soapUI, copyright (C) 2004-2009 eviware.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details at gnu.org. */ package com.eviware.soapui.impl.wsdl.monitor.jettyproxy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.mortbay.util.IO; import com.eviware.soapui.impl.wsdl.actions.monitor.SoapMonitorAction.LaunchForm; import com.eviware.soapui.impl.wsdl.monitor.JProxyServletWsdlMonitorMessageExchange; import com.eviware.soapui.impl.wsdl.monitor.SoapMonitor; import com.eviware.soapui.impl.wsdl.submit.transports.http.support.methods.ExtendedGetMethod; import com.eviware.soapui.impl.wsdl.submit.transports.http.support.methods.ExtendedPostMethod; import com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport; import com.eviware.soapui.impl.wsdl.support.http.ProxyUtils; import com.eviware.soapui.impl.wsdl.support.http.SoapUIHostConfiguration; import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext; import com.eviware.soapui.support.types.StringToStringMap; import com.eviware.soapui.support.xml.XmlUtils; public class TunnelServlet extends ProxyServlet { private String sslEndPoint; private int sslPort = 443; private String prot = "https://"; public TunnelServlet( SoapMonitor soapMonitor, String sslEndpoint ) { super( soapMonitor ); if( !sslEndpoint.startsWith( "https" ) ) { this.prot = "http://"; } int prefix = sslEndpoint.indexOf( "://" ); int c = sslEndpoint.indexOf( prefix, ':' ); if( c > 0 ) { this.sslPort = Integer.parseInt( sslEndpoint.substring( c + 1 ) ); this.sslEndPoint = sslEndpoint.substring( prefix, c ); } else { if( prefix > 0 ) this.sslEndPoint = sslEndpoint.substring( prefix + 3 ); } } @Override public void init( ServletConfig config ) throws ServletException { this.config = config; this.context = config.getServletContext(); client = HttpClientSupport.getHttpClient(); } public void service( ServletRequest request, ServletResponse response ) throws ServletException, IOException { monitor.fireOnRequest( request, response ); if( response.isCommitted() ) return; HttpMethodBase postMethod; // for this create ui server and port, properties. InetSocketAddress inetAddress = new InetSocketAddress( sslEndPoint, sslPort ); HttpServletRequest httpRequest = ( HttpServletRequest )request; if( httpRequest.getMethod().equals( "GET" ) ) postMethod = new ExtendedGetMethod(); else postMethod = new ExtendedPostMethod(); JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange( project ); capturedData.setRequestHost( httpRequest.getRemoteHost() ); capturedData.setRequestHeader( httpRequest ); capturedData.setTargetURL( this.prot + inetAddress.getHostName() ); CaptureInputStream capture = new CaptureInputStream( httpRequest.getInputStream() ); // copy headers Enumeration<?> headerNames = httpRequest.getHeaderNames(); while( headerNames.hasMoreElements() ) { String hdr = ( String )headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if( "host".equals( lhdr ) ) { Enumeration<?> vals = httpRequest.getHeaders( hdr ); while( vals.hasMoreElements() ) { String val = ( String )vals.nextElement(); if( val.startsWith( "127.0.0.1" ) ) { postMethod.addRequestHeader( hdr, sslEndPoint ); } } continue; } Enumeration<?> vals = httpRequest.getHeaders( hdr ); while( vals.hasMoreElements() ) { String val = ( String )vals.nextElement(); if( val != null ) { postMethod.addRequestHeader( hdr, val ); } } } if( postMethod instanceof ExtendedPostMethod ) ( ( ExtendedPostMethod )postMethod ).setRequestEntity( new InputStreamRequestEntity( capture, request .getContentType() ) ); HostConfiguration hostConfiguration = new HostConfiguration(); httpRequest.getProtocol(); hostConfiguration.getParams().setParameter( SoapUIHostConfiguration.SOAPUI_SSL_CONFIG, settings.getString( LaunchForm.SSLTUNNEL_KEYSTOREPATH, "" ) + " " + settings.getString( LaunchForm.SSLTUNNEL_KEYSTOREPASSWORD, "" ) ); hostConfiguration.setHost( new URI( this.prot + sslEndPoint, true ) ); hostConfiguration = ProxyUtils.initProxySettings( settings, httpState, hostConfiguration, prot + sslEndPoint, new DefaultPropertyExpansionContext( project ) ); - postMethod.setPath( sslEndPoint.substring( sslEndPoint.indexOf( "/" ), sslEndPoint.length() ) ); + if (sslEndPoint.indexOf( "/" ) < 0) + postMethod.setPath( sslEndPoint ); + else + postMethod.setPath( sslEndPoint.substring( sslEndPoint.indexOf( "/" ), sslEndPoint.length() ) ); monitor.fireBeforeProxy( request, response, postMethod, hostConfiguration ); if( settings.getBoolean( LaunchForm.SSLTUNNEL_REUSESTATE ) ) { if( httpState == null ) httpState = new HttpState(); client.executeMethod( hostConfiguration, postMethod, httpState ); } else { client.executeMethod( hostConfiguration, postMethod ); } capturedData.stopCapture(); capturedData.setRequest( capture.getCapturedData() ); capturedData.setRawResponseBody( postMethod.getResponseBody() ); capturedData.setResponseHeader( postMethod ); capturedData.setRawRequestData( getRequestToBytes( request.toString(), postMethod, capture ) ); capturedData.setRawResponseData( getResponseToBytes( response.toString(), postMethod, capturedData .getRawResponseBody() ) ); monitor.fireAfterProxy( request, response, postMethod, capturedData ); StringToStringMap responseHeaders = capturedData.getResponseHeaders(); // copy headers to response HttpServletResponse httpResponse = ( HttpServletResponse )response; for( String name : responseHeaders.keySet() ) { String header = responseHeaders.get( name ); httpResponse.addHeader( name, header ); } IO.copy( new ByteArrayInputStream( capturedData.getRawResponseBody() ), httpResponse.getOutputStream() ); postMethod.releaseConnection(); monitor.addMessageExchange( capturedData ); capturedData = null; } private byte[] getResponseToBytes( String footer, HttpMethodBase postMethod, byte[] res ) { String response = footer; Header[] headers = postMethod.getResponseHeaders(); for( Header header : headers ) { response += header.toString(); } response += "\n"; response += XmlUtils.prettyPrintXml( new String( res ) ); return response.getBytes(); } private byte[] getRequestToBytes( String footer, HttpMethodBase postMethod, CaptureInputStream capture ) { String request = footer; // Header[] headers = postMethod.getRequestHeaders(); // for (Header header : headers) // { // request += header.toString(); // } request += "\n"; request += XmlUtils.prettyPrintXml( new String( capture.getCapturedData() ) ); return request.getBytes(); } }
true
true
public void service( ServletRequest request, ServletResponse response ) throws ServletException, IOException { monitor.fireOnRequest( request, response ); if( response.isCommitted() ) return; HttpMethodBase postMethod; // for this create ui server and port, properties. InetSocketAddress inetAddress = new InetSocketAddress( sslEndPoint, sslPort ); HttpServletRequest httpRequest = ( HttpServletRequest )request; if( httpRequest.getMethod().equals( "GET" ) ) postMethod = new ExtendedGetMethod(); else postMethod = new ExtendedPostMethod(); JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange( project ); capturedData.setRequestHost( httpRequest.getRemoteHost() ); capturedData.setRequestHeader( httpRequest ); capturedData.setTargetURL( this.prot + inetAddress.getHostName() ); CaptureInputStream capture = new CaptureInputStream( httpRequest.getInputStream() ); // copy headers Enumeration<?> headerNames = httpRequest.getHeaderNames(); while( headerNames.hasMoreElements() ) { String hdr = ( String )headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if( "host".equals( lhdr ) ) { Enumeration<?> vals = httpRequest.getHeaders( hdr ); while( vals.hasMoreElements() ) { String val = ( String )vals.nextElement(); if( val.startsWith( "127.0.0.1" ) ) { postMethod.addRequestHeader( hdr, sslEndPoint ); } } continue; } Enumeration<?> vals = httpRequest.getHeaders( hdr ); while( vals.hasMoreElements() ) { String val = ( String )vals.nextElement(); if( val != null ) { postMethod.addRequestHeader( hdr, val ); } } } if( postMethod instanceof ExtendedPostMethod ) ( ( ExtendedPostMethod )postMethod ).setRequestEntity( new InputStreamRequestEntity( capture, request .getContentType() ) ); HostConfiguration hostConfiguration = new HostConfiguration(); httpRequest.getProtocol(); hostConfiguration.getParams().setParameter( SoapUIHostConfiguration.SOAPUI_SSL_CONFIG, settings.getString( LaunchForm.SSLTUNNEL_KEYSTOREPATH, "" ) + " " + settings.getString( LaunchForm.SSLTUNNEL_KEYSTOREPASSWORD, "" ) ); hostConfiguration.setHost( new URI( this.prot + sslEndPoint, true ) ); hostConfiguration = ProxyUtils.initProxySettings( settings, httpState, hostConfiguration, prot + sslEndPoint, new DefaultPropertyExpansionContext( project ) ); postMethod.setPath( sslEndPoint.substring( sslEndPoint.indexOf( "/" ), sslEndPoint.length() ) ); monitor.fireBeforeProxy( request, response, postMethod, hostConfiguration ); if( settings.getBoolean( LaunchForm.SSLTUNNEL_REUSESTATE ) ) { if( httpState == null ) httpState = new HttpState(); client.executeMethod( hostConfiguration, postMethod, httpState ); } else { client.executeMethod( hostConfiguration, postMethod ); } capturedData.stopCapture(); capturedData.setRequest( capture.getCapturedData() ); capturedData.setRawResponseBody( postMethod.getResponseBody() ); capturedData.setResponseHeader( postMethod ); capturedData.setRawRequestData( getRequestToBytes( request.toString(), postMethod, capture ) ); capturedData.setRawResponseData( getResponseToBytes( response.toString(), postMethod, capturedData .getRawResponseBody() ) ); monitor.fireAfterProxy( request, response, postMethod, capturedData ); StringToStringMap responseHeaders = capturedData.getResponseHeaders(); // copy headers to response HttpServletResponse httpResponse = ( HttpServletResponse )response; for( String name : responseHeaders.keySet() ) { String header = responseHeaders.get( name ); httpResponse.addHeader( name, header ); } IO.copy( new ByteArrayInputStream( capturedData.getRawResponseBody() ), httpResponse.getOutputStream() ); postMethod.releaseConnection(); monitor.addMessageExchange( capturedData ); capturedData = null; }
public void service( ServletRequest request, ServletResponse response ) throws ServletException, IOException { monitor.fireOnRequest( request, response ); if( response.isCommitted() ) return; HttpMethodBase postMethod; // for this create ui server and port, properties. InetSocketAddress inetAddress = new InetSocketAddress( sslEndPoint, sslPort ); HttpServletRequest httpRequest = ( HttpServletRequest )request; if( httpRequest.getMethod().equals( "GET" ) ) postMethod = new ExtendedGetMethod(); else postMethod = new ExtendedPostMethod(); JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange( project ); capturedData.setRequestHost( httpRequest.getRemoteHost() ); capturedData.setRequestHeader( httpRequest ); capturedData.setTargetURL( this.prot + inetAddress.getHostName() ); CaptureInputStream capture = new CaptureInputStream( httpRequest.getInputStream() ); // copy headers Enumeration<?> headerNames = httpRequest.getHeaderNames(); while( headerNames.hasMoreElements() ) { String hdr = ( String )headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if( "host".equals( lhdr ) ) { Enumeration<?> vals = httpRequest.getHeaders( hdr ); while( vals.hasMoreElements() ) { String val = ( String )vals.nextElement(); if( val.startsWith( "127.0.0.1" ) ) { postMethod.addRequestHeader( hdr, sslEndPoint ); } } continue; } Enumeration<?> vals = httpRequest.getHeaders( hdr ); while( vals.hasMoreElements() ) { String val = ( String )vals.nextElement(); if( val != null ) { postMethod.addRequestHeader( hdr, val ); } } } if( postMethod instanceof ExtendedPostMethod ) ( ( ExtendedPostMethod )postMethod ).setRequestEntity( new InputStreamRequestEntity( capture, request .getContentType() ) ); HostConfiguration hostConfiguration = new HostConfiguration(); httpRequest.getProtocol(); hostConfiguration.getParams().setParameter( SoapUIHostConfiguration.SOAPUI_SSL_CONFIG, settings.getString( LaunchForm.SSLTUNNEL_KEYSTOREPATH, "" ) + " " + settings.getString( LaunchForm.SSLTUNNEL_KEYSTOREPASSWORD, "" ) ); hostConfiguration.setHost( new URI( this.prot + sslEndPoint, true ) ); hostConfiguration = ProxyUtils.initProxySettings( settings, httpState, hostConfiguration, prot + sslEndPoint, new DefaultPropertyExpansionContext( project ) ); if (sslEndPoint.indexOf( "/" ) < 0) postMethod.setPath( sslEndPoint ); else postMethod.setPath( sslEndPoint.substring( sslEndPoint.indexOf( "/" ), sslEndPoint.length() ) ); monitor.fireBeforeProxy( request, response, postMethod, hostConfiguration ); if( settings.getBoolean( LaunchForm.SSLTUNNEL_REUSESTATE ) ) { if( httpState == null ) httpState = new HttpState(); client.executeMethod( hostConfiguration, postMethod, httpState ); } else { client.executeMethod( hostConfiguration, postMethod ); } capturedData.stopCapture(); capturedData.setRequest( capture.getCapturedData() ); capturedData.setRawResponseBody( postMethod.getResponseBody() ); capturedData.setResponseHeader( postMethod ); capturedData.setRawRequestData( getRequestToBytes( request.toString(), postMethod, capture ) ); capturedData.setRawResponseData( getResponseToBytes( response.toString(), postMethod, capturedData .getRawResponseBody() ) ); monitor.fireAfterProxy( request, response, postMethod, capturedData ); StringToStringMap responseHeaders = capturedData.getResponseHeaders(); // copy headers to response HttpServletResponse httpResponse = ( HttpServletResponse )response; for( String name : responseHeaders.keySet() ) { String header = responseHeaders.get( name ); httpResponse.addHeader( name, header ); } IO.copy( new ByteArrayInputStream( capturedData.getRawResponseBody() ), httpResponse.getOutputStream() ); postMethod.releaseConnection(); monitor.addMessageExchange( capturedData ); capturedData = null; }
diff --git a/DVST/src/com/dhbw/dvst/model/Spiel.java b/DVST/src/com/dhbw/dvst/model/Spiel.java index 4c0fb5b..57f3939 100644 --- a/DVST/src/com/dhbw/dvst/model/Spiel.java +++ b/DVST/src/com/dhbw/dvst/model/Spiel.java @@ -1,140 +1,140 @@ package com.dhbw.dvst.model; import java.util.ArrayList; public class Spiel{ /** * Spielmodi */ public static final int modus_einspieler = 0; public static final int modus_mehrspieler_server = 1; public static final int modus_mehrspieler_client = 2; private ArrayList<Spielfigur> alleSpielfiguren; private ArrayList<Spieler> alleSpieler; private int spielmodus; private Spielbrett spielbrett; private Spielplatte platte_aktiv; private ArrayList<Spielkarte> kartenstapel; /** * Konstruktor */ public Spiel() { alleSpielfiguren = new ArrayList<Spielfigur>(); initialisiereSpielfiguren(); alleSpieler = new ArrayList<Spieler>(); } /** * Spielfiguren initialisieren */ public void initialisiereSpielfiguren() { this.alleSpielfiguren.add(new Spielfigur("motorrad", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "gelb", "")); - this.alleSpielfiguren.add(new Spielfigur("motorrad", "gruen", "")); - this.alleSpielfiguren.add(new Spielfigur("auto", "gruen", "")); - this.alleSpielfiguren.add(new Spielfigur("bus", "gruen", "")); + this.alleSpielfiguren.add(new Spielfigur("motorrad", "grün", "")); + this.alleSpielfiguren.add(new Spielfigur("auto", "grün", "")); + this.alleSpielfiguren.add(new Spielfigur("bus", "grün", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "blau", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "blau", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "blau", "")); } /** * Spieler zum Spiel hinzufuegen * @param name * @param spielfigur */ public void spielerHinzufuegen(String name, Spielfigur spielfigur) { Spieler neuerSpieler = new Spieler(name, spielfigur); this.alleSpieler.add(neuerSpieler); spielfigur.setVergeben(true); } /** * Spielfigur als bereits an einen Spieler vergeben markieren * @param neuerSpieler */ // private void setFigurVergeben(Spieler neuerSpieler) { // //foreach // for (Spielfigur s : this.alleSpielfiguren) { // if(s.getFarbe().equals(neuerSpieler.getSpielfigur().getFarbe())) { // if(s.getForm().equals(neuerSpieler.getSpielfigur().getForm())) { // s.setVergeben(true); // } // } // } // } /** * Spieler loeschen und Spielfigur wieder freigeben * @param spieler */ public void spielerLoeschen(Spieler spieler) { spieler.getSpielfigur().setVergeben(false); this.alleSpieler.remove(spieler); } /* * Getter und Setter Methoden */ /** * @return the spielmodus */ public int getSpielmodus() { return spielmodus; } /** * @param spielmodus the spielmodus to set */ public void setSpielmodus(int spielmodus) { this.spielmodus = spielmodus; } public ArrayList<Spielfigur> getAlleSpielfiguren() { return alleSpielfiguren; } public void setAlleSpielfiguren(ArrayList<Spielfigur> alleSpielfiguren) { this.alleSpielfiguren = alleSpielfiguren; } public ArrayList<Spieler> getAlleSpieler() { return alleSpieler; } public void setAlleSpieler(ArrayList<Spieler> alleSpieler) { this.alleSpieler = alleSpieler; } public Spielbrett getSpielbrett() { return spielbrett; } public void setSpielbrett(Spielbrett spielbrett) { this.spielbrett = spielbrett; } public Spielplatte getPlatte_aktiv() { return platte_aktiv; } public void setPlatte_aktiv(Spielplatte platte_aktiv) { this.platte_aktiv = platte_aktiv; } public ArrayList<Spielkarte> getKartenstapel() { return kartenstapel; } public void setKartenstapel(ArrayList<Spielkarte> kartenstapel) { this.kartenstapel = kartenstapel; } }
true
true
public void initialisiereSpielfiguren() { this.alleSpielfiguren.add(new Spielfigur("motorrad", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "gruen", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "gruen", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "gruen", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "blau", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "blau", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "blau", "")); }
public void initialisiereSpielfiguren() { this.alleSpielfiguren.add(new Spielfigur("motorrad", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "rot", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "gelb", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "grün", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "grün", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "grün", "")); this.alleSpielfiguren.add(new Spielfigur("motorrad", "blau", "")); this.alleSpielfiguren.add(new Spielfigur("auto", "blau", "")); this.alleSpielfiguren.add(new Spielfigur("bus", "blau", "")); }
diff --git a/hyracks/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java b/hyracks/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java index f2c296d2d..c1b467485 100644 --- a/hyracks/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java +++ b/hyracks/hyracks-control-common/src/main/java/edu/uci/ics/hyracks/control/common/application/ApplicationContext.java @@ -1,181 +1,183 @@ /* * Copyright 2009-2010 by The Regents of the University of California * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * you may obtain a copy of the License from * * 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 edu.uci.ics.hyracks.control.common.application; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import edu.uci.ics.hyracks.api.application.IApplicationContext; import edu.uci.ics.hyracks.api.application.IBootstrap; import edu.uci.ics.hyracks.control.common.context.ServerContext; public class ApplicationContext implements IApplicationContext { private static final String APPLICATION_ROOT = "applications"; private static final String CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY = "cc.bootstrap.class"; private static final String NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY = "nc.bootstrap.class"; private ServerContext serverCtx; private final String appName; private final File applicationRootDir; private ClassLoader classLoader; private ApplicationStatus status; private Properties deploymentDescriptor; private IBootstrap bootstrap; public ApplicationContext(ServerContext serverCtx, String appName) throws IOException { this.serverCtx = serverCtx; this.appName = appName; this.applicationRootDir = new File(new File(serverCtx.getBaseDir(), APPLICATION_ROOT), appName); status = ApplicationStatus.CREATED; FileUtils.deleteDirectory(applicationRootDir); applicationRootDir.mkdirs(); } public String getApplicationName() { return appName; } public void initialize() throws Exception { if (status != ApplicationStatus.CREATED) { throw new IllegalStateException(); } if (expandArchive()) { File expandedFolder = getExpandedFolder(); List<URL> urls = new ArrayList<URL>(); findJarFiles(expandedFolder, urls); classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); deploymentDescriptor = parseDeploymentDescriptor(); String bootstrapClass = null; switch (serverCtx.getServerType()) { case CLUSTER_CONTROLLER: { bootstrapClass = deploymentDescriptor.getProperty(CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY); + break; } case NODE_CONTROLLER: { bootstrapClass = deploymentDescriptor.getProperty(NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY); + break; } } if (bootstrapClass != null) { bootstrap = (IBootstrap) classLoader.loadClass(bootstrapClass).newInstance(); bootstrap.setApplicationContext(this); bootstrap.start(); } } else { classLoader = getClass().getClassLoader(); } status = ApplicationStatus.INITIALIZED; } private void findJarFiles(File dir, List<URL> urls) throws MalformedURLException { for (File f : dir.listFiles()) { if (f.isDirectory()) { findJarFiles(f, urls); } else if (f.getName().endsWith(".jar") || f.getName().endsWith(".zip")) { urls.add(f.toURI().toURL()); } } } private Properties parseDeploymentDescriptor() throws IOException { InputStream in = classLoader.getResourceAsStream("hyracks-deployment.properties"); Properties props = new Properties(); if (in != null) { try { props.load(in); } finally { in.close(); } } return props; } private boolean expandArchive() throws IOException { File archiveFile = getArchiveFile(); if (archiveFile.exists()) { File expandedFolder = getExpandedFolder(); FileUtils.deleteDirectory(expandedFolder); ZipFile zf = new ZipFile(archiveFile); for (Enumeration<? extends ZipEntry> i = zf.entries(); i.hasMoreElements();) { ZipEntry ze = i.nextElement(); String name = ze.getName(); if (name.endsWith("/")) { continue; } InputStream is = zf.getInputStream(ze); OutputStream os = FileUtils.openOutputStream(new File(expandedFolder, name)); try { IOUtils.copyLarge(is, os); } finally { os.close(); is.close(); } } return true; } return false; } private File getExpandedFolder() { return new File(applicationRootDir, "expanded"); } public void deinitialize() throws Exception { status = ApplicationStatus.DEINITIALIZED; if (bootstrap != null) { bootstrap.stop(); } File expandedFolder = getExpandedFolder(); FileUtils.deleteDirectory(expandedFolder); } public Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ClassLoaderObjectInputStream(new ByteArrayInputStream(bytes), classLoader); return ois.readObject(); } public OutputStream getHarOutputStream() throws IOException { return new FileOutputStream(getArchiveFile()); } private File getArchiveFile() { return new File(applicationRootDir, "application.har"); } public InputStream getHarInputStream() throws IOException { return new FileInputStream(getArchiveFile()); } public boolean containsHar() { return getArchiveFile().exists(); } }
false
true
public void initialize() throws Exception { if (status != ApplicationStatus.CREATED) { throw new IllegalStateException(); } if (expandArchive()) { File expandedFolder = getExpandedFolder(); List<URL> urls = new ArrayList<URL>(); findJarFiles(expandedFolder, urls); classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); deploymentDescriptor = parseDeploymentDescriptor(); String bootstrapClass = null; switch (serverCtx.getServerType()) { case CLUSTER_CONTROLLER: { bootstrapClass = deploymentDescriptor.getProperty(CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY); } case NODE_CONTROLLER: { bootstrapClass = deploymentDescriptor.getProperty(NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY); } } if (bootstrapClass != null) { bootstrap = (IBootstrap) classLoader.loadClass(bootstrapClass).newInstance(); bootstrap.setApplicationContext(this); bootstrap.start(); } } else { classLoader = getClass().getClassLoader(); } status = ApplicationStatus.INITIALIZED; }
public void initialize() throws Exception { if (status != ApplicationStatus.CREATED) { throw new IllegalStateException(); } if (expandArchive()) { File expandedFolder = getExpandedFolder(); List<URL> urls = new ArrayList<URL>(); findJarFiles(expandedFolder, urls); classLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); deploymentDescriptor = parseDeploymentDescriptor(); String bootstrapClass = null; switch (serverCtx.getServerType()) { case CLUSTER_CONTROLLER: { bootstrapClass = deploymentDescriptor.getProperty(CLUSTER_CONTROLLER_BOOTSTRAP_CLASS_KEY); break; } case NODE_CONTROLLER: { bootstrapClass = deploymentDescriptor.getProperty(NODE_CONTROLLER_BOOTSTRAP_CLASS_KEY); break; } } if (bootstrapClass != null) { bootstrap = (IBootstrap) classLoader.loadClass(bootstrapClass).newInstance(); bootstrap.setApplicationContext(this); bootstrap.start(); } } else { classLoader = getClass().getClassLoader(); } status = ApplicationStatus.INITIALIZED; }
diff --git a/SongScheduler/src/model/InitialDB.java b/SongScheduler/src/model/InitialDB.java index 724519a..27a86a0 100644 --- a/SongScheduler/src/model/InitialDB.java +++ b/SongScheduler/src/model/InitialDB.java @@ -1,52 +1,53 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package model; import java.sql.*; import java.io.*; /** * * @author liufeng */ public class InitialDB { /** * Just trivial initial stuff. * not finished yet. */ private static void initialDB() { try { Class.forName("java.sqlite.JDBC"); Connection connection = DriverManager.getConnection("jdbc.sqlite:/Users/liufeng/prog/ss/song.db"); Statement statement = connection.createStatement(); statement.executeUpdate("create table songlist (title, performer, recordingTitle, recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority);"); BufferedReader in = new BufferedReader(new FileReader("library.txt")); String line = in.readLine(); while (line != null) { String[] token = line.split(";"); String title = token[0]; String performer = token[1]; String recordingTitle = token[2]; String recordingType = token[3]; String year = token[4]; String length = token[5] + ":" + token[6]; int popularity = Integer.parseInt(token[7]); int playCount = Integer.parseInt(token[8]); Time addedTime = new Time().getCurrentTime(); Time lastPlayed = new Time(0, 0, 0, 0, 0, 0); double priority = 0; //statement.executeUpdate("insert into songlist (title, performer, recordingTitle, recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority) values (\"" + title + "\"" + ", \"" + performer + "\", \"" + recordingTitle + "\"" , recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority + "\");";"); + line = in.readLine(); } connection.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
true
private static void initialDB() { try { Class.forName("java.sqlite.JDBC"); Connection connection = DriverManager.getConnection("jdbc.sqlite:/Users/liufeng/prog/ss/song.db"); Statement statement = connection.createStatement(); statement.executeUpdate("create table songlist (title, performer, recordingTitle, recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority);"); BufferedReader in = new BufferedReader(new FileReader("library.txt")); String line = in.readLine(); while (line != null) { String[] token = line.split(";"); String title = token[0]; String performer = token[1]; String recordingTitle = token[2]; String recordingType = token[3]; String year = token[4]; String length = token[5] + ":" + token[6]; int popularity = Integer.parseInt(token[7]); int playCount = Integer.parseInt(token[8]); Time addedTime = new Time().getCurrentTime(); Time lastPlayed = new Time(0, 0, 0, 0, 0, 0); double priority = 0; //statement.executeUpdate("insert into songlist (title, performer, recordingTitle, recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority) values (\"" + title + "\"" + ", \"" + performer + "\", \"" + recordingTitle + "\"" , recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority + "\");";"); } connection.close(); } catch (Exception e) { e.printStackTrace(); } }
private static void initialDB() { try { Class.forName("java.sqlite.JDBC"); Connection connection = DriverManager.getConnection("jdbc.sqlite:/Users/liufeng/prog/ss/song.db"); Statement statement = connection.createStatement(); statement.executeUpdate("create table songlist (title, performer, recordingTitle, recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority);"); BufferedReader in = new BufferedReader(new FileReader("library.txt")); String line = in.readLine(); while (line != null) { String[] token = line.split(";"); String title = token[0]; String performer = token[1]; String recordingTitle = token[2]; String recordingType = token[3]; String year = token[4]; String length = token[5] + ":" + token[6]; int popularity = Integer.parseInt(token[7]); int playCount = Integer.parseInt(token[8]); Time addedTime = new Time().getCurrentTime(); Time lastPlayed = new Time(0, 0, 0, 0, 0, 0); double priority = 0; //statement.executeUpdate("insert into songlist (title, performer, recordingTitle, recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority) values (\"" + title + "\"" + ", \"" + performer + "\", \"" + recordingTitle + "\"" , recordingType, year, length, popularity, playCount, addedTime, lastPlayed, priority + "\");";"); line = in.readLine(); } connection.close(); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintVisitor.java b/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintVisitor.java index 9ceeac73..6b367b39 100644 --- a/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintVisitor.java +++ b/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintVisitor.java @@ -1,765 +1,768 @@ /* License: GPL. Copyright 2007 by Immanuel Scholz and others */ package org.openstreetmap.josm.data.osm.visitor.paint; /* To enable debugging or profiling remove the double / signs */ import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.data.Bounds; import org.openstreetmap.josm.data.coor.EastNorth; import org.openstreetmap.josm.data.coor.LatLon; import org.openstreetmap.josm.data.osm.BBox; import org.openstreetmap.josm.data.osm.DataSet; import org.openstreetmap.josm.data.osm.Node; import org.openstreetmap.josm.data.osm.OsmPrimitive; import org.openstreetmap.josm.data.osm.OsmUtils; import org.openstreetmap.josm.data.osm.Relation; import org.openstreetmap.josm.data.osm.RelationMember; import org.openstreetmap.josm.data.osm.Way; import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor; import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon; import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData; import org.openstreetmap.josm.gui.DefaultNameFormatter; import org.openstreetmap.josm.gui.NavigatableComponent; import org.openstreetmap.josm.gui.mappaint.AreaElemStyle; import org.openstreetmap.josm.gui.mappaint.ElemStyle; import org.openstreetmap.josm.gui.mappaint.ElemStyles; import org.openstreetmap.josm.gui.mappaint.IconElemStyle; import org.openstreetmap.josm.gui.mappaint.LineElemStyle; import org.openstreetmap.josm.gui.mappaint.MapPaintStyles; import org.openstreetmap.josm.gui.mappaint.SimpleNodeElemStyle; public class MapPaintVisitor implements PaintVisitor { private Graphics2D g; private NavigatableComponent nc; private boolean zoomLevelDisplay; private boolean drawMultipolygon; private boolean drawRestriction; private boolean leftHandTraffic; private ElemStyles.StyleSet styles; private double circum; private double dist; private boolean useStyleCache; private static int paintid = 0; private EastNorth minEN; private EastNorth maxEN; private MapPainter painter; private MapPaintSettings paintSettings; private boolean inactive; protected boolean isZoomOk(ElemStyle e) { if (!zoomLevelDisplay) /* show everything if the user wishes so */ return true; if(e == null) /* the default for things that don't have a rule (show, if scale is smaller than 1500m) */ return (circum < 1500); return !(circum >= e.maxScale || circum < e.minScale); } public ElemStyle getPrimitiveStyle(OsmPrimitive osm) { if(!useStyleCache) return ((styles != null) ? styles.get(osm) : null); if(osm.mappaintStyle == null && styles != null) { osm.mappaintStyle = styles.get(osm); if(osm instanceof Way) { ((Way)osm).isMappaintArea = styles.isArea(osm); } } if (osm.mappaintStyle == null && osm instanceof Node) { osm.mappaintStyle = SimpleNodeElemStyle.INSTANCE; } if (osm.mappaintStyle == null && osm instanceof Way) { osm.mappaintStyle = LineElemStyle.UNTAGGED_WAY; } return osm.mappaintStyle; } public IconElemStyle getPrimitiveNodeStyle(OsmPrimitive osm) { if(!useStyleCache) return (styles != null) ? styles.getIcon(osm) : null; if(osm.mappaintStyle == null && styles != null) { osm.mappaintStyle = styles.getIcon(osm); } return (IconElemStyle)osm.mappaintStyle; } public boolean isPrimitiveArea(Way osm) { if(!useStyleCache) return styles.isArea(osm); if(osm.mappaintStyle == null && styles != null) { osm.mappaintStyle = styles.get(osm); osm.isMappaintArea = styles.isArea(osm); } return osm.isMappaintArea; } public void drawNode(Node n) { /* check, if the node is visible at all */ if((n.getEastNorth().east() > maxEN.east() ) || (n.getEastNorth().north() > maxEN.north()) || (n.getEastNorth().east() < minEN.east() ) || (n.getEastNorth().north() < minEN.north())) return; ElemStyle nodeStyle = getPrimitiveStyle(n); if (isZoomOk(nodeStyle)) { nodeStyle.paintPrimitive(n, paintSettings, painter, n.isSelected()); } } public void drawWay(Way w, int fillAreas) { if(w.getNodesCount() < 2) return; if (w.hasIncompleteNodes()) return; /* check, if the way is visible at all */ double minx = 10000; double maxx = -10000; double miny = 10000; double maxy = -10000; for (Node n : w.getNodes()) { if(n.getEastNorth().east() > maxx) { maxx = n.getEastNorth().east(); } if(n.getEastNorth().north() > maxy) { maxy = n.getEastNorth().north(); } if(n.getEastNorth().east() < minx) { minx = n.getEastNorth().east(); } if(n.getEastNorth().north() < miny) { miny = n.getEastNorth().north(); } } if ((minx > maxEN.east()) || (miny > maxEN.north()) || (maxx < minEN.east()) || (maxy < minEN.north())) return; ElemStyle wayStyle = getPrimitiveStyle(w); if(!isZoomOk(wayStyle)) return; if (wayStyle == null) { wayStyle = LineElemStyle.UNTAGGED_WAY; } if(wayStyle instanceof LineElemStyle) { wayStyle.paintPrimitive(w, paintSettings, painter, data.isSelected(w)); } else if (wayStyle instanceof AreaElemStyle) { AreaElemStyle areaStyle = (AreaElemStyle) wayStyle; /* way with area style */ if (fillAreas > dist) { painter.drawArea(getPolygon(w), (data.isSelected(w) ? paintSettings.getSelectedColor() : areaStyle.color), painter.getWayName(w)); if(!w.isClosed()) { putError(w, tr("Area style way is not closed."), true); } } areaStyle.getLineStyle().paintPrimitive(w, paintSettings, painter, data.isSelected(w)); } } public void drawSelectedMember(OsmPrimitive osm, ElemStyle style, boolean area, boolean areaselected) { if(osm instanceof Way) { if(style instanceof AreaElemStyle) { Way way = (Way)osm; AreaElemStyle areaStyle = (AreaElemStyle)style; areaStyle.getLineStyle().paintPrimitive(way, paintSettings, painter, true); if(area) { painter.drawArea(getPolygon(way), (areaselected ? paintSettings.getSelectedColor() : areaStyle.color), painter.getWayName(way)); } } else { style.paintPrimitive(osm, paintSettings, painter, true); } } else if(osm instanceof Node) { if(isZoomOk(style)) { style.paintPrimitive(osm, paintSettings, painter, true); } } osm.mappaintDrawnCode = paintid; } public void paintUnselectedRelation(Relation r) { if (drawMultipolygon && "multipolygon".equals(r.get("type"))) { if(drawMultipolygon(r)) return; } else if (drawRestriction && "restriction".equals(r.get("type"))) { drawRestriction(r); } if(data.isSelected(r)) /* draw ways*/ { for (RelationMember m : r.getMembers()) { if (m.isWay() && m.getMember().isDrawable()) { drawSelectedMember(m.getMember(), styles != null ? getPrimitiveStyle(m.getMember()) : null, true, true); } } } } public void drawRestriction(Relation r) { Way fromWay = null; Way toWay = null; OsmPrimitive via = null; /* find the "from", "via" and "to" elements */ for (RelationMember m : r.getMembers()) { if(m.getMember().isIncomplete()) return; else { if(m.isWay()) { Way w = m.getWay(); if(w.getNodesCount() < 2) { continue; } if("from".equals(m.getRole())) { if(fromWay != null) { putError(r, tr("More than one \"from\" way found."), true); } else { fromWay = w; } } else if("to".equals(m.getRole())) { if(toWay != null) { putError(r, tr("More than one \"to\" way found."), true); } else { toWay = w; } } else if("via".equals(m.getRole())) { if(via != null) { putError(r, tr("More than one \"via\" found."), true); } else { via = w; } } else { putError(r, tr("Unknown role ''{0}''.", m.getRole()), true); } } else if(m.isNode()) { Node n = m.getNode(); if("via".equals(m.getRole())) { if(via != null) { putError(r, tr("More than one \"via\" found."), true); } else { via = n; } } else { putError(r, tr("Unknown role ''{0}''.", m.getRole()), true); } } else { putError(r, tr("Unknown member type for ''{0}''.", m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true); } } } if (fromWay == null) { putError(r, tr("No \"from\" way found."), true); return; } if (toWay == null) { putError(r, tr("No \"to\" way found."), true); return; } if (via == null) { putError(r, tr("No \"via\" node or way found."), true); return; } Node viaNode; if(via instanceof Node) { viaNode = (Node) via; if(!fromWay.isFirstLastNode(viaNode)) { putError(r, tr("The \"from\" way does not start or end at a \"via\" node."), true); return; } if(!toWay.isFirstLastNode(viaNode)) { putError(r, tr("The \"to\" way does not start or end at a \"via\" node."), true); } } else { Way viaWay = (Way) via; Node firstNode = viaWay.firstNode(); Node lastNode = viaWay.lastNode(); - boolean onewayvia = false; + Boolean onewayvia = false; String onewayviastr = viaWay.get("oneway"); if(onewayviastr != null) { if("-1".equals(onewayviastr)) { onewayvia = true; Node tmp = firstNode; firstNode = lastNode; lastNode = tmp; } else { onewayvia = OsmUtils.getOsmBoolean(onewayviastr); + if (onewayvia == null) { + onewayvia = false; + } } } if(fromWay.isFirstLastNode(firstNode)) { viaNode = firstNode; } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) { viaNode = lastNode; } else { putError(r, tr("The \"from\" way does not start or end at the \"via\" way."), true); return; } if(!toWay.isFirstLastNode(viaNode == firstNode ? lastNode : firstNode)) { putError(r, tr("The \"to\" way does not start or end at the \"via\" way."), true); } } /* find the "direct" nodes before the via node */ Node fromNode = null; if(fromWay.firstNode() == via) { fromNode = fromWay.getNode(1); } else { fromNode = fromWay.getNode(fromWay.getNodesCount()-2); } Point pFrom = nc.getPoint(fromNode); Point pVia = nc.getPoint(viaNode); /* starting from via, go back the "from" way a few pixels (calculate the vector vx/vy with the specified length and the direction away from the "via" node along the first segment of the "from" way) */ double distanceFromVia=14; double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x); double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y); double fromAngle; if(dx == 0.0) { fromAngle = Math.PI/2; } else { fromAngle = Math.atan(dy / dx); } double fromAngleDeg = Math.toDegrees(fromAngle); double vx = distanceFromVia * Math.cos(fromAngle); double vy = distanceFromVia * Math.sin(fromAngle); if(pFrom.x < pVia.x) { vx = -vx; } if(pFrom.y < pVia.y) { vy = -vy; } /* go a few pixels away from the way (in a right angle) (calculate the vx2/vy2 vector with the specified length and the direction 90degrees away from the first segment of the "from" way) */ double distanceFromWay=10; double vx2 = 0; double vy2 = 0; double iconAngle = 0; if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90)); } else { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90)); } iconAngle = 270+fromAngleDeg; } if(pFrom.x < pVia.x && pFrom.y >= pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg)); } else { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180)); } iconAngle = 90-fromAngleDeg; } if(pFrom.x < pVia.x && pFrom.y < pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90)); } else { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90)); } iconAngle = 90+fromAngleDeg; } if(pFrom.x >= pVia.x && pFrom.y < pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180)); } else { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg)); } iconAngle = 270-fromAngleDeg; } IconElemStyle nodeStyle = getPrimitiveNodeStyle(r); if (nodeStyle == null) { putError(r, tr("Style for restriction {0} not found.", r.get("restriction")), true); return; } painter.drawRestriction(inactive || r.isDisabled() ? nodeStyle.getDisabledIcon() : nodeStyle.icon, pVia, vx, vx2, vy, vy2, iconAngle, data.isSelected(r)); } public boolean drawMultipolygon(Relation r) { boolean drawn = false; Multipolygon multipolygon = new Multipolygon(nc); multipolygon.load(r); ElemStyle wayStyle = getPrimitiveStyle(r); // If area style was not found for relation then use style of ways if(styles != null && !(wayStyle instanceof AreaElemStyle)) { for (Way w : multipolygon.getOuterWays()) { wayStyle = styles.getArea(w); if(wayStyle != null) { break; } } r.mappaintStyle = wayStyle; } if (wayStyle instanceof AreaElemStyle) { boolean zoomok = isZoomOk(wayStyle); boolean visible = false; drawn = true; if(zoomok && !multipolygon.getOuterWays().isEmpty()) { AreaElemStyle areaStyle = (AreaElemStyle)wayStyle; for (PolyData pd : multipolygon.getCombinedPolygons()) { Polygon p = pd.get(); if(!isPolygonVisible(p)) { continue; } boolean selected = pd.selected || data.isSelected(r); painter.drawArea(p, selected ? paintSettings.getSelectedColor() : areaStyle.color, null); visible = true; } } if(!visible) return drawn; for (Way wInner : multipolygon.getInnerWays()) { ElemStyle innerStyle = getPrimitiveStyle(wInner); if(innerStyle == null) { if (data.isSelected(wInner)) { continue; } if(zoomok && (wInner.mappaintDrawnCode != paintid || multipolygon.getOuterWays().isEmpty())) { ((AreaElemStyle)wayStyle).getLineStyle().paintPrimitive(wInner, paintSettings, painter, (data.isSelected(wInner) || data.isSelected(r))); } wInner.mappaintDrawnCode = paintid; } else { if(data.isSelected(r)) { drawSelectedMember(wInner, innerStyle, !wayStyle.equals(innerStyle), data.isSelected(wInner)); } if(wayStyle.equals(innerStyle)) { putError(r, tr("Style for inner way ''{0}'' equals multipolygon.", wInner.getDisplayName(DefaultNameFormatter.getInstance())), false); if(!data.isSelected(r)) { wInner.mappaintDrawnAreaCode = paintid; } } } } for (Way wOuter : multipolygon.getOuterWays()) { ElemStyle outerStyle = getPrimitiveStyle(wOuter); if(outerStyle == null) { // Selected ways are drawn at the very end if (data.isSelected(wOuter)) { continue; } if(zoomok) { ((AreaElemStyle)wayStyle).getLineStyle().paintPrimitive(wOuter, paintSettings, painter, (data.isSelected(wOuter) || data.isSelected(r))); } wOuter.mappaintDrawnCode = paintid; } else { if(outerStyle instanceof AreaElemStyle && !wayStyle.equals(outerStyle)) { putError(r, tr("Style for outer way ''{0}'' mismatches.", wOuter.getDisplayName(DefaultNameFormatter.getInstance())), true); } if(data.isSelected(r)) { drawSelectedMember(wOuter, outerStyle, false, false); } else if(outerStyle instanceof AreaElemStyle) { wOuter.mappaintDrawnAreaCode = paintid; } } } } return drawn; } protected boolean isPolygonVisible(Polygon polygon) { Rectangle bounds = polygon.getBounds(); if (bounds.width == 0 && bounds.height == 0) return false; if (bounds.x > nc.getWidth()) return false; if (bounds.y > nc.getHeight()) return false; if (bounds.x + bounds.width < 0) return false; if (bounds.y + bounds.height < 0) return false; return true; } protected Polygon getPolygon(Way w) { Polygon polygon = new Polygon(); for (Node n : w.getNodes()) { Point p = nc.getPoint(n); polygon.addPoint(p.x,p.y); } return polygon; } protected Point2D getCentroid(Polygon p) { double cx = 0.0, cy = 0.0, a = 0.0; // usually requires points[0] == points[npoints] and can then use i+1 instead of j. // Faked it slowly using j. If this is really gets used, this should be fixed. for (int i = 0; i < p.npoints; i++) { int j = i+1 == p.npoints ? 0 : i+1; a += (p.xpoints[i] * p.ypoints[j]) - (p.ypoints[i] * p.xpoints[j]); cx += (p.xpoints[i] + p.xpoints[j]) * (p.xpoints[i] * p.ypoints[j] - p.ypoints[i] * p.xpoints[j]); cy += (p.ypoints[i] + p.ypoints[j]) * (p.xpoints[i] * p.ypoints[j] - p.ypoints[i] * p.xpoints[j]); } return new Point2D.Double(cx / (3.0*a), cy / (3.0*a)); } protected double getArea(Polygon p) { double sum = 0.0; // usually requires points[0] == points[npoints] and can then use i+1 instead of j. // Faked it slowly using j. If this is really gets used, this should be fixed. for (int i = 0; i < p.npoints; i++) { int j = i+1 == p.npoints ? 0 : i+1; sum = sum + (p.xpoints[i] * p.ypoints[j]) - (p.ypoints[i] * p.xpoints[j]); } return Math.abs(sum/2.0); } DataSet data; <T extends OsmPrimitive> Collection<T> selectedLast(final DataSet data, Collection <T> prims) { ArrayList<T> sorted = new ArrayList<T>(prims); Collections.sort(sorted, new Comparator<T>() { public int compare(T o1, T o2) { boolean s1 = data.isSelected(o1); boolean s2 = data.isSelected(o2); if (s1 && !s2) return 1; if (!s1 && s2) return -1; return o1.compareTo(o2); } }); return sorted; } /* Shows areas before non-areas */ public void visitAll(DataSet data, boolean virtual, Bounds bounds) { BBox bbox = new BBox(bounds); this.data = data; useStyleCache = Main.pref.getBoolean("mappaint.cache", true); int fillAreas = Main.pref.getInteger("mappaint.fillareas", 10000000); LatLon ll1 = nc.getLatLon(0, 0); LatLon ll2 = nc.getLatLon(100, 0); dist = ll1.greatCircleDistance(ll2); zoomLevelDisplay = Main.pref.getBoolean("mappaint.zoomLevelDisplay", false); circum = Main.map.mapView.getDist100Pixel(); styles = MapPaintStyles.getStyles().getStyleSet(); drawMultipolygon = Main.pref.getBoolean("mappaint.multipolygon", true); drawRestriction = Main.pref.getBoolean("mappaint.restriction", true); leftHandTraffic = Main.pref.getBoolean("mappaint.lefthandtraffic", false); minEN = nc.getEastNorth(0, nc.getHeight() - 1); maxEN = nc.getEastNorth(nc.getWidth() - 1, 0); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, Main.pref.getBoolean("mappaint.use-antialiasing", false) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); this.paintSettings = MapPaintSettings.INSTANCE; this.painter = new MapPainter(paintSettings, g, inactive, nc, virtual, dist, circum); data.clearErrors(); ++paintid; if (fillAreas > dist && styles != null && styles.hasAreas()) { Collection<Way> noAreaWays = new LinkedList<Way>(); /*** RELATIONS ***/ for (final Relation osm: data.getRelations()) { if (osm.isDrawable()) { paintUnselectedRelation(osm); } } /*** AREAS ***/ for (final Way osm : selectedLast(data, data.searchWays(bbox))) { if (osm.isDrawable() && osm.mappaintDrawnCode != paintid) { if (isPrimitiveArea(osm) && osm.mappaintDrawnAreaCode != paintid) { drawWay(osm, fillAreas); } else { noAreaWays.add(osm); } } } /*** WAYS ***/ for (final Way osm : noAreaWays) { drawWay(osm, 0); } } else { drawMultipolygon = false; /*** RELATIONS ***/ for (final Relation osm: data.getRelations()) { if (osm.isDrawable()) { paintUnselectedRelation(osm); } } /*** WAYS (filling disabled) ***/ for (final Way way: data.getWays()) { if (way.isDrawable() && !data.isSelected(way)) { drawWay(way, 0); } } } /*** SELECTED ***/ for (final OsmPrimitive osm : data.getSelected()) { if (osm.isUsable() && !(osm instanceof Node) && osm.mappaintDrawnCode != paintid) { osm.visit(new AbstractVisitor() { public void visit(Way w) { drawWay(w, 0); } public void visit(Node n) { // Selected nodes are painted in following part } public void visit(Relation r) { /* TODO: is it possible to do this like the nodes/ways code? */ // Only nodes are painted, ways was already painted before (this might cause that // way in selected relation is hidden by another way) for (RelationMember m : r.getMembers()) { if (m.isNode() && m.getMember().isDrawable()) { drawSelectedMember(m.getMember(), styles != null ? getPrimitiveStyle(m.getMember()) : null, true, true); } } } }); } } /*** NODES ***/ for (final Node osm: data.searchNodes(bbox)) { if (!osm.isIncomplete() && !osm.isDeleted() && (data.isSelected(osm) || !osm.isFiltered()) && osm.mappaintDrawnCode != paintid) { drawNode(osm); } } painter.drawVirtualNodes(data.searchWays(bbox)); } public void putError(OsmPrimitive p, String text, boolean isError) { data.addError(p, isError ? tr("Error: {0}", text) : tr("Warning: {0}", text)); } public void setGraphics(Graphics2D g) { this.g = g; } public void setInactive(boolean inactive) { this.inactive = inactive; } public void setNavigatableComponent(NavigatableComponent nc) { this.nc = nc; } }
false
true
public void drawRestriction(Relation r) { Way fromWay = null; Way toWay = null; OsmPrimitive via = null; /* find the "from", "via" and "to" elements */ for (RelationMember m : r.getMembers()) { if(m.getMember().isIncomplete()) return; else { if(m.isWay()) { Way w = m.getWay(); if(w.getNodesCount() < 2) { continue; } if("from".equals(m.getRole())) { if(fromWay != null) { putError(r, tr("More than one \"from\" way found."), true); } else { fromWay = w; } } else if("to".equals(m.getRole())) { if(toWay != null) { putError(r, tr("More than one \"to\" way found."), true); } else { toWay = w; } } else if("via".equals(m.getRole())) { if(via != null) { putError(r, tr("More than one \"via\" found."), true); } else { via = w; } } else { putError(r, tr("Unknown role ''{0}''.", m.getRole()), true); } } else if(m.isNode()) { Node n = m.getNode(); if("via".equals(m.getRole())) { if(via != null) { putError(r, tr("More than one \"via\" found."), true); } else { via = n; } } else { putError(r, tr("Unknown role ''{0}''.", m.getRole()), true); } } else { putError(r, tr("Unknown member type for ''{0}''.", m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true); } } } if (fromWay == null) { putError(r, tr("No \"from\" way found."), true); return; } if (toWay == null) { putError(r, tr("No \"to\" way found."), true); return; } if (via == null) { putError(r, tr("No \"via\" node or way found."), true); return; } Node viaNode; if(via instanceof Node) { viaNode = (Node) via; if(!fromWay.isFirstLastNode(viaNode)) { putError(r, tr("The \"from\" way does not start or end at a \"via\" node."), true); return; } if(!toWay.isFirstLastNode(viaNode)) { putError(r, tr("The \"to\" way does not start or end at a \"via\" node."), true); } } else { Way viaWay = (Way) via; Node firstNode = viaWay.firstNode(); Node lastNode = viaWay.lastNode(); boolean onewayvia = false; String onewayviastr = viaWay.get("oneway"); if(onewayviastr != null) { if("-1".equals(onewayviastr)) { onewayvia = true; Node tmp = firstNode; firstNode = lastNode; lastNode = tmp; } else { onewayvia = OsmUtils.getOsmBoolean(onewayviastr); } } if(fromWay.isFirstLastNode(firstNode)) { viaNode = firstNode; } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) { viaNode = lastNode; } else { putError(r, tr("The \"from\" way does not start or end at the \"via\" way."), true); return; } if(!toWay.isFirstLastNode(viaNode == firstNode ? lastNode : firstNode)) { putError(r, tr("The \"to\" way does not start or end at the \"via\" way."), true); } } /* find the "direct" nodes before the via node */ Node fromNode = null; if(fromWay.firstNode() == via) { fromNode = fromWay.getNode(1); } else { fromNode = fromWay.getNode(fromWay.getNodesCount()-2); } Point pFrom = nc.getPoint(fromNode); Point pVia = nc.getPoint(viaNode); /* starting from via, go back the "from" way a few pixels (calculate the vector vx/vy with the specified length and the direction away from the "via" node along the first segment of the "from" way) */ double distanceFromVia=14; double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x); double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y); double fromAngle; if(dx == 0.0) { fromAngle = Math.PI/2; } else { fromAngle = Math.atan(dy / dx); } double fromAngleDeg = Math.toDegrees(fromAngle); double vx = distanceFromVia * Math.cos(fromAngle); double vy = distanceFromVia * Math.sin(fromAngle); if(pFrom.x < pVia.x) { vx = -vx; } if(pFrom.y < pVia.y) { vy = -vy; } /* go a few pixels away from the way (in a right angle) (calculate the vx2/vy2 vector with the specified length and the direction 90degrees away from the first segment of the "from" way) */ double distanceFromWay=10; double vx2 = 0; double vy2 = 0; double iconAngle = 0; if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90)); } else { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90)); } iconAngle = 270+fromAngleDeg; } if(pFrom.x < pVia.x && pFrom.y >= pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg)); } else { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180)); } iconAngle = 90-fromAngleDeg; } if(pFrom.x < pVia.x && pFrom.y < pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90)); } else { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90)); } iconAngle = 90+fromAngleDeg; } if(pFrom.x >= pVia.x && pFrom.y < pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180)); } else { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg)); } iconAngle = 270-fromAngleDeg; } IconElemStyle nodeStyle = getPrimitiveNodeStyle(r); if (nodeStyle == null) { putError(r, tr("Style for restriction {0} not found.", r.get("restriction")), true); return; } painter.drawRestriction(inactive || r.isDisabled() ? nodeStyle.getDisabledIcon() : nodeStyle.icon, pVia, vx, vx2, vy, vy2, iconAngle, data.isSelected(r)); }
public void drawRestriction(Relation r) { Way fromWay = null; Way toWay = null; OsmPrimitive via = null; /* find the "from", "via" and "to" elements */ for (RelationMember m : r.getMembers()) { if(m.getMember().isIncomplete()) return; else { if(m.isWay()) { Way w = m.getWay(); if(w.getNodesCount() < 2) { continue; } if("from".equals(m.getRole())) { if(fromWay != null) { putError(r, tr("More than one \"from\" way found."), true); } else { fromWay = w; } } else if("to".equals(m.getRole())) { if(toWay != null) { putError(r, tr("More than one \"to\" way found."), true); } else { toWay = w; } } else if("via".equals(m.getRole())) { if(via != null) { putError(r, tr("More than one \"via\" found."), true); } else { via = w; } } else { putError(r, tr("Unknown role ''{0}''.", m.getRole()), true); } } else if(m.isNode()) { Node n = m.getNode(); if("via".equals(m.getRole())) { if(via != null) { putError(r, tr("More than one \"via\" found."), true); } else { via = n; } } else { putError(r, tr("Unknown role ''{0}''.", m.getRole()), true); } } else { putError(r, tr("Unknown member type for ''{0}''.", m.getMember().getDisplayName(DefaultNameFormatter.getInstance())), true); } } } if (fromWay == null) { putError(r, tr("No \"from\" way found."), true); return; } if (toWay == null) { putError(r, tr("No \"to\" way found."), true); return; } if (via == null) { putError(r, tr("No \"via\" node or way found."), true); return; } Node viaNode; if(via instanceof Node) { viaNode = (Node) via; if(!fromWay.isFirstLastNode(viaNode)) { putError(r, tr("The \"from\" way does not start or end at a \"via\" node."), true); return; } if(!toWay.isFirstLastNode(viaNode)) { putError(r, tr("The \"to\" way does not start or end at a \"via\" node."), true); } } else { Way viaWay = (Way) via; Node firstNode = viaWay.firstNode(); Node lastNode = viaWay.lastNode(); Boolean onewayvia = false; String onewayviastr = viaWay.get("oneway"); if(onewayviastr != null) { if("-1".equals(onewayviastr)) { onewayvia = true; Node tmp = firstNode; firstNode = lastNode; lastNode = tmp; } else { onewayvia = OsmUtils.getOsmBoolean(onewayviastr); if (onewayvia == null) { onewayvia = false; } } } if(fromWay.isFirstLastNode(firstNode)) { viaNode = firstNode; } else if (!onewayvia && fromWay.isFirstLastNode(lastNode)) { viaNode = lastNode; } else { putError(r, tr("The \"from\" way does not start or end at the \"via\" way."), true); return; } if(!toWay.isFirstLastNode(viaNode == firstNode ? lastNode : firstNode)) { putError(r, tr("The \"to\" way does not start or end at the \"via\" way."), true); } } /* find the "direct" nodes before the via node */ Node fromNode = null; if(fromWay.firstNode() == via) { fromNode = fromWay.getNode(1); } else { fromNode = fromWay.getNode(fromWay.getNodesCount()-2); } Point pFrom = nc.getPoint(fromNode); Point pVia = nc.getPoint(viaNode); /* starting from via, go back the "from" way a few pixels (calculate the vector vx/vy with the specified length and the direction away from the "via" node along the first segment of the "from" way) */ double distanceFromVia=14; double dx = (pFrom.x >= pVia.x) ? (pFrom.x - pVia.x) : (pVia.x - pFrom.x); double dy = (pFrom.y >= pVia.y) ? (pFrom.y - pVia.y) : (pVia.y - pFrom.y); double fromAngle; if(dx == 0.0) { fromAngle = Math.PI/2; } else { fromAngle = Math.atan(dy / dx); } double fromAngleDeg = Math.toDegrees(fromAngle); double vx = distanceFromVia * Math.cos(fromAngle); double vy = distanceFromVia * Math.sin(fromAngle); if(pFrom.x < pVia.x) { vx = -vx; } if(pFrom.y < pVia.y) { vy = -vy; } /* go a few pixels away from the way (in a right angle) (calculate the vx2/vy2 vector with the specified length and the direction 90degrees away from the first segment of the "from" way) */ double distanceFromWay=10; double vx2 = 0; double vy2 = 0; double iconAngle = 0; if(pFrom.x >= pVia.x && pFrom.y >= pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90)); } else { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90)); } iconAngle = 270+fromAngleDeg; } if(pFrom.x < pVia.x && pFrom.y >= pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg)); } else { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180)); } iconAngle = 90-fromAngleDeg; } if(pFrom.x < pVia.x && pFrom.y < pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 90)); } else { vx2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg - 90)); vy2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg - 90)); } iconAngle = 90+fromAngleDeg; } if(pFrom.x >= pVia.x && pFrom.y < pVia.y) { if(!leftHandTraffic) { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg + 180)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg + 180)); } else { vx2 = distanceFromWay * Math.sin(Math.toRadians(fromAngleDeg)); vy2 = distanceFromWay * Math.cos(Math.toRadians(fromAngleDeg)); } iconAngle = 270-fromAngleDeg; } IconElemStyle nodeStyle = getPrimitiveNodeStyle(r); if (nodeStyle == null) { putError(r, tr("Style for restriction {0} not found.", r.get("restriction")), true); return; } painter.drawRestriction(inactive || r.isDisabled() ? nodeStyle.getDisabledIcon() : nodeStyle.icon, pVia, vx, vx2, vy, vy2, iconAngle, data.isSelected(r)); }
diff --git a/java/opennlp/textgrounder/models/EvalRegionModel.java b/java/opennlp/textgrounder/models/EvalRegionModel.java index 2240b030..75990aad 100644 --- a/java/opennlp/textgrounder/models/EvalRegionModel.java +++ b/java/opennlp/textgrounder/models/EvalRegionModel.java @@ -1,349 +1,353 @@ /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2010 Taesun Moon, The University of Texas at Austin // // 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 opennlp.textgrounder.models; import gnu.trove.TIntHashSet; import gnu.trove.TIntIterator; import gnu.trove.TIntObjectHashMap; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import opennlp.textgrounder.annealers.*; import opennlp.textgrounder.models.callbacks.*; import opennlp.textgrounder.textstructs.*; import opennlp.textgrounder.topostructs.*; /** * * @author tsmoon */ public class EvalRegionModel extends RegionModel { /** * */ protected RegionModel rm; /** * */ protected double[] priorWordByTopicCounts; /** * */ protected double[] priorTopicCounts; /** * * @param rm */ public EvalRegionModel(RegionModel rm) { this.rm = rm; try { initialize(); } catch (FileNotFoundException ex) { Logger.getLogger(EvalRegionModel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(EvalRegionModel.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(EvalRegionModel.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(EvalRegionModel.class.getName()).log(Level.SEVERE, null, ex); } } protected void initialize() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException { lexicon = new Lexicon(); stopwordList = rm.stopwordList; evalInputFile = rm.evalInputFile; evalTokenArrayBuffer = new EvalTokenArrayBuffer(lexicon, new TrainingMaterialCallback(lexicon)); processEvalInputPath(evalInputFile, new TextProcessorTR(lexicon), evalTokenArrayBuffer, stopwordList); evalTokenArrayBuffer.convertToPrimitiveArrays(); degreesPerRegion = rm.degreesPerRegion; initializeRegionArray(); locationSet = new TIntHashSet(); beta = rm.beta; alpha = rm.alpha; gazetteer = rm.gazetteer; regionMapperCallback = new RegionMapperCallback(); regionArrayHeight = rm.regionArrayHeight; regionArrayWidth = rm.regionArrayWidth; setAllocateFields(evalTokenArrayBuffer); annealer = new EvalAnnealer(); rand = rm.rand; } /** * */ protected void setAllocateFields(TokenArrayBuffer evalTokenArrayBuffer) { N = evalTokenArrayBuffer.size(); fW = lexicon.getDictionarySize(); D = evalTokenArrayBuffer.getNumDocs(); sW = stopwordList.size(); W = fW - sW; wordVector = evalTokenArrayBuffer.wordVector; documentVector = evalTokenArrayBuffer.documentVector; toponymVector = evalTokenArrayBuffer.toponymVector; stopwordVector = evalTokenArrayBuffer.stopwordVector; /** * There is no need to initialize the topicVector. It will be randomly * initialized */ topicVector = new int[N]; TIntHashSet toponymsNotInGazetteer = buildTopoTable(); T = regionMapperCallback.getNumRegions(); RegionModelBridge regionModelBridge = new RegionModelBridge(this, rm); int[] regionIdToRegionId = regionModelBridge.matchRegionId(); int[] wordIdToWordId = regionModelBridge.matchWordId(); topicByDocumentCounts = new int[D * T]; for (int i = 0; i < D * T; ++i) { topicByDocumentCounts[i] = 0; } wordByTopicCounts = new double[fW * T]; priorWordByTopicCounts = new double[fW * T]; for (int i = 0; i < fW * T; ++i) { priorWordByTopicCounts[i] = wordByTopicCounts[i] = 0; } for (int i = 0; i < fW; ++i) { int ewordoff = i * T; int twordoff = wordIdToWordId[i] * rm.T; if (twordoff < 0) { for (int j = 0; j < T; ++j) { priorWordByTopicCounts[ewordoff + j] = beta; } } else { for (int j = 0; j < T; ++j) { int tregid = regionIdToRegionId[j]; - priorWordByTopicCounts[ewordoff + j] = rm.wordByTopicCounts[twordoff + tregid] + beta; + if (tregid < 0) { + priorWordByTopicCounts[ewordoff + j] = beta; + } else { + priorWordByTopicCounts[ewordoff + j] = rm.wordByTopicCounts[twordoff + tregid] + beta; + } } } } topicCounts = new double[T]; priorTopicCounts = new double[T]; for (int i = 0; i < T; ++i) { priorTopicCounts[i] = topicCounts[i] = 0; } for (int i = 0; i < fW; ++i) { if (!stopwordList.isStopWord(lexicon.getWordForInt(i))) { int wordoff = i * T; for (int j = 0; j < T; ++j) { priorTopicCounts[j] += priorWordByTopicCounts[wordoff + j]; } } } regionByToponym = new int[fW * T]; for (int i = 0; i < fW * T; ++i) { regionByToponym[i] = 0; } buildTopoFilter(toponymsNotInGazetteer); } /** * Randomly initialize fields for training. If word is a toponym, choose * random region only from regions aligned to name. */ @Override public void randomInitialize() { int wordid, docid, topicid; int istoponym, isstopword; int docoff, wordoff; double[] probs = new double[T]; double totalprob, max, r; for (int i = 0; i < N; ++i) { isstopword = stopwordVector[i]; if (isstopword == 0) { wordid = wordVector[i]; docid = documentVector[i]; istoponym = toponymVector[i]; docoff = docid * T; wordoff = wordid * T; try { if (istoponym == 1) { for (int j = 0;; ++j) { probs[j] = (wordByTopicCounts[wordoff + j] + priorWordByTopicCounts[wordoff + j]) / (topicCounts[j] + priorTopicCounts[j]) * (topicByDocumentCounts[docoff + j] + alpha) * regionByToponym[wordoff + j]; } } else { for (int j = 0;; ++j) { probs[j] = (wordByTopicCounts[wordoff + j] + priorWordByTopicCounts[wordoff + j]) / (topicCounts[j] + priorTopicCounts[j]) * (topicByDocumentCounts[docoff + j] + alpha); } } } catch (ArrayIndexOutOfBoundsException e) { } totalprob = annealer.annealProbs(probs); r = rand.nextDouble() * totalprob; max = probs[0]; topicid = 0; while (r > max) { topicid++; max += probs[topicid]; } topicVector[i] = topicid; topicCounts[topicid]++; topicByDocumentCounts[docid * T + topicid]++; wordByTopicCounts[wordid * T + topicid]++; } } } /** * Train topics * * @param annealer Annealing scheme to use */ @Override public void train(Annealer annealer) { int wordid, docid, topicid; int wordoff, docoff; int istoponym, isstopword; double[] probs = new double[T]; double totalprob, max, r; while (annealer.nextIter()) { for (int i = 0; i < N; ++i) { isstopword = stopwordVector[i]; if (isstopword == 0) { wordid = wordVector[i]; docid = documentVector[i]; topicid = topicVector[i]; istoponym = toponymVector[i]; docoff = docid * T; wordoff = wordid * T; topicCounts[topicid]--; topicByDocumentCounts[docoff + topicid]--; wordByTopicCounts[wordoff + topicid]--; try { if (istoponym == 1) { for (int j = 0;; ++j) { probs[j] = (wordByTopicCounts[wordoff + j] + priorWordByTopicCounts[wordoff + j]) / (topicCounts[j] + priorTopicCounts[j]) * (topicByDocumentCounts[docoff + j] + alpha) * regionByToponym[wordoff + j]; } } else { for (int j = 0;; ++j) { probs[j] = (wordByTopicCounts[wordoff + j] + priorWordByTopicCounts[wordoff + j]) / (topicCounts[j] + priorTopicCounts[j]) * (topicByDocumentCounts[docoff + j] + alpha); } } } catch (ArrayIndexOutOfBoundsException e) { } totalprob = annealer.annealProbs(probs); r = rand.nextDouble() * totalprob; max = probs[0]; topicid = 0; while (r > max) { topicid++; max += probs[topicid]; } topicVector[i] = topicid; topicCounts[topicid]++; topicByDocumentCounts[docoff + topicid]++; wordByTopicCounts[wordoff + topicid]++; } } annealer.collectSamples(topicCounts, wordByTopicCounts); } } /** * */ @Override protected void normalizeLocations() { for (TIntIterator it = locationSet.iterator(); it.hasNext();) { int locid = it.next(); Location loc = gazetteer.getLocation(locid); loc.count += beta; loc.backPointers = new ArrayList<Integer>(); } TIntObjectHashMap<TIntHashSet> toponymRegionToLocations = regionMapperCallback.getToponymRegionToLocations(); int wordid, topicid; int istoponym, isstopword; for (int i = 0; i < N; ++i) { isstopword = stopwordVector[i]; boolean added = false; if (isstopword == 0) { istoponym = toponymVector[i]; if (istoponym == 1) { wordid = wordVector[i]; topicid = topicVector[i]; ToponymRegionPair trp = new ToponymRegionPair(wordid, topicid); TIntHashSet locs = toponymRegionToLocations.get(trp.hashCode()); try { int size = locs.size(); int randIndex = rand.nextInt(size); int curLocationIdx = locs.toArray()[randIndex]; Location curLocation = gazetteer.getLocation(curLocationIdx); evalTokenArrayBuffer.modelLocationArrayList.add(curLocation); } catch (NullPointerException e) { locs = new TIntHashSet(); Region r = regionMapperCallback.getRegionMap().get(topicid); Coordinate coord = new Coordinate(r.centLon, r.centLat); Location loc = new Location(-1, lexicon.getWordForInt(wordid), null, coord, 0, null, 1); evalTokenArrayBuffer.modelLocationArrayList.add(loc); locs.add(loc.id); toponymRegionToLocations.put(trp.hashCode(), locs); } added = true; } } if (!added) { evalTokenArrayBuffer.modelLocationArrayList.add(null); } } } @Override public void evaluate() { evaluate(evalTokenArrayBuffer); } }
true
true
protected void setAllocateFields(TokenArrayBuffer evalTokenArrayBuffer) { N = evalTokenArrayBuffer.size(); fW = lexicon.getDictionarySize(); D = evalTokenArrayBuffer.getNumDocs(); sW = stopwordList.size(); W = fW - sW; wordVector = evalTokenArrayBuffer.wordVector; documentVector = evalTokenArrayBuffer.documentVector; toponymVector = evalTokenArrayBuffer.toponymVector; stopwordVector = evalTokenArrayBuffer.stopwordVector; /** * There is no need to initialize the topicVector. It will be randomly * initialized */ topicVector = new int[N]; TIntHashSet toponymsNotInGazetteer = buildTopoTable(); T = regionMapperCallback.getNumRegions(); RegionModelBridge regionModelBridge = new RegionModelBridge(this, rm); int[] regionIdToRegionId = regionModelBridge.matchRegionId(); int[] wordIdToWordId = regionModelBridge.matchWordId(); topicByDocumentCounts = new int[D * T]; for (int i = 0; i < D * T; ++i) { topicByDocumentCounts[i] = 0; } wordByTopicCounts = new double[fW * T]; priorWordByTopicCounts = new double[fW * T]; for (int i = 0; i < fW * T; ++i) { priorWordByTopicCounts[i] = wordByTopicCounts[i] = 0; } for (int i = 0; i < fW; ++i) { int ewordoff = i * T; int twordoff = wordIdToWordId[i] * rm.T; if (twordoff < 0) { for (int j = 0; j < T; ++j) { priorWordByTopicCounts[ewordoff + j] = beta; } } else { for (int j = 0; j < T; ++j) { int tregid = regionIdToRegionId[j]; priorWordByTopicCounts[ewordoff + j] = rm.wordByTopicCounts[twordoff + tregid] + beta; } } } topicCounts = new double[T]; priorTopicCounts = new double[T]; for (int i = 0; i < T; ++i) { priorTopicCounts[i] = topicCounts[i] = 0; } for (int i = 0; i < fW; ++i) { if (!stopwordList.isStopWord(lexicon.getWordForInt(i))) { int wordoff = i * T; for (int j = 0; j < T; ++j) { priorTopicCounts[j] += priorWordByTopicCounts[wordoff + j]; } } } regionByToponym = new int[fW * T]; for (int i = 0; i < fW * T; ++i) { regionByToponym[i] = 0; } buildTopoFilter(toponymsNotInGazetteer); }
protected void setAllocateFields(TokenArrayBuffer evalTokenArrayBuffer) { N = evalTokenArrayBuffer.size(); fW = lexicon.getDictionarySize(); D = evalTokenArrayBuffer.getNumDocs(); sW = stopwordList.size(); W = fW - sW; wordVector = evalTokenArrayBuffer.wordVector; documentVector = evalTokenArrayBuffer.documentVector; toponymVector = evalTokenArrayBuffer.toponymVector; stopwordVector = evalTokenArrayBuffer.stopwordVector; /** * There is no need to initialize the topicVector. It will be randomly * initialized */ topicVector = new int[N]; TIntHashSet toponymsNotInGazetteer = buildTopoTable(); T = regionMapperCallback.getNumRegions(); RegionModelBridge regionModelBridge = new RegionModelBridge(this, rm); int[] regionIdToRegionId = regionModelBridge.matchRegionId(); int[] wordIdToWordId = regionModelBridge.matchWordId(); topicByDocumentCounts = new int[D * T]; for (int i = 0; i < D * T; ++i) { topicByDocumentCounts[i] = 0; } wordByTopicCounts = new double[fW * T]; priorWordByTopicCounts = new double[fW * T]; for (int i = 0; i < fW * T; ++i) { priorWordByTopicCounts[i] = wordByTopicCounts[i] = 0; } for (int i = 0; i < fW; ++i) { int ewordoff = i * T; int twordoff = wordIdToWordId[i] * rm.T; if (twordoff < 0) { for (int j = 0; j < T; ++j) { priorWordByTopicCounts[ewordoff + j] = beta; } } else { for (int j = 0; j < T; ++j) { int tregid = regionIdToRegionId[j]; if (tregid < 0) { priorWordByTopicCounts[ewordoff + j] = beta; } else { priorWordByTopicCounts[ewordoff + j] = rm.wordByTopicCounts[twordoff + tregid] + beta; } } } } topicCounts = new double[T]; priorTopicCounts = new double[T]; for (int i = 0; i < T; ++i) { priorTopicCounts[i] = topicCounts[i] = 0; } for (int i = 0; i < fW; ++i) { if (!stopwordList.isStopWord(lexicon.getWordForInt(i))) { int wordoff = i * T; for (int j = 0; j < T; ++j) { priorTopicCounts[j] += priorWordByTopicCounts[wordoff + j]; } } } regionByToponym = new int[fW * T]; for (int i = 0; i < fW * T; ++i) { regionByToponym[i] = 0; } buildTopoFilter(toponymsNotInGazetteer); }
diff --git a/src/main/java/com/runetooncraft/plugins/CostDistanceTeleporter/Teleportlistener.java b/src/main/java/com/runetooncraft/plugins/CostDistanceTeleporter/Teleportlistener.java index 71547c8..dde9626 100644 --- a/src/main/java/com/runetooncraft/plugins/CostDistanceTeleporter/Teleportlistener.java +++ b/src/main/java/com/runetooncraft/plugins/CostDistanceTeleporter/Teleportlistener.java @@ -1,116 +1,116 @@ package com.runetooncraft.plugins.CostDistanceTeleporter; import java.util.HashMap; import net.ess3.api.InvalidWorldException; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.commands.WarpNotFoundException; public class Teleportlistener implements Listener { private Config config; public static HashMap<Player, String> Playerwarpdata = new HashMap<Player, String>(); public Teleportlistener(Config config){ this.config = config; } @EventHandler public void onCommand(PlayerCommandPreprocessEvent event) { if(CDT.perms.has(event.getPlayer(), "cdt.bypass") == false) { String Cvalue = CDT.econ.currencyNamePlural(); if(event.getMessage().startsWith("/warp") && config.getbool("CDT.Commandsenabled.warp")) { Player p = event.getPlayer(); String input = event.getMessage(); String[] args = input.split(" "); if(args[0].equals("/warp") && args.length == 2) { if(CDT.perms.has(p, "essentials.warps." + args[1]) && config.getbool("CDT.Commandsenabled.warp") || CDT.perms.has(p, "essentials.warps.*") || !CDT.PerWarpPermissions || !CDT.permsenabled) { try { Location warploc = CDT.ess.getWarps().getWarp(args[1]).getBlock().getLocation(); if(p.getLocation().getWorld().equals(warploc.getWorld())) { HandleWarp(event,args,warploc,Cvalue); }else{ - if(config.getbool("CDT.MultiWorldSupport") == false) { + if(config.getbool("CDT.MultiWorld.Support") == false) { Messenger.playermessage("Multi-world warp support is not enabled.", p); event.setCancelled(true); }else{ HandleWarp(event,args,warploc,Cvalue); } } } catch (WarpNotFoundException e) { Messenger.playermessage("Warp " + args[1] + " not found.", p); } catch (InvalidWorldException e) { Messenger.playermessage("Invalid world.", p); } } } }else if(event.getMessage().startsWith("/spawn") && config.getbool("CDT.Commandsenabled.spawn") && CDT.EssentialsSpawn || !CDT.permsenabled) { Player p = event.getPlayer(); Location spawnloc = CDT.parseSpawnYmlLoc(); int Cost = parseLocation.getDistanceCost(p.getLocation(), spawnloc); if(Playerwarpdata.get(p) == null) { Messenger.playermessage("Warping to spawn will cost " + Cost + " " + Cvalue + ". Type [/spawn] again to pay this amount and teleport.", p); Playerwarpdata.put(p, "essentialsSpawn"); event.setCancelled(true); }else{ if(Playerwarpdata.get(p).equals("essentialsSpawn")) { if(CDT.econ.has(p.getName(), Cost)) { EconomyResponse r = CDT.econ.withdrawPlayer(p.getName(), Cost); Messenger.playermessage(Cost + " " + Cvalue + " was deducted from your account to warp to Spawn", p); config.addint("CDT.stats.money", Cost); Playerwarpdata.remove(p); event.setCancelled(false); }else{ Messenger.playermessage("You do not have sufficient funds to warp to " + "essentialsSpawn" + ". You require " + Cost + " " + Cvalue + ", but only have " + CDT.econ.getBalance(p.getName()) + " " + Cvalue + ".", p); Playerwarpdata.remove(p); event.setCancelled(true); } //TODO: Currency check (if player has enough money for warp), Taking money away and warping, clear hashmap of this value. }else{ Messenger.playermessage("Warping to spawn will cost " + Cost + " " + Cvalue + ". Type [/spawn] again to pay this amount and teleport.", p); Playerwarpdata.put(p, "essentialsSpawn"); event.setCancelled(true); } } } }else{ event.setCancelled(false); } } private void HandleWarp(PlayerCommandPreprocessEvent event, String[] args, Location warploc, String Cvalue) { Player p = event.getPlayer(); int Cost = parseLocation.getDistanceCost(p.getLocation(), warploc); if(Playerwarpdata.get(p) == null) { Messenger.playermessage("Warping to " + args[1] + " will cost " + Cost + " " + Cvalue + ". Type [/warp " + args[1] + "] again to pay this amount and teleport.", p); Playerwarpdata.put(p, args[1]); event.setCancelled(true); }else{ if(Playerwarpdata.get(p).equals(args[1])) { if(CDT.econ.has(p.getName(), Cost)) { EconomyResponse r = CDT.econ.withdrawPlayer(p.getName(), Cost); Messenger.playermessage(Cost + " " + Cvalue + " was deducted from your account to warp to " + args[1], p); config.addint("CDT.stats.money", Cost); Playerwarpdata.remove(p); event.setCancelled(false); }else{ Messenger.playermessage("You do not have sufficient funds to warp to " + args[1] + ". You require " + Cost + " " + Cvalue + ", but only have " + CDT.econ.getBalance(p.getName()) + " " + Cvalue + ".", p); Playerwarpdata.remove(p); event.setCancelled(true); } //TODO: Currency check (if player has enough money for warp), Taking money away and warping, clear hashmap of this value. }else{ Messenger.playermessage("Warping to " + args[1] + " will cost " + Cost + " " + Cvalue + ". Type [/warp " + args[1] + "] again to pay this amount and teleport.", p); Playerwarpdata.put(p, args[1]); event.setCancelled(true); } } } }
true
true
public void onCommand(PlayerCommandPreprocessEvent event) { if(CDT.perms.has(event.getPlayer(), "cdt.bypass") == false) { String Cvalue = CDT.econ.currencyNamePlural(); if(event.getMessage().startsWith("/warp") && config.getbool("CDT.Commandsenabled.warp")) { Player p = event.getPlayer(); String input = event.getMessage(); String[] args = input.split(" "); if(args[0].equals("/warp") && args.length == 2) { if(CDT.perms.has(p, "essentials.warps." + args[1]) && config.getbool("CDT.Commandsenabled.warp") || CDT.perms.has(p, "essentials.warps.*") || !CDT.PerWarpPermissions || !CDT.permsenabled) { try { Location warploc = CDT.ess.getWarps().getWarp(args[1]).getBlock().getLocation(); if(p.getLocation().getWorld().equals(warploc.getWorld())) { HandleWarp(event,args,warploc,Cvalue); }else{ if(config.getbool("CDT.MultiWorldSupport") == false) { Messenger.playermessage("Multi-world warp support is not enabled.", p); event.setCancelled(true); }else{ HandleWarp(event,args,warploc,Cvalue); } } } catch (WarpNotFoundException e) { Messenger.playermessage("Warp " + args[1] + " not found.", p); } catch (InvalidWorldException e) { Messenger.playermessage("Invalid world.", p); } } } }else if(event.getMessage().startsWith("/spawn") && config.getbool("CDT.Commandsenabled.spawn") && CDT.EssentialsSpawn || !CDT.permsenabled) { Player p = event.getPlayer(); Location spawnloc = CDT.parseSpawnYmlLoc(); int Cost = parseLocation.getDistanceCost(p.getLocation(), spawnloc); if(Playerwarpdata.get(p) == null) { Messenger.playermessage("Warping to spawn will cost " + Cost + " " + Cvalue + ". Type [/spawn] again to pay this amount and teleport.", p); Playerwarpdata.put(p, "essentialsSpawn"); event.setCancelled(true); }else{ if(Playerwarpdata.get(p).equals("essentialsSpawn")) { if(CDT.econ.has(p.getName(), Cost)) { EconomyResponse r = CDT.econ.withdrawPlayer(p.getName(), Cost); Messenger.playermessage(Cost + " " + Cvalue + " was deducted from your account to warp to Spawn", p); config.addint("CDT.stats.money", Cost); Playerwarpdata.remove(p); event.setCancelled(false); }else{ Messenger.playermessage("You do not have sufficient funds to warp to " + "essentialsSpawn" + ". You require " + Cost + " " + Cvalue + ", but only have " + CDT.econ.getBalance(p.getName()) + " " + Cvalue + ".", p); Playerwarpdata.remove(p); event.setCancelled(true); } //TODO: Currency check (if player has enough money for warp), Taking money away and warping, clear hashmap of this value. }else{ Messenger.playermessage("Warping to spawn will cost " + Cost + " " + Cvalue + ". Type [/spawn] again to pay this amount and teleport.", p); Playerwarpdata.put(p, "essentialsSpawn"); event.setCancelled(true); } } } }else{ event.setCancelled(false); } }
public void onCommand(PlayerCommandPreprocessEvent event) { if(CDT.perms.has(event.getPlayer(), "cdt.bypass") == false) { String Cvalue = CDT.econ.currencyNamePlural(); if(event.getMessage().startsWith("/warp") && config.getbool("CDT.Commandsenabled.warp")) { Player p = event.getPlayer(); String input = event.getMessage(); String[] args = input.split(" "); if(args[0].equals("/warp") && args.length == 2) { if(CDT.perms.has(p, "essentials.warps." + args[1]) && config.getbool("CDT.Commandsenabled.warp") || CDT.perms.has(p, "essentials.warps.*") || !CDT.PerWarpPermissions || !CDT.permsenabled) { try { Location warploc = CDT.ess.getWarps().getWarp(args[1]).getBlock().getLocation(); if(p.getLocation().getWorld().equals(warploc.getWorld())) { HandleWarp(event,args,warploc,Cvalue); }else{ if(config.getbool("CDT.MultiWorld.Support") == false) { Messenger.playermessage("Multi-world warp support is not enabled.", p); event.setCancelled(true); }else{ HandleWarp(event,args,warploc,Cvalue); } } } catch (WarpNotFoundException e) { Messenger.playermessage("Warp " + args[1] + " not found.", p); } catch (InvalidWorldException e) { Messenger.playermessage("Invalid world.", p); } } } }else if(event.getMessage().startsWith("/spawn") && config.getbool("CDT.Commandsenabled.spawn") && CDT.EssentialsSpawn || !CDT.permsenabled) { Player p = event.getPlayer(); Location spawnloc = CDT.parseSpawnYmlLoc(); int Cost = parseLocation.getDistanceCost(p.getLocation(), spawnloc); if(Playerwarpdata.get(p) == null) { Messenger.playermessage("Warping to spawn will cost " + Cost + " " + Cvalue + ". Type [/spawn] again to pay this amount and teleport.", p); Playerwarpdata.put(p, "essentialsSpawn"); event.setCancelled(true); }else{ if(Playerwarpdata.get(p).equals("essentialsSpawn")) { if(CDT.econ.has(p.getName(), Cost)) { EconomyResponse r = CDT.econ.withdrawPlayer(p.getName(), Cost); Messenger.playermessage(Cost + " " + Cvalue + " was deducted from your account to warp to Spawn", p); config.addint("CDT.stats.money", Cost); Playerwarpdata.remove(p); event.setCancelled(false); }else{ Messenger.playermessage("You do not have sufficient funds to warp to " + "essentialsSpawn" + ". You require " + Cost + " " + Cvalue + ", but only have " + CDT.econ.getBalance(p.getName()) + " " + Cvalue + ".", p); Playerwarpdata.remove(p); event.setCancelled(true); } //TODO: Currency check (if player has enough money for warp), Taking money away and warping, clear hashmap of this value. }else{ Messenger.playermessage("Warping to spawn will cost " + Cost + " " + Cvalue + ". Type [/spawn] again to pay this amount and teleport.", p); Playerwarpdata.put(p, "essentialsSpawn"); event.setCancelled(true); } } } }else{ event.setCancelled(false); } }
diff --git a/modules/srm/src/org/dcache/srm/server/SRMServerV2.java b/modules/srm/src/org/dcache/srm/server/SRMServerV2.java index e7c1c8b10b..14ec526804 100644 --- a/modules/srm/src/org/dcache/srm/server/SRMServerV2.java +++ b/modules/srm/src/org/dcache/srm/server/SRMServerV2.java @@ -1,606 +1,606 @@ //______________________________________________________________________________ // // $Id$ // $Author$ // //______________________________________________________________________________ /* COPYRIGHT STATUS: Dec 1st 2001, Fermi National Accelerator Laboratory (FNAL) documents and software are sponsored by the U.S. Department of Energy under Contract No. DE-AC02-76CH03000. Therefore, the U.S. Government retains a world-wide non-exclusive, royalty-free license to publish or reproduce these documents and software for U.S. Government purposes. All documents and software available from this server are protected under the U.S. and Foreign Copyright Laws, and FNAL reserves all rights. Distribution of the software available from this server is free of charge subject to the user following the terms of the Fermitools Software Legal Information. Redistribution and/or modification of the software shall be accompanied by the Fermitools Software Legal Information (including the copyright notice). The user is asked to feed back problems, benefits, and/or suggestions about the software to the Fermilab Software Providers. Neither the name of Fermilab, the URA, nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. DISCLAIMER OF LIABILITY (BSD): THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FERMILAB, OR THE URA, OR THE U.S. DEPARTMENT of ENERGY, OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Liabilities of the Government: This software is provided by URA, independent from its Prime Contract with the U.S. Department of Energy. URA is acting independently from the Government and in its own private capacity and is not acting on behalf of the U.S. Government, nor as its contractor nor its agent. Correspondingly, it is understood and agreed that the U.S. Government has no connection to this software and in no manner whatsoever shall be liable for nor assume any responsibility or obligation for any claim, cost, or damages arising out of or resulting from the use of the software available from this server. Export Control: All documents and software available from this server are subject to U.S. export control laws. Anyone downloading information from this server is obligated to secure any necessary Government licenses before exporting documents or software obtained from this server. */ package org.dcache.srm.server; import java.rmi.RemoteException; import org.dcache.srm.SRM; import org.dcache.srm.v2_2.SrmAbortFilesRequest; import org.dcache.srm.v2_2.SrmAbortFilesResponse; import org.dcache.srm.v2_2.SrmAbortRequestRequest; import org.dcache.srm.v2_2.SrmAbortRequestResponse; import org.dcache.srm.v2_2.SrmBringOnlineRequest; import org.dcache.srm.v2_2.SrmBringOnlineResponse; import org.dcache.srm.v2_2.SrmChangeSpaceForFilesRequest; import org.dcache.srm.v2_2.SrmChangeSpaceForFilesResponse; import org.dcache.srm.v2_2.SrmCheckPermissionRequest; import org.dcache.srm.v2_2.SrmCheckPermissionResponse; import org.dcache.srm.v2_2.SrmCopyRequest; import org.dcache.srm.v2_2.SrmCopyResponse; import org.dcache.srm.v2_2.SrmExtendFileLifeTimeInSpaceRequest; import org.dcache.srm.v2_2.SrmExtendFileLifeTimeInSpaceResponse; import org.dcache.srm.v2_2.SrmExtendFileLifeTimeRequest; import org.dcache.srm.v2_2.SrmExtendFileLifeTimeResponse; import org.dcache.srm.v2_2.SrmGetPermissionRequest; import org.dcache.srm.v2_2.SrmGetPermissionResponse; import org.dcache.srm.v2_2.SrmGetRequestSummaryRequest; import org.dcache.srm.v2_2.SrmGetRequestSummaryResponse; import org.dcache.srm.v2_2.SrmGetRequestTokensRequest; import org.dcache.srm.v2_2.SrmGetRequestTokensResponse; import org.dcache.srm.v2_2.SrmGetSpaceMetaDataRequest; import org.dcache.srm.v2_2.SrmGetSpaceMetaDataResponse; import org.dcache.srm.v2_2.SrmGetSpaceTokensRequest; import org.dcache.srm.v2_2.SrmGetSpaceTokensResponse; import org.dcache.srm.v2_2.SrmGetTransferProtocolsRequest; import org.dcache.srm.v2_2.SrmGetTransferProtocolsResponse; import org.dcache.srm.v2_2.SrmLsRequest; import org.dcache.srm.v2_2.SrmLsResponse; import org.dcache.srm.v2_2.SrmMvRequest; import org.dcache.srm.v2_2.SrmMvResponse; import org.dcache.srm.v2_2.SrmPingRequest; import org.dcache.srm.v2_2.SrmPingResponse; import org.dcache.srm.v2_2.SrmPrepareToGetRequest; import org.dcache.srm.v2_2.SrmPrepareToGetResponse; import org.dcache.srm.v2_2.SrmPrepareToPutRequest; import org.dcache.srm.v2_2.SrmPrepareToPutResponse; import org.dcache.srm.v2_2.SrmPurgeFromSpaceRequest; import org.dcache.srm.v2_2.SrmPurgeFromSpaceResponse; import org.dcache.srm.v2_2.SrmPutDoneRequest; import org.dcache.srm.v2_2.SrmPutDoneResponse; import org.dcache.srm.v2_2.SrmReleaseFilesRequest; import org.dcache.srm.v2_2.SrmReleaseFilesResponse; import org.dcache.srm.v2_2.SrmReleaseSpaceRequest; import org.dcache.srm.v2_2.SrmReleaseSpaceResponse; import org.dcache.srm.v2_2.SrmReserveSpaceRequest; import org.dcache.srm.v2_2.SrmReserveSpaceResponse; import org.dcache.srm.v2_2.SrmResumeRequestRequest; import org.dcache.srm.v2_2.SrmResumeRequestResponse; import org.dcache.srm.v2_2.SrmRmRequest; import org.dcache.srm.v2_2.SrmRmResponse; import org.dcache.srm.v2_2.SrmRmdirRequest; import org.dcache.srm.v2_2.SrmRmdirResponse; import org.dcache.srm.v2_2.SrmMkdirRequest; import org.dcache.srm.v2_2.SrmMkdirResponse; import org.dcache.srm.v2_2.SrmSetPermissionRequest; import org.dcache.srm.v2_2.SrmSetPermissionResponse; import org.dcache.srm.v2_2.SrmStatusOfBringOnlineRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfBringOnlineRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfChangeSpaceForFilesRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfChangeSpaceForFilesRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfCopyRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfCopyRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfGetRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfGetRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfLsRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfLsRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfPutRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfPutRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfReserveSpaceRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfReserveSpaceRequestResponse; import org.dcache.srm.v2_2.SrmStatusOfUpdateSpaceRequestRequest; import org.dcache.srm.v2_2.SrmStatusOfUpdateSpaceRequestResponse; import org.dcache.srm.v2_2.SrmSuspendRequestRequest; import org.dcache.srm.v2_2.SrmSuspendRequestResponse; import org.dcache.srm.v2_2.SrmUpdateSpaceRequest; import org.dcache.srm.v2_2.SrmUpdateSpaceResponse; import org.dcache.srm.v2_2.TStatusCode; import org.dcache.srm.v2_2.TReturnStatus; import javax.naming.Context; import javax.naming.InitialContext; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import org.dcache.srm.SRMAuthorizationException; import org.dcache.srm.request.RequestUser; import org.dcache.srm.AbstractStorageElement; import org.dcache.srm.request.RequestCredential; import java.util.Collection; import org.gridforum.jgss.ExtendedGSSContext; public class SRMServerV2 implements org.dcache.srm.v2_2.ISRM { // log4j Logger public Logger log; private SrmDCacheConnector srmConn; private SrmAuthorizer srmAuth = null; org.dcache.srm.util.Configuration configuration; private AbstractStorageElement storage; public SRMServerV2() throws java.rmi.RemoteException{ try { // srmConn = SrmDCacheConnector.getInstance(); log = Logger.getLogger("logger.org.dcache.authorization."+ this.getClass().getName()); Context logctx = new InitialContext(); String srmConfigFile = (String) logctx.lookup("java:comp/env/srmConfigFile"); if(srmConfigFile == null) { String error = "name of srm config file is not specified"; String error_details ="please insert the following xml codelet into web.xml\n"+ " <env-entry>\n"+ " <env-entry-name>srmConfigFile</env-entry-name>\n"+ " <env-entry-value>INSERT SRM CONFIG FILE NAME HERE</env-entry-value>\n"+ " <env-entry-type>java.lang.String</env-entry-type>\n"+ " </env-entry>"; log.error(error); log.error(error_details); throw new java.rmi.RemoteException(error ); } srmConn = SrmDCacheConnector.getInstance(srmConfigFile); if (srmConn == null) { throw new java.rmi.RemoteException("Failed to get instance of srm." ); } String logConfigFile = srmConn.getLogFile(); DOMConfigurator.configure(logConfigFile); log.info("srmConfigFile: " + srmConfigFile); log.info(" initialize() got connector ="+srmConn); // Set up the authorization service srmAuth = new SrmAuthorizer(srmConn); storage = srmConn.getSrm().getConfiguration().getStorage(); } catch ( java.rmi.RemoteException re) { throw re; } catch ( Exception e) { throw new java.rmi.RemoteException("exception",e); } } private Object handleRequest(String requestName, Object request) throws RemoteException { String capitalizedRequestName = Character.toUpperCase(requestName.charAt(0))+ requestName.substring(1); try { Class requestClass = request.getClass(); log.debug("Entering SRMServerV2."+requestName+"()"); String authorizationID = null; try { Method getAuthorizationID = requestClass.getMethod("getAuthorizationID",(Class[])null); if(getAuthorizationID !=null) { authorizationID = (String)getAuthorizationID.invoke(request,(Object[])null); log.debug("SRMServerV2."+requestName+"() : authorization id"+authorizationID); } } catch(Exception e){ log.error("getting authorization id failed",e); //do nothing here, just do not use authorizattion id in the following code } RequestUser user = null; UserCredential userCred = null; RequestCredential requestCredential = null; try { userCred = srmAuth.getUserCredentials(); Collection roles = SrmAuthorizer.getFQANsFromContext((ExtendedGSSContext) userCred.context); String role = roles.isEmpty() ? null : (String) roles.toArray()[0]; log.debug("SRMServerV2."+requestName+"() : role is "+role); requestCredential = srmAuth.getRequestCredential(userCred,role); user = srmAuth.getRequestUser( requestCredential, (String) null, userCred.context); } catch (SRMAuthorizationException sae) { log.error("SRM Authorization failed", sae); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_AUTHENTICATION_FAILURE, - "SRM Authentication failed :"+sae); + "SRM Authentication failed"); } log.debug("About to call SRMServerV2"+requestName+"()"); Class handlerClass; Constructor handlerConstructor; Object handler; Method handleGetResponseMethod; try { handlerClass = Class.forName("org.dcache.srm.handler."+ capitalizedRequestName); handlerConstructor = handlerClass.getConstructor(new Class[]{RequestUser.class, RequestCredential.class, requestClass, AbstractStorageElement.class, SRM.class, String.class}); handler = handlerConstructor.newInstance(new Object[] { user, requestCredential, request, storage, srmConn.getSrm(), userCred.clientHost }); handleGetResponseMethod = handlerClass.getMethod("getResponse",(Class[])null); } catch(Exception e) { log.error("handler discovery and dinamic load failed", e); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_NOT_SUPPORTED, "can not find a handler, not implemented"); } try { Object response = handleGetResponseMethod.invoke(handler,(Object[])null); return response; } catch(Exception e) { log.fatal("handler invocation failed",e); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_FAILURE, "handler invocation failed"+ e); } } catch(Exception e) { log.fatal(" handleRequest: ",e); try{ return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_INTERNAL_ERROR, "internal error: "+ e); } catch(Exception ee){ throw new RemoteException("SRMServerV2."+requestName+"() exception",e); } } } private Object getFailedResponse(String capitalizedRequestName, TStatusCode statusCode, String errorMessage) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { Class responseClass = Class.forName("org.dcache.srm.v2_2."+capitalizedRequestName+"Response"); Constructor responseConstructor = responseClass.getConstructor((Class[])null); Object response = responseConstructor.newInstance((Object[])null); try { TReturnStatus trs = new TReturnStatus(statusCode,errorMessage ); Method setReturnStatus = responseClass.getMethod("setReturnStatus",new Class[]{TReturnStatus.class}); setReturnStatus.invoke(response, new Object[]{trs}); } catch (java.lang.NoSuchMethodException nsme) { // A hack to handle SrmPingResponse which does not have "setReturnStatus" method // I put it here cause it will go away as soon as this method is present // (by Dmitry Litvintsev ([email protected])) log.fatal("getFailedResponse invocation failed for "+capitalizedRequestName+"Response.setReturnStatus"); if (capitalizedRequestName.equals("SrmPing")) { Class handlerClass = Class.forName("org.dcache.srm.handler."+capitalizedRequestName); Method getFailedRespose = handlerClass.getMethod("getFailedResponse",new Class[]{String.class}); return getFailedRespose.invoke(null,new Object[]{errorMessage}); } } catch(Exception e) { log.fatal("getFailedResponse invocation failed",e); Method setStatusCode = responseClass.getMethod("setStatusCode",new Class[]{TStatusCode.class}); Method setExplanation = responseClass.getMethod("setExplanation",new Class[]{String.class}); setStatusCode.invoke(response, new Object[]{statusCode}); setExplanation.invoke(response, new Object[]{errorMessage}); } return response; } public SrmReserveSpaceResponse srmReserveSpace( SrmReserveSpaceRequest srmReserveSpaceRequest) throws java.rmi.RemoteException { return (SrmReserveSpaceResponse) handleRequest("srmReserveSpace",srmReserveSpaceRequest); } public SrmReleaseSpaceResponse srmReleaseSpace( SrmReleaseSpaceRequest srmReleaseSpaceRequest) throws java.rmi.RemoteException { return (SrmReleaseSpaceResponse) handleRequest("srmReleaseSpace",srmReleaseSpaceRequest); } public SrmUpdateSpaceResponse srmUpdateSpace( SrmUpdateSpaceRequest srmUpdateSpaceRequest) throws java.rmi.RemoteException { return (SrmUpdateSpaceResponse) handleRequest("srmUpdateSpace",srmUpdateSpaceRequest); } public SrmGetSpaceMetaDataResponse srmGetSpaceMetaData( SrmGetSpaceMetaDataRequest srmGetSpaceMetaDataRequest) throws java.rmi.RemoteException { return (SrmGetSpaceMetaDataResponse) handleRequest("srmGetSpaceMetaData",srmGetSpaceMetaDataRequest); } public SrmSetPermissionResponse srmSetPermission( SrmSetPermissionRequest srmSetPermissionRequest) throws java.rmi.RemoteException { return (SrmSetPermissionResponse) handleRequest("srmSetPermission",srmSetPermissionRequest); } public SrmCheckPermissionResponse srmCheckPermission( SrmCheckPermissionRequest srmCheckPermissionRequest) throws java.rmi.RemoteException { return (SrmCheckPermissionResponse) handleRequest("srmCheckPermission",srmCheckPermissionRequest); } public SrmMkdirResponse srmMkdir( SrmMkdirRequest request) throws java.rmi.RemoteException { return (SrmMkdirResponse) handleRequest("srmMkdir",request); } public SrmRmdirResponse srmRmdir( SrmRmdirRequest request) throws java.rmi.RemoteException { return (SrmRmdirResponse) handleRequest("srmRmdir",request); } public SrmCopyResponse srmCopy(SrmCopyRequest request) throws java.rmi.RemoteException { return (SrmCopyResponse) handleRequest("srmCopy",request); } public SrmRmResponse srmRm(SrmRmRequest request) throws java.rmi.RemoteException { return (SrmRmResponse) handleRequest("srmRm",request); } public SrmLsResponse srmLs(SrmLsRequest srmLsRequest) throws java.rmi.RemoteException { return (SrmLsResponse)handleRequest("srmLs",srmLsRequest); } public SrmMvResponse srmMv(SrmMvRequest request) throws java.rmi.RemoteException { return (SrmMvResponse) handleRequest("srmMv",request); } public SrmPrepareToGetResponse srmPrepareToGet( SrmPrepareToGetRequest srmPrepareToGetRequest) throws java.rmi.RemoteException { return (SrmPrepareToGetResponse) handleRequest("srmPrepareToGet",srmPrepareToGetRequest); } public SrmPrepareToPutResponse srmPrepareToPut( SrmPrepareToPutRequest srmPrepareToPutRequest) throws java.rmi.RemoteException { return (SrmPrepareToPutResponse) handleRequest("srmPrepareToPut",srmPrepareToPutRequest); } public SrmReleaseFilesResponse srmReleaseFiles( SrmReleaseFilesRequest srmReleaseFilesRequest) throws java.rmi.RemoteException { return (SrmReleaseFilesResponse) handleRequest("srmReleaseFiles",srmReleaseFilesRequest); } public SrmPutDoneResponse srmPutDone( SrmPutDoneRequest srmPutDoneRequest) throws java.rmi.RemoteException { return (SrmPutDoneResponse) handleRequest("srmPutDone",srmPutDoneRequest); } public SrmAbortRequestResponse srmAbortRequest( SrmAbortRequestRequest srmAbortRequestRequest) throws java.rmi.RemoteException { return (SrmAbortRequestResponse) handleRequest("srmAbortRequest",srmAbortRequestRequest); } public SrmAbortFilesResponse srmAbortFiles( SrmAbortFilesRequest srmAbortFilesRequest) throws java.rmi.RemoteException { return (SrmAbortFilesResponse) handleRequest("srmAbortFiles",srmAbortFilesRequest); } public SrmSuspendRequestResponse srmSuspendRequest( SrmSuspendRequestRequest srmSuspendRequestRequest) throws java.rmi.RemoteException { return (SrmSuspendRequestResponse) handleRequest("srmSuspendRequest",srmSuspendRequestRequest); } public SrmResumeRequestResponse srmResumeRequest( SrmResumeRequestRequest srmResumeRequestRequest) throws java.rmi.RemoteException { return (SrmResumeRequestResponse) handleRequest("srmResumeRequest",srmResumeRequestRequest); } public SrmStatusOfGetRequestResponse srmStatusOfGetRequest( SrmStatusOfGetRequestRequest srmStatusOfGetRequestRequest) throws java.rmi.RemoteException { return (SrmStatusOfGetRequestResponse) handleRequest("srmStatusOfGetRequest",srmStatusOfGetRequestRequest); } public SrmStatusOfPutRequestResponse srmStatusOfPutRequest( SrmStatusOfPutRequestRequest srmStatusOfPutRequestRequest) throws java.rmi.RemoteException { return (SrmStatusOfPutRequestResponse) handleRequest("srmStatusOfPutRequest",srmStatusOfPutRequestRequest); } public SrmStatusOfCopyRequestResponse srmStatusOfCopyRequest( SrmStatusOfCopyRequestRequest request) throws java.rmi.RemoteException { return (SrmStatusOfCopyRequestResponse) handleRequest("srmStatusOfCopyRequest",request); } public SrmGetRequestSummaryResponse srmGetRequestSummary( SrmGetRequestSummaryRequest srmGetRequestSummaryRequest) throws java.rmi.RemoteException { return (SrmGetRequestSummaryResponse) handleRequest("srmGetRequestSummary",srmGetRequestSummaryRequest); } public SrmExtendFileLifeTimeResponse srmExtendFileLifeTime( SrmExtendFileLifeTimeRequest srmExtendFileLifeTimeRequest) throws java.rmi.RemoteException { return (SrmExtendFileLifeTimeResponse) handleRequest("srmExtendFileLifeTime",srmExtendFileLifeTimeRequest); } public SrmStatusOfBringOnlineRequestResponse srmStatusOfBringOnlineRequest(SrmStatusOfBringOnlineRequestRequest srmStatusOfBringOnlineRequestRequest) throws RemoteException { return (SrmStatusOfBringOnlineRequestResponse) handleRequest("srmStatusOfBringOnlineRequest",srmStatusOfBringOnlineRequestRequest); } public SrmBringOnlineResponse srmBringOnline(SrmBringOnlineRequest srmBringOnlineRequest) throws RemoteException { return (SrmBringOnlineResponse) handleRequest("srmBringOnline",srmBringOnlineRequest); } public SrmExtendFileLifeTimeInSpaceResponse srmExtendFileLifeTimeInSpace(SrmExtendFileLifeTimeInSpaceRequest srmExtendFileLifeTimeInSpaceRequest) throws RemoteException { return (SrmExtendFileLifeTimeInSpaceResponse) handleRequest("srmExtendFileLifeTimeInSpace",srmExtendFileLifeTimeInSpaceRequest); } public SrmStatusOfUpdateSpaceRequestResponse srmStatusOfUpdateSpaceRequest(SrmStatusOfUpdateSpaceRequestRequest srmStatusOfUpdateSpaceRequestRequest) throws RemoteException { return (SrmStatusOfUpdateSpaceRequestResponse) handleRequest("srmStatusOfUpdateSpaceRequest",srmStatusOfUpdateSpaceRequestRequest); } public SrmPurgeFromSpaceResponse srmPurgeFromSpace(SrmPurgeFromSpaceRequest srmPurgeFromSpaceRequest) throws RemoteException { return (SrmPurgeFromSpaceResponse) handleRequest("srmPurgeFromSpace",srmPurgeFromSpaceRequest); } public SrmPingResponse srmPing(SrmPingRequest srmPingRequest) throws RemoteException { return (SrmPingResponse) handleRequest("srmPing",srmPingRequest); } public SrmGetPermissionResponse srmGetPermission(SrmGetPermissionRequest srmGetPermissionRequest) throws RemoteException { return (SrmGetPermissionResponse) handleRequest("srmGetPermission",srmGetPermissionRequest); } public SrmStatusOfReserveSpaceRequestResponse srmStatusOfReserveSpaceRequest(SrmStatusOfReserveSpaceRequestRequest srmStatusOfReserveSpaceRequestRequest) throws RemoteException { return (SrmStatusOfReserveSpaceRequestResponse) handleRequest("srmStatusOfReserveSpaceRequest",srmStatusOfReserveSpaceRequestRequest); } public SrmChangeSpaceForFilesResponse srmChangeSpaceForFiles(SrmChangeSpaceForFilesRequest srmChangeSpaceForFilesRequest) throws RemoteException { return (SrmChangeSpaceForFilesResponse) handleRequest("srmChangeSpaceForFiles",srmChangeSpaceForFilesRequest); } public SrmGetTransferProtocolsResponse srmGetTransferProtocols(SrmGetTransferProtocolsRequest srmGetTransferProtocolsRequest) throws RemoteException { return (SrmGetTransferProtocolsResponse) handleRequest("srmGetTransferProtocols",srmGetTransferProtocolsRequest); } public SrmGetRequestTokensResponse srmGetRequestTokens(SrmGetRequestTokensRequest srmGetRequestTokensRequest) throws RemoteException { return (SrmGetRequestTokensResponse) handleRequest("srmGetRequestTokens",srmGetRequestTokensRequest); } public SrmGetSpaceTokensResponse srmGetSpaceTokens(SrmGetSpaceTokensRequest srmGetSpaceTokensRequest) throws RemoteException { return (SrmGetSpaceTokensResponse) handleRequest("srmGetSpaceTokens",srmGetSpaceTokensRequest); } public SrmStatusOfChangeSpaceForFilesRequestResponse srmStatusOfChangeSpaceForFilesRequest(SrmStatusOfChangeSpaceForFilesRequestRequest srmStatusOfChangeSpaceForFilesRequestRequest) throws RemoteException { return (SrmStatusOfChangeSpaceForFilesRequestResponse) handleRequest("srmStatusOfChangeSpaceForFilesRequest",srmStatusOfChangeSpaceForFilesRequestRequest); } public SrmStatusOfLsRequestResponse srmStatusOfLsRequest(SrmStatusOfLsRequestRequest srmStatusOfLsRequestRequest) throws RemoteException { return (SrmStatusOfLsRequestResponse) handleRequest("srmStatusOfLsRequest",srmStatusOfLsRequestRequest); } }
true
true
private Object handleRequest(String requestName, Object request) throws RemoteException { String capitalizedRequestName = Character.toUpperCase(requestName.charAt(0))+ requestName.substring(1); try { Class requestClass = request.getClass(); log.debug("Entering SRMServerV2."+requestName+"()"); String authorizationID = null; try { Method getAuthorizationID = requestClass.getMethod("getAuthorizationID",(Class[])null); if(getAuthorizationID !=null) { authorizationID = (String)getAuthorizationID.invoke(request,(Object[])null); log.debug("SRMServerV2."+requestName+"() : authorization id"+authorizationID); } } catch(Exception e){ log.error("getting authorization id failed",e); //do nothing here, just do not use authorizattion id in the following code } RequestUser user = null; UserCredential userCred = null; RequestCredential requestCredential = null; try { userCred = srmAuth.getUserCredentials(); Collection roles = SrmAuthorizer.getFQANsFromContext((ExtendedGSSContext) userCred.context); String role = roles.isEmpty() ? null : (String) roles.toArray()[0]; log.debug("SRMServerV2."+requestName+"() : role is "+role); requestCredential = srmAuth.getRequestCredential(userCred,role); user = srmAuth.getRequestUser( requestCredential, (String) null, userCred.context); } catch (SRMAuthorizationException sae) { log.error("SRM Authorization failed", sae); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_AUTHENTICATION_FAILURE, "SRM Authentication failed :"+sae); } log.debug("About to call SRMServerV2"+requestName+"()"); Class handlerClass; Constructor handlerConstructor; Object handler; Method handleGetResponseMethod; try { handlerClass = Class.forName("org.dcache.srm.handler."+ capitalizedRequestName); handlerConstructor = handlerClass.getConstructor(new Class[]{RequestUser.class, RequestCredential.class, requestClass, AbstractStorageElement.class, SRM.class, String.class}); handler = handlerConstructor.newInstance(new Object[] { user, requestCredential, request, storage, srmConn.getSrm(), userCred.clientHost }); handleGetResponseMethod = handlerClass.getMethod("getResponse",(Class[])null); } catch(Exception e) { log.error("handler discovery and dinamic load failed", e); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_NOT_SUPPORTED, "can not find a handler, not implemented"); } try { Object response = handleGetResponseMethod.invoke(handler,(Object[])null); return response; } catch(Exception e) { log.fatal("handler invocation failed",e); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_FAILURE, "handler invocation failed"+ e); } } catch(Exception e) { log.fatal(" handleRequest: ",e); try{ return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_INTERNAL_ERROR, "internal error: "+ e); } catch(Exception ee){ throw new RemoteException("SRMServerV2."+requestName+"() exception",e); } } }
private Object handleRequest(String requestName, Object request) throws RemoteException { String capitalizedRequestName = Character.toUpperCase(requestName.charAt(0))+ requestName.substring(1); try { Class requestClass = request.getClass(); log.debug("Entering SRMServerV2."+requestName+"()"); String authorizationID = null; try { Method getAuthorizationID = requestClass.getMethod("getAuthorizationID",(Class[])null); if(getAuthorizationID !=null) { authorizationID = (String)getAuthorizationID.invoke(request,(Object[])null); log.debug("SRMServerV2."+requestName+"() : authorization id"+authorizationID); } } catch(Exception e){ log.error("getting authorization id failed",e); //do nothing here, just do not use authorizattion id in the following code } RequestUser user = null; UserCredential userCred = null; RequestCredential requestCredential = null; try { userCred = srmAuth.getUserCredentials(); Collection roles = SrmAuthorizer.getFQANsFromContext((ExtendedGSSContext) userCred.context); String role = roles.isEmpty() ? null : (String) roles.toArray()[0]; log.debug("SRMServerV2."+requestName+"() : role is "+role); requestCredential = srmAuth.getRequestCredential(userCred,role); user = srmAuth.getRequestUser( requestCredential, (String) null, userCred.context); } catch (SRMAuthorizationException sae) { log.error("SRM Authorization failed", sae); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_AUTHENTICATION_FAILURE, "SRM Authentication failed"); } log.debug("About to call SRMServerV2"+requestName+"()"); Class handlerClass; Constructor handlerConstructor; Object handler; Method handleGetResponseMethod; try { handlerClass = Class.forName("org.dcache.srm.handler."+ capitalizedRequestName); handlerConstructor = handlerClass.getConstructor(new Class[]{RequestUser.class, RequestCredential.class, requestClass, AbstractStorageElement.class, SRM.class, String.class}); handler = handlerConstructor.newInstance(new Object[] { user, requestCredential, request, storage, srmConn.getSrm(), userCred.clientHost }); handleGetResponseMethod = handlerClass.getMethod("getResponse",(Class[])null); } catch(Exception e) { log.error("handler discovery and dinamic load failed", e); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_NOT_SUPPORTED, "can not find a handler, not implemented"); } try { Object response = handleGetResponseMethod.invoke(handler,(Object[])null); return response; } catch(Exception e) { log.fatal("handler invocation failed",e); return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_FAILURE, "handler invocation failed"+ e); } } catch(Exception e) { log.fatal(" handleRequest: ",e); try{ return getFailedResponse(capitalizedRequestName, TStatusCode.SRM_INTERNAL_ERROR, "internal error: "+ e); } catch(Exception ee){ throw new RemoteException("SRMServerV2."+requestName+"() exception",e); } } }
diff --git a/apps/animaldb/convertors/ulidb/ConvertUliDbToPheno.java b/apps/animaldb/convertors/ulidb/ConvertUliDbToPheno.java index e9332c483..fe720e285 100644 --- a/apps/animaldb/convertors/ulidb/ConvertUliDbToPheno.java +++ b/apps/animaldb/convertors/ulidb/ConvertUliDbToPheno.java @@ -1,684 +1,689 @@ package convertors.ulidb; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.log4j.Logger; import org.molgenis.animaldb.NamePrefix; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; import org.molgenis.framework.security.Login; import org.molgenis.organization.Investigation; import org.molgenis.pheno.Individual; import org.molgenis.pheno.ObservedValue; import org.molgenis.pheno.Panel; import org.molgenis.protocol.ProtocolApplication; import org.molgenis.util.CsvFileReader; import org.molgenis.util.CsvReaderListener; import org.molgenis.util.Tuple; import commonservice.CommonService; public class ConvertUliDbToPheno { private Database db; private CommonService ct; private Login login; private Logger logger; private String userName; private String invName; private List<ProtocolApplication> protocolAppsToAddList; private List<Individual> animalsToAddList; private List<String> animalNames; private List<ObservedValue> valuesToAddList; private List<Panel> panelsToAddList; private Map<String, String> oldUliDbIdMap; private Map<String, String> appMap; private Calendar calendar; private SimpleDateFormat dbFormat = new SimpleDateFormat("d-M-yyyy H:mm", Locale.US); private SimpleDateFormat dateOnlyFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US); //private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MMMM d, yyyy, HH:mm:ss", Locale.US); private Map<String, Integer> parentgroupNrMap; private Map<String, Integer> litterNrMap; private int highestNr = 0; public ConvertUliDbToPheno(Database db, Login login) throws Exception { calendar = Calendar.getInstance(); this.db = db; this.login = login; ct = CommonService.getInstance(); ct.setDatabase(this.db); ct.makeObservationTargetNameMap(login.getUserId(), false); logger = Logger.getLogger("LoadUliDb"); userName = login.getUserName(); // If needed, make investigation invName = "UliEiselLegacyImport"; if (ct.getInvestigationId(invName) == -1) { Investigation newInv = new Investigation(); newInv.setName(invName); newInv.setOwns_Name(userName); db.add(newInv); } // Init lists that we can later add to the DB at once protocolAppsToAddList = new ArrayList<ProtocolApplication>(); animalsToAddList = new ArrayList<Individual>(); animalNames = new ArrayList<String>(); valuesToAddList = new ArrayList<ObservedValue>(); panelsToAddList = new ArrayList<Panel>(); oldUliDbIdMap = new HashMap<String, String>(); appMap = new HashMap<String, String>(); parentgroupNrMap = new HashMap<String, Integer>(); litterNrMap = new HashMap<String, Integer>(); } public void writeToDb() { try { db.add(protocolAppsToAddList); logger.debug("Protocols successfully added"); db.add(animalsToAddList); // Make entry in name prefix table with highest animal nr. (Tiernummer) NamePrefix namePrefix = new NamePrefix(); namePrefix.setUserId_Name(userName); namePrefix.setTargetType("animal"); namePrefix.setPrefix(""); namePrefix.setHighestNumber(highestNr); db.add(namePrefix); logger.debug("Animals successfully added"); db.add(panelsToAddList); // Make entries in name prefix table with highest parentgroup nrs. for (String lineName : parentgroupNrMap.keySet()) { namePrefix = new NamePrefix(); namePrefix.setUserId_Name(userName); namePrefix.setTargetType("parentgroup"); namePrefix.setPrefix("PG_" + lineName + "_"); namePrefix.setHighestNumber(parentgroupNrMap.get(lineName)); db.add(namePrefix); } // Make entries in name prefix table with highest litter nrs. for (String lineName : litterNrMap.keySet()) { namePrefix = new NamePrefix(); namePrefix.setUserId_Name(userName); namePrefix.setTargetType("litter"); namePrefix.setPrefix("LT_" + lineName + "_"); namePrefix.setHighestNumber(litterNrMap.get(lineName)); db.add(namePrefix); } logger.debug("Panels successfully added"); for (int valueStart = 0; valueStart < valuesToAddList.size(); valueStart += 1000) { int valueEnd = Math.min(valuesToAddList.size(), valueStart + 1000); db.add(valuesToAddList.subList(valueStart, valueEnd)); logger.debug("Values " + valueStart + " through " + valueEnd + " successfully added"); } } catch (Exception e) { logger.error("Writing to DB failed: " + e.getMessage()); e.printStackTrace(); } } public void populateAnimal(String filename) throws Exception { File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { // Tiernummer -> make new animal String animalName = tuple.getString("Tiernummer"); // Store highest animal nr. for later storage in name prefix table try { int animalNr = Integer.parseInt(animalName); if (animalNr > highestNr) { highestNr = animalNr; } } catch (NumberFormatException e) { // Not a parseable animal nr.: ignore } // Deal with empty names (of which there are a few in Uli's DB if (animalName == null) { animalName = "OldUliId_" + tuple.getString("laufende Nr"); } else { // Prepend 0's to name animalName = ct.prependZeros(animalName, 6); } // Make sure we have a unique name while (animalNames.contains(animalName)) { animalName = ("Dup_" + animalName); } animalNames.add(animalName); Individual newAnimal = ct.createIndividual(invName, animalName, userName); animalsToAddList.add(newAnimal); } }); } public void populateProtocolApplication() throws Exception { makeProtocolApplication("SetOldUliDbId"); makeProtocolApplication("SetSpecies"); makeProtocolApplication("SetAnimalType"); makeProtocolApplication("SetActive"); makeProtocolApplication("SetDateOfBirth"); makeProtocolApplication("SetDeathDate"); makeProtocolApplication("SetSource"); //makeProtocolApplication("SetOldUliDbExperimentator"); //makeProtocolApplication("SetOldUliDbTierschutzrecht"); makeProtocolApplication("SetSex"); makeProtocolApplication("SetColor"); makeProtocolApplication("SetEarmark"); makeProtocolApplication("SetGenotype", "SetGenotype1"); makeProtocolApplication("SetGenotype", "SetGenotype2"); makeProtocolApplication("SetBackground"); makeProtocolApplication("SetOldUliDbMotherInfo"); makeProtocolApplication("SetOldUliDbFatherInfo"); makeProtocolApplication("SetTypeOfGroup"); makeProtocolApplication("SetMother"); makeProtocolApplication("SetFather"); //makeProtocolApplication("SetLine"); makeProtocolApplication("SetParentgroup"); makeProtocolApplication("SetLitter"); makeProtocolApplication("SetLine"); makeProtocolApplication("SetWeanDate"); makeProtocolApplication("SetGenotypeDate"); } public void populateValue(String filename) throws Exception { final String speciesName = "House mouse"; File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { Date now = calendar.getTime(); String newAnimalName = animalsToAddList.get(line_number - 1).getName(); // laufende Nr -> OldUliDbId String oldUliDbId = tuple.getString("laufende Nr"); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbId"), now, null, "OldUliDbId", newAnimalName, oldUliDbId, null)); oldUliDbIdMap.put(oldUliDbId, newAnimalName); // Tierkategorie -> Species (always Mus musculus) valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSpecies"), now, null, "Species", newAnimalName, null, speciesName)); // AnimalType (always "B. Transgeen dier") valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetAnimalType"), now, null, "AnimalType", newAnimalName, "B. Transgeen dier", null)); // Eingangsdatum, Abgangsdatum and Status -> // DateOfBirth, DeathDate and Active + start and end time String startDateString = tuple.getString("Eingangsdatum"); Date startDate = null; if (startDateString != null) { startDate = dbFormat.parse(startDateString); String dateOfBirth = dateOnlyFormat.format(startDate); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetDateOfBirth"), startDate, null, "DateOfBirth", newAnimalName, dateOfBirth, null)); } String endDateString = tuple.getString("Abgangsdatum"); Date endDate = null; if (endDateString != null) { endDate = dbFormat.parse(endDateString); String dateOfDeath = dateOnlyFormat.format(endDate); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetDeathDate"), startDate, null, "DeathDate", newAnimalName, dateOfDeath, null)); } String state = tuple.getString("Status"); if (state != null) { if (state.equals("lebt")) { state = "Alive"; } else { state = "Dead"; } valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetActive"), startDate, endDate, "Active", newAnimalName, state, null)); } // Herkunft -> Source Integer uliSourceId = tuple.getInt("Herkunft"); if (uliSourceId != null) { String sourceName = null; if (uliSourceId == 51 || uliSourceId == 52) { // 51: Zucht- oder Liefereinrichtung innerhalb Deutschlands, die f�r ihre T�tigkeit eine Erlaubnis nach � 11 Abs. 1 Satz 1 Nr. 1 des Tierschutzgesetzes erhalten hat // 52: andere amtlich registrierte oder zugelassene Einrichtung innerhalb der EU // --> SourceType for both: Van EU-lid-staten sourceName = "UliEisel51and52"; } if (uliSourceId == 55) { // 55: Switserland // --> SourceType: Andere herkomst sourceName = "UliEisel55"; } if (uliSourceId != 0) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSource"), now, null, "Source", newAnimalName, null, sourceName)); } } // not needed, skip import (update ate @ 2011-09-20) // K�rzel -> OldUliDbKuerzel /* * String kuerzel = tuple.getString("K�rzel"); * if (kuerzel != null) { * valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbKuerzel"), * now, null, "OldUliDbKuerzel", newAnimalName, kuerzel, null)); * } */ // Bemerkungen -> Remark String remark = tuple.getString("Bemerkungen"); if (remark != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetRemark"), now, null, "Remark", newAnimalName, remark, null)); } // not needed, skip import (update ate @ 2011-09-20) /*// Aktenzeichen -> OldUliDbAktenzeichen String aktenzeichen = tuple.getString("Aktenzeichen"); if (aktenzeichen != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbAktenzeichen"), now, null, "OldUliDbAktenzeichen", newAnimalName, aktenzeichen, null)); }*/ // not needed, skip import (update ate @ 2011-09-20) /*// Experimentator -> OldUliDbExperimentator String experimentator = tuple.getString("Experimentator"); if (experimentator != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbExperimentator"), now, null, "OldUliDbExperimentator", newAnimalName, experimentator, null)); }*/ // not needed, skip import (update ate @ 2011-09-20) // Tierschutzrecht -> OldUliDbTierschutzrecht // TODO: actually this corresponds to Goal, but in AnimalDB that is linked // to a DEC subproject (Experiment) instead of to the individual animals. // For now, store in OldUliDbTierschutzrecht. /*String tierschutzrecht = tuple.getString("Tierschutzrecht"); if (tierschutzrecht != null) {; valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbTierschutzrecht"), now, null, "OldUliDbTierschutzrecht", newAnimalName, tierschutzrecht, null)); }*/ // BeschrGeschlecht -> Sex String sex = tuple.getString("BeschrGeschlecht"); if (sex != null) { String sexName; if (sex.equals("w")) { sexName = "Female"; } else { sexName = "Male"; } valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSex"), now, null, "Sex", newAnimalName, null, sexName)); } // Farbe -> Color String color = tuple.getString("Farbe"); if (color != null) { String colorName = null; if (color.equals("beige")) colorName = "beige"; if (color.equals("braun")) colorName = "brown"; if (color.equals("gelb")) colorName = "yellow"; if (color.equals("grau")) colorName = "gray"; if (color.equals("grau-braun")) colorName = "gray-brown"; if (color.equals("rotbraun")) colorName = "red-brown"; if (color.equals("schwarz")) colorName = "black"; if (color.equals("Schwarz-braun")) colorName = "black-brown"; if (color.equals("schwarz-gray")) colorName = "black-gray"; if (color.equals("weiss")) colorName = "white"; if (color.equals("zimt")) colorName = "cinnamon"; valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetColor"), now, null, "Color", newAnimalName, colorName, null)); } // Ohrmarkierung1 -> Earmark String earmark = tuple.getString("Ohrmarkierung1"); if (earmark != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetEarmark"), now, null, "Earmark", newAnimalName, earmark, null)); } // Gen and tg -> Gene and GeneState (in one or more SetGenotype protocol applications) String geneName = tuple.getString("Gen"); if (geneName == null) { geneName = "unknown"; } String geneState = tuple.getString("tg"); // Allowed flavors: -/- +/- +/+ ntg wt unknown transgenic + // First do some normalization if (geneState == null || geneState.equals("Unknown")) { geneState = "unknown"; } - logger.info(geneState); + if (geneState.equals("WT")) { + geneState = "wt"; + } logger.debug(geneState); + // Then check if geneState is singular or double if (!geneState.equals("+/+") && !geneState.equals("+/-") && !geneState.equals("-/-") && - !geneState.equals("ntg") && !geneState.equals("transgenic") && !geneState.equals("Unknown") && !geneState.equals("WT")) { + !geneState.equals("ntg") && !geneState.equals("transgenic") && !geneState.equals("unknown") && + !geneState.equals("wt")) { // Double geneState, so split (first 3 chars and last 3 chars, ignoring all the spaces and slashes in between) String geneState1 = geneState.substring(0, 3); String geneState2 = geneState.substring(geneState.length() - 3, geneState.length()); // Try to split geneName, on slash (if present) - // TODO: find out if this is OK! + // TODO: find out from Uli if this is OK! String geneName1 = geneName; String geneName2 = geneName; String[] geneNames = geneName.split("/"); if (geneNames.length == 2) { geneName1 = geneNames[0]; geneName2 = geneNames[1]; } // Add to values list valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneName", newAnimalName, geneName1, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneState", newAnimalName, geneState1, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype2"), now, null, "GeneName", newAnimalName, geneName2, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype2"), now, null, "GeneState", newAnimalName, geneState2, null)); } else { // geneName and geneState can remain as is valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneName", newAnimalName, geneName, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneState", newAnimalName, geneState, null)); } // gen Hintergrund-Tier -> Background String background = tuple.getString("gen Hintergrund-Tier"); if (background != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetBackground"), now, null, "Background", newAnimalName, null, background)); } } }); } public void parseParentRelations(String filename) throws Exception { final Map<String, String> litterMap = new HashMap<String, String>(); File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { Date now = calendar.getTime(); String newAnimalName = animalsToAddList.get(line_number - 1).getName(); // Eingangsdatum -> DateOfBirth String birthDateString = tuple.getString("Eingangsdatum"); String weanDate = null; if (birthDateString != null) { Date birthDate = dbFormat.parse(birthDateString); weanDate = dateOnlyFormat.format(birthDate); } // Mutter-Nr -> Mother List<String> motherList = new ArrayList<String>(); String motherIdsString = tuple.getString("Mutter-Nr"); if (motherIdsString != null) { // First, store literal value valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbMotherInfo"), now, null, "OldUliDbMotherInfo", newAnimalName, motherIdsString, null)); for (Integer oldMotherId : SplitParentIdsString(motherIdsString)) { // Find corresponding animal // If 5 digits, it's a laufende Nr (OldUliDbId); if fewer, it's a Tiernummer (name) String motherName = null; if (oldMotherId.toString().length() == 5) { motherName = oldUliDbIdMap.get(oldMotherId.toString()); } else { int idx = animalNames.indexOf(oldMotherId.toString()); if (idx != -1) { motherName = animalNames.get(idx); } } if (motherName != null) { motherList.add(motherName); } } } // Vater-Nr -> Father List<String> fatherList = new ArrayList<String>(); String fatherIdsString = tuple.getString("Vater-Nr"); if (fatherIdsString != null) { // First, store literal value valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbFatherInfo"), now, null, "OldUliDbFatherInfo", newAnimalName, fatherIdsString, null)); for (Integer oldFatherId : SplitParentIdsString(fatherIdsString)) { // Find corresponding animal // If 5 digits, it's a laufende Nr (OldUliDbId); if fewer, it's a Tiernummer (name) String fatherName = null; if (oldFatherId.toString().length() == 5) { fatherName = oldUliDbIdMap.get(oldFatherId.toString()); } else { int idx = animalNames.indexOf(oldFatherId.toString()); if (idx != -1) { fatherName = animalNames.get(idx); } } if (fatherName != null) { fatherList.add(fatherName); } } } // Put date of birth, mother info and father info into one string and check if we've // seen this combination before String litterInfo = birthDateString + motherList.toString() + fatherList.toString(); if (litterMap.containsKey(litterInfo)) { // This combination of birth date and parents has been seen before, // so retrieve litter and link animal directly to it valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetLitter"), now, null, "Litter", newAnimalName, null, litterMap.get(litterInfo))); } else { // This combination of birth date and parents has not been seen before, // so start a new parentgroup and litter String lineName = tuple.getString("Linie"); // Create a parentgroup int parentgroupNr = 1; if (parentgroupNrMap.containsKey(lineName)) { parentgroupNr = parentgroupNrMap.get(lineName) + 1; } parentgroupNrMap.put(lineName, parentgroupNr); String parentgroupNrPart = ct.prependZeros("" + parentgroupNr, 6); String parentgroupName = "PG_" + lineName + "_" + parentgroupNrPart; panelsToAddList.add(ct.createPanel(invName, parentgroupName, userName)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetTypeOfGroup"), now, null, "TypeOfGroup", parentgroupName, "Parentgroup", null)); // Link parent(s) to parentgroup for (String motherName : motherList) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetMother"), now, null, "Mother", motherName, null, parentgroupName)); } for (String fatherName : fatherList) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetFather"), now, null, "Father", fatherName, null, parentgroupName)); } // Set line (Linie) of parentgroup if (lineName != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetLine"), now, null, "Line", parentgroupName, null, lineName)); } // Make a litter and set wean and genotype dates int litterNr = 1; if (litterNrMap.containsKey(lineName)) { litterNr = litterNrMap.get(lineName) + 1; } litterNrMap.put(lineName, litterNr); String litterNrPart = ct.prependZeros("" + litterNr, 6); String litterName = "LT_" + lineName + "_" + litterNrPart; panelsToAddList.add(ct.createPanel(invName, litterName, userName)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetTypeOfGroup"), now, null, "TypeOfGroup", litterName, "Litter", null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetWeanDate"), now, null, "WeanDate", litterName, weanDate, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotypeDate"), now, null, "GenotypeDate", litterName, weanDate, null)); // Link litter to parentgroup valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetParentgroup"), now, null, "Parentgroup", litterName, null, parentgroupName)); // Link animal to litter valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetLitter"), now, null, "Litter", newAnimalName, null, litterName)); // Set litter also on animal valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetLine"), now, null, "Line", newAnimalName, null, lineName)); // Add litter to hashmap for reuse with siblings of this animal litterMap.put(litterInfo, litterName); } } }); } public void populateLine(String filename) throws Exception { final int invid = ct.getInvestigationId(invName); File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); String lineName = tuple.getString("Linie"); // Make line panel int lineId = ct.makePanel(invid, lineName, login.getUserId()); // Label it as line using the (Set)TypeOfGroup protocol and feature int featureId = ct.getMeasurementId("TypeOfGroup"); int protocolId = ct.getProtocolId("SetTypeOfGroup"); db.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, featureId, lineId, "Line", 0)); // Set the source of the line (always 'Kweek moleculaire neurobiologie') featureId = ct.getMeasurementId("Source"); protocolId = ct.getProtocolId("SetSource"); int sourceId = ct.getObservationTargetId("Kweek moleculaire neurobiologie"); db.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, featureId, lineId, null, sourceId)); } }); } public void populateGene(String filename) throws Exception { File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { // Every gene becomes a code for the 'GeneName' feature String geneName = tuple.getString("Gen"); ct.makeCode(geneName, geneName, "GeneName"); } }); } public void populateBackground(String filename) throws Exception { final int featureId = ct.getMeasurementId("TypeOfGroup"); final int protocolId = ct.getProtocolId("SetTypeOfGroup"); final int invid = ct.getInvestigationId(invName); File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); String bkgName = tuple.getString("Genetischer Hintergrund"); if (bkgName != null && ct.getObservationTargetId(bkgName) == -1) { // Make background panel int bkgId = ct.makePanel(invid, bkgName, login.getUserId()); // Label it as background using the (Set)TypeOfGroup protocol and feature db.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, featureId, bkgId, "Background", 0)); } } }); } public List<Integer> SplitParentIdsString(String parentIdsString) { List<Integer> idsList = new ArrayList<Integer>(); // Separators can be: comma + whitespace OR forward slash OR whitespace OR // period + whitespace OR whitespace + plus sign + whitespace String[] ids = parentIdsString.split("[(,\\s)/\\s(\\.\\s)(\\s\\+\\s)]"); for (String idString : ids) { Integer id = 0; try { id = Integer.parseInt(idString); } catch (Exception e) { // } if (id != 0) { // We now know it's a number if (idString.length() == 8) { // Two Tiernummers glued together idsList.add(Integer.parseInt(idString.substring(0, 4))); idsList.add(Integer.parseInt(idString.substring(4, 8))); } else { if (idString.length() == 10) { // Two laufende Nrs glued together idsList.add(Integer.parseInt(idString.substring(0, 5))); idsList.add(Integer.parseInt(idString.substring(5, 10))); } else { idsList.add(id); } } } } return idsList; } public void makeProtocolApplication(String protocolName) throws ParseException, DatabaseException, IOException { makeProtocolApplication(protocolName, protocolName); } public void makeProtocolApplication(String protocolName, String protocolLabel) throws ParseException, DatabaseException, IOException { ProtocolApplication app = ct.createProtocolApplication(invName, protocolName); protocolAppsToAddList.add(app); appMap.put(protocolLabel, app.getName()); } }
false
true
public void populateValue(String filename) throws Exception { final String speciesName = "House mouse"; File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { Date now = calendar.getTime(); String newAnimalName = animalsToAddList.get(line_number - 1).getName(); // laufende Nr -> OldUliDbId String oldUliDbId = tuple.getString("laufende Nr"); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbId"), now, null, "OldUliDbId", newAnimalName, oldUliDbId, null)); oldUliDbIdMap.put(oldUliDbId, newAnimalName); // Tierkategorie -> Species (always Mus musculus) valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSpecies"), now, null, "Species", newAnimalName, null, speciesName)); // AnimalType (always "B. Transgeen dier") valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetAnimalType"), now, null, "AnimalType", newAnimalName, "B. Transgeen dier", null)); // Eingangsdatum, Abgangsdatum and Status -> // DateOfBirth, DeathDate and Active + start and end time String startDateString = tuple.getString("Eingangsdatum"); Date startDate = null; if (startDateString != null) { startDate = dbFormat.parse(startDateString); String dateOfBirth = dateOnlyFormat.format(startDate); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetDateOfBirth"), startDate, null, "DateOfBirth", newAnimalName, dateOfBirth, null)); } String endDateString = tuple.getString("Abgangsdatum"); Date endDate = null; if (endDateString != null) { endDate = dbFormat.parse(endDateString); String dateOfDeath = dateOnlyFormat.format(endDate); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetDeathDate"), startDate, null, "DeathDate", newAnimalName, dateOfDeath, null)); } String state = tuple.getString("Status"); if (state != null) { if (state.equals("lebt")) { state = "Alive"; } else { state = "Dead"; } valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetActive"), startDate, endDate, "Active", newAnimalName, state, null)); } // Herkunft -> Source Integer uliSourceId = tuple.getInt("Herkunft"); if (uliSourceId != null) { String sourceName = null; if (uliSourceId == 51 || uliSourceId == 52) { // 51: Zucht- oder Liefereinrichtung innerhalb Deutschlands, die f�r ihre T�tigkeit eine Erlaubnis nach � 11 Abs. 1 Satz 1 Nr. 1 des Tierschutzgesetzes erhalten hat // 52: andere amtlich registrierte oder zugelassene Einrichtung innerhalb der EU // --> SourceType for both: Van EU-lid-staten sourceName = "UliEisel51and52"; } if (uliSourceId == 55) { // 55: Switserland // --> SourceType: Andere herkomst sourceName = "UliEisel55"; } if (uliSourceId != 0) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSource"), now, null, "Source", newAnimalName, null, sourceName)); } } // not needed, skip import (update ate @ 2011-09-20) // K�rzel -> OldUliDbKuerzel /* * String kuerzel = tuple.getString("K�rzel"); * if (kuerzel != null) { * valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbKuerzel"), * now, null, "OldUliDbKuerzel", newAnimalName, kuerzel, null)); * } */ // Bemerkungen -> Remark String remark = tuple.getString("Bemerkungen"); if (remark != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetRemark"), now, null, "Remark", newAnimalName, remark, null)); } // not needed, skip import (update ate @ 2011-09-20) /*// Aktenzeichen -> OldUliDbAktenzeichen String aktenzeichen = tuple.getString("Aktenzeichen"); if (aktenzeichen != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbAktenzeichen"), now, null, "OldUliDbAktenzeichen", newAnimalName, aktenzeichen, null)); }*/ // not needed, skip import (update ate @ 2011-09-20) /*// Experimentator -> OldUliDbExperimentator String experimentator = tuple.getString("Experimentator"); if (experimentator != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbExperimentator"), now, null, "OldUliDbExperimentator", newAnimalName, experimentator, null)); }*/ // not needed, skip import (update ate @ 2011-09-20) // Tierschutzrecht -> OldUliDbTierschutzrecht // TODO: actually this corresponds to Goal, but in AnimalDB that is linked // to a DEC subproject (Experiment) instead of to the individual animals. // For now, store in OldUliDbTierschutzrecht. /*String tierschutzrecht = tuple.getString("Tierschutzrecht"); if (tierschutzrecht != null) {; valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbTierschutzrecht"), now, null, "OldUliDbTierschutzrecht", newAnimalName, tierschutzrecht, null)); }*/ // BeschrGeschlecht -> Sex String sex = tuple.getString("BeschrGeschlecht"); if (sex != null) { String sexName; if (sex.equals("w")) { sexName = "Female"; } else { sexName = "Male"; } valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSex"), now, null, "Sex", newAnimalName, null, sexName)); } // Farbe -> Color String color = tuple.getString("Farbe"); if (color != null) { String colorName = null; if (color.equals("beige")) colorName = "beige"; if (color.equals("braun")) colorName = "brown"; if (color.equals("gelb")) colorName = "yellow"; if (color.equals("grau")) colorName = "gray"; if (color.equals("grau-braun")) colorName = "gray-brown"; if (color.equals("rotbraun")) colorName = "red-brown"; if (color.equals("schwarz")) colorName = "black"; if (color.equals("Schwarz-braun")) colorName = "black-brown"; if (color.equals("schwarz-gray")) colorName = "black-gray"; if (color.equals("weiss")) colorName = "white"; if (color.equals("zimt")) colorName = "cinnamon"; valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetColor"), now, null, "Color", newAnimalName, colorName, null)); } // Ohrmarkierung1 -> Earmark String earmark = tuple.getString("Ohrmarkierung1"); if (earmark != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetEarmark"), now, null, "Earmark", newAnimalName, earmark, null)); } // Gen and tg -> Gene and GeneState (in one or more SetGenotype protocol applications) String geneName = tuple.getString("Gen"); if (geneName == null) { geneName = "unknown"; } String geneState = tuple.getString("tg"); // Allowed flavors: -/- +/- +/+ ntg wt unknown transgenic if (geneState == null || geneState.equals("Unknown")) { geneState = "unknown"; } logger.info(geneState); logger.debug(geneState); if (!geneState.equals("+/+") && !geneState.equals("+/-") && !geneState.equals("-/-") && !geneState.equals("ntg") && !geneState.equals("transgenic") && !geneState.equals("Unknown") && !geneState.equals("WT")) { // Double geneState, so split (first 3 chars and last 3 chars, ignoring all the spaces and slashes in between) String geneState1 = geneState.substring(0, 3); String geneState2 = geneState.substring(geneState.length() - 3, geneState.length()); // Try to split geneName, on slash (if present) // TODO: find out if this is OK! String geneName1 = geneName; String geneName2 = geneName; String[] geneNames = geneName.split("/"); if (geneNames.length == 2) { geneName1 = geneNames[0]; geneName2 = geneNames[1]; } // Add to values list valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneName", newAnimalName, geneName1, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneState", newAnimalName, geneState1, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype2"), now, null, "GeneName", newAnimalName, geneName2, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype2"), now, null, "GeneState", newAnimalName, geneState2, null)); } else { // geneName and geneState can remain as is valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneName", newAnimalName, geneName, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneState", newAnimalName, geneState, null)); } // gen Hintergrund-Tier -> Background String background = tuple.getString("gen Hintergrund-Tier"); if (background != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetBackground"), now, null, "Background", newAnimalName, null, background)); } } }); }
public void populateValue(String filename) throws Exception { final String speciesName = "House mouse"; File file = new File(filename); CsvFileReader reader = new CsvFileReader(file); reader.parse(new CsvReaderListener() { public void handleLine(int line_number, Tuple tuple) throws DatabaseException, ParseException, IOException { Date now = calendar.getTime(); String newAnimalName = animalsToAddList.get(line_number - 1).getName(); // laufende Nr -> OldUliDbId String oldUliDbId = tuple.getString("laufende Nr"); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbId"), now, null, "OldUliDbId", newAnimalName, oldUliDbId, null)); oldUliDbIdMap.put(oldUliDbId, newAnimalName); // Tierkategorie -> Species (always Mus musculus) valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSpecies"), now, null, "Species", newAnimalName, null, speciesName)); // AnimalType (always "B. Transgeen dier") valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetAnimalType"), now, null, "AnimalType", newAnimalName, "B. Transgeen dier", null)); // Eingangsdatum, Abgangsdatum and Status -> // DateOfBirth, DeathDate and Active + start and end time String startDateString = tuple.getString("Eingangsdatum"); Date startDate = null; if (startDateString != null) { startDate = dbFormat.parse(startDateString); String dateOfBirth = dateOnlyFormat.format(startDate); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetDateOfBirth"), startDate, null, "DateOfBirth", newAnimalName, dateOfBirth, null)); } String endDateString = tuple.getString("Abgangsdatum"); Date endDate = null; if (endDateString != null) { endDate = dbFormat.parse(endDateString); String dateOfDeath = dateOnlyFormat.format(endDate); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetDeathDate"), startDate, null, "DeathDate", newAnimalName, dateOfDeath, null)); } String state = tuple.getString("Status"); if (state != null) { if (state.equals("lebt")) { state = "Alive"; } else { state = "Dead"; } valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetActive"), startDate, endDate, "Active", newAnimalName, state, null)); } // Herkunft -> Source Integer uliSourceId = tuple.getInt("Herkunft"); if (uliSourceId != null) { String sourceName = null; if (uliSourceId == 51 || uliSourceId == 52) { // 51: Zucht- oder Liefereinrichtung innerhalb Deutschlands, die f�r ihre T�tigkeit eine Erlaubnis nach � 11 Abs. 1 Satz 1 Nr. 1 des Tierschutzgesetzes erhalten hat // 52: andere amtlich registrierte oder zugelassene Einrichtung innerhalb der EU // --> SourceType for both: Van EU-lid-staten sourceName = "UliEisel51and52"; } if (uliSourceId == 55) { // 55: Switserland // --> SourceType: Andere herkomst sourceName = "UliEisel55"; } if (uliSourceId != 0) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSource"), now, null, "Source", newAnimalName, null, sourceName)); } } // not needed, skip import (update ate @ 2011-09-20) // K�rzel -> OldUliDbKuerzel /* * String kuerzel = tuple.getString("K�rzel"); * if (kuerzel != null) { * valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbKuerzel"), * now, null, "OldUliDbKuerzel", newAnimalName, kuerzel, null)); * } */ // Bemerkungen -> Remark String remark = tuple.getString("Bemerkungen"); if (remark != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetRemark"), now, null, "Remark", newAnimalName, remark, null)); } // not needed, skip import (update ate @ 2011-09-20) /*// Aktenzeichen -> OldUliDbAktenzeichen String aktenzeichen = tuple.getString("Aktenzeichen"); if (aktenzeichen != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbAktenzeichen"), now, null, "OldUliDbAktenzeichen", newAnimalName, aktenzeichen, null)); }*/ // not needed, skip import (update ate @ 2011-09-20) /*// Experimentator -> OldUliDbExperimentator String experimentator = tuple.getString("Experimentator"); if (experimentator != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbExperimentator"), now, null, "OldUliDbExperimentator", newAnimalName, experimentator, null)); }*/ // not needed, skip import (update ate @ 2011-09-20) // Tierschutzrecht -> OldUliDbTierschutzrecht // TODO: actually this corresponds to Goal, but in AnimalDB that is linked // to a DEC subproject (Experiment) instead of to the individual animals. // For now, store in OldUliDbTierschutzrecht. /*String tierschutzrecht = tuple.getString("Tierschutzrecht"); if (tierschutzrecht != null) {; valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetOldUliDbTierschutzrecht"), now, null, "OldUliDbTierschutzrecht", newAnimalName, tierschutzrecht, null)); }*/ // BeschrGeschlecht -> Sex String sex = tuple.getString("BeschrGeschlecht"); if (sex != null) { String sexName; if (sex.equals("w")) { sexName = "Female"; } else { sexName = "Male"; } valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetSex"), now, null, "Sex", newAnimalName, null, sexName)); } // Farbe -> Color String color = tuple.getString("Farbe"); if (color != null) { String colorName = null; if (color.equals("beige")) colorName = "beige"; if (color.equals("braun")) colorName = "brown"; if (color.equals("gelb")) colorName = "yellow"; if (color.equals("grau")) colorName = "gray"; if (color.equals("grau-braun")) colorName = "gray-brown"; if (color.equals("rotbraun")) colorName = "red-brown"; if (color.equals("schwarz")) colorName = "black"; if (color.equals("Schwarz-braun")) colorName = "black-brown"; if (color.equals("schwarz-gray")) colorName = "black-gray"; if (color.equals("weiss")) colorName = "white"; if (color.equals("zimt")) colorName = "cinnamon"; valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetColor"), now, null, "Color", newAnimalName, colorName, null)); } // Ohrmarkierung1 -> Earmark String earmark = tuple.getString("Ohrmarkierung1"); if (earmark != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetEarmark"), now, null, "Earmark", newAnimalName, earmark, null)); } // Gen and tg -> Gene and GeneState (in one or more SetGenotype protocol applications) String geneName = tuple.getString("Gen"); if (geneName == null) { geneName = "unknown"; } String geneState = tuple.getString("tg"); // Allowed flavors: -/- +/- +/+ ntg wt unknown transgenic // First do some normalization if (geneState == null || geneState.equals("Unknown")) { geneState = "unknown"; } if (geneState.equals("WT")) { geneState = "wt"; } logger.debug(geneState); // Then check if geneState is singular or double if (!geneState.equals("+/+") && !geneState.equals("+/-") && !geneState.equals("-/-") && !geneState.equals("ntg") && !geneState.equals("transgenic") && !geneState.equals("unknown") && !geneState.equals("wt")) { // Double geneState, so split (first 3 chars and last 3 chars, ignoring all the spaces and slashes in between) String geneState1 = geneState.substring(0, 3); String geneState2 = geneState.substring(geneState.length() - 3, geneState.length()); // Try to split geneName, on slash (if present) // TODO: find out from Uli if this is OK! String geneName1 = geneName; String geneName2 = geneName; String[] geneNames = geneName.split("/"); if (geneNames.length == 2) { geneName1 = geneNames[0]; geneName2 = geneNames[1]; } // Add to values list valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneName", newAnimalName, geneName1, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneState", newAnimalName, geneState1, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype2"), now, null, "GeneName", newAnimalName, geneName2, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype2"), now, null, "GeneState", newAnimalName, geneState2, null)); } else { // geneName and geneState can remain as is valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneName", newAnimalName, geneName, null)); valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetGenotype1"), now, null, "GeneState", newAnimalName, geneState, null)); } // gen Hintergrund-Tier -> Background String background = tuple.getString("gen Hintergrund-Tier"); if (background != null) { valuesToAddList.add(ct.createObservedValue(invName, appMap.get("SetBackground"), now, null, "Background", newAnimalName, null, background)); } } }); }
diff --git a/src/main/java/com/relayrides/pushy/apns/FeedbackServiceClient.java b/src/main/java/com/relayrides/pushy/apns/FeedbackServiceClient.java index 896bc686..972374af 100644 --- a/src/main/java/com/relayrides/pushy/apns/FeedbackServiceClient.java +++ b/src/main/java/com/relayrides/pushy/apns/FeedbackServiceClient.java @@ -1,236 +1,236 @@ /* Copyright (c) 2013 RelayRides * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.relayrides.pushy.apns; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.ReplayingDecoder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.ReadTimeoutException; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.util.concurrent.Future; import java.util.Date; import java.util.List; import java.util.Vector; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>A client that communicates with the APNs feedback to retrieve expired device tokens. According to Apple's * documentation:</p> * * <blockquote>The Apple Push Notification Service includes a feedback service to give you information about failed * push notifications. When a push notification cannot be delivered because the intended app does not exist on the * device, the feedback service adds that device's token to its list. Push notifications that expire before being * delivered are not considered a failed delivery and don't impact the feedback service...</blockquote> * * <blockquote>Query the feedback service daily to get the list of device tokens. Use the timestamp to verify that the * device tokens haven't been reregistered since the feedback entry was generated. For each device that has not been * reregistered, stop sending notifications.</blockquote> * * <p>Generally, users of Pushy should <em>not</em> instantiate a {@code FeedbackServiceClient} directly, but should * instead call {@link com.relayrides.pushy.apns.PushManager#getExpiredTokens()}, which will manage the creation * and configuration of a {@code FeedbackServiceClient} internally.</p> * * @author <a href="mailto:[email protected]">Jon Chambers</a> * * @see <a href="http://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3"> * Local and Push Notification Programming Guide - Provider Communication with Apple Push Notification Service - The * Feedback Service</a> */ class FeedbackServiceClient { private final PushManager<? extends ApnsPushNotification> pushManager; private Vector<ExpiredToken> expiredTokens; private final Logger log = LoggerFactory.getLogger(ApnsClientThread.class); private enum ExpiredTokenDecoderState { EXPIRATION, TOKEN_LENGTH, TOKEN } private class ExpiredTokenDecoder extends ReplayingDecoder<ExpiredTokenDecoderState> { private Date expiration; private byte[] token; public ExpiredTokenDecoder() { super(ExpiredTokenDecoderState.EXPIRATION); } @Override protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) { switch (this.state()) { case EXPIRATION: { final long timestamp = (in.readInt() & 0xFFFFFFFFL) * 1000L; this.expiration = new Date(timestamp); this.checkpoint(ExpiredTokenDecoderState.TOKEN_LENGTH); break; } case TOKEN_LENGTH: { this.token = new byte[in.readShort() & 0x0000FFFF]; this.checkpoint(ExpiredTokenDecoderState.TOKEN); break; } case TOKEN: { in.readBytes(this.token); out.add(new ExpiredToken(this.token, this.expiration)); this.checkpoint(ExpiredTokenDecoderState.EXPIRATION); break; } } } } private class FeedbackClientHandler extends SimpleChannelInboundHandler<ExpiredToken> { private final FeedbackServiceClient feedbackClient; public FeedbackClientHandler(final FeedbackServiceClient feedbackClient) { this.feedbackClient = feedbackClient; } @Override protected void channelRead0(final ChannelHandlerContext context, final ExpiredToken expiredToken) { this.feedbackClient.addExpiredToken(expiredToken); } @Override public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { if (!(cause instanceof ReadTimeoutException)) { log.warn("Caught an unexpected exception while waiting for feedback.", cause); } context.close(); } } /** * <p>Constructs a new feedback client that connects to the feedback service in the given {@code PushManager}'s * environment.</p> * * @param pushManager the {@code PushManager} in whose environment this client should operate */ public FeedbackServiceClient(final PushManager<? extends ApnsPushNotification> pushManager) { this.pushManager = pushManager; } protected void addExpiredToken(final ExpiredToken expiredToken) { this.expiredTokens.add(expiredToken); } /** * <p>Retrieves a list of expired tokens from the APNs feedback service. Be warned that this is a * <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote> * * @param timeout the time after the last received data after which the connection to the feedback service should * be closed * @param timeoutUnit the unit of time in which the given {@code timeout} is measured * * @return a list of tokens that have expired since the last connection to the feedback service * * @throws InterruptedException if interrupted while waiting for a response from the feedback service */ public synchronized List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException { this.expiredTokens = new Vector<ExpiredToken>(); final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(pushManager.getWorkerGroup()); bootstrap.channel(NioSocketChannel.class); final FeedbackServiceClient feedbackClient = this; bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (pushManager.getEnvironment().isTlsRequired()) { pipeline.addLast("ssl", SslHandlerUtil.createSslHandler(pushManager.getKeyStore(), pushManager.getKeyStorePassword())); } - pipeline.addLast("readTiemoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit)); + pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit)); pipeline.addLast("decoder", new ExpiredTokenDecoder()); pipeline.addLast("handler", new FeedbackClientHandler(feedbackClient)); } }); final ChannelFuture connectFuture = bootstrap.connect( this.pushManager.getEnvironment().getFeedbackHost(), this.pushManager.getEnvironment().getFeedbackPort()).await(); if (connectFuture.isSuccess()) { log.debug("Connected to feedback service."); if (this.pushManager.getEnvironment().isTlsRequired()) { final Future<Channel> handshakeFuture = connectFuture.channel().pipeline().get(SslHandler.class).handshakeFuture().await(); if (handshakeFuture.isSuccess()) { log.debug("Completed TLS handshake with feedback service."); connectFuture.channel().closeFuture().await(); } else if (handshakeFuture.cause() != null) { log.warn("Failed to complete TLS handshake with feedback service.", handshakeFuture.cause()); } else if (handshakeFuture.isCancelled()) { log.debug("TLS handhsake attempt was cancelled."); } } else { connectFuture.channel().closeFuture().await(); } } else if (connectFuture.cause() != null) { log.warn("Failed to connect to feedback service.", connectFuture.cause()); } else if (connectFuture.isCancelled()) { log.debug("Attempt to connect to feedback service was cancelled."); } // The feedback service will send us a list of device tokens as soon as we connect, then hang up. While we're // waiting to sync with the connection closure, we'll be receiving messages from the feedback service from // another thread. return this.expiredTokens; } }
true
true
public synchronized List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException { this.expiredTokens = new Vector<ExpiredToken>(); final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(pushManager.getWorkerGroup()); bootstrap.channel(NioSocketChannel.class); final FeedbackServiceClient feedbackClient = this; bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (pushManager.getEnvironment().isTlsRequired()) { pipeline.addLast("ssl", SslHandlerUtil.createSslHandler(pushManager.getKeyStore(), pushManager.getKeyStorePassword())); } pipeline.addLast("readTiemoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit)); pipeline.addLast("decoder", new ExpiredTokenDecoder()); pipeline.addLast("handler", new FeedbackClientHandler(feedbackClient)); } }); final ChannelFuture connectFuture = bootstrap.connect( this.pushManager.getEnvironment().getFeedbackHost(), this.pushManager.getEnvironment().getFeedbackPort()).await(); if (connectFuture.isSuccess()) { log.debug("Connected to feedback service."); if (this.pushManager.getEnvironment().isTlsRequired()) { final Future<Channel> handshakeFuture = connectFuture.channel().pipeline().get(SslHandler.class).handshakeFuture().await(); if (handshakeFuture.isSuccess()) { log.debug("Completed TLS handshake with feedback service."); connectFuture.channel().closeFuture().await(); } else if (handshakeFuture.cause() != null) { log.warn("Failed to complete TLS handshake with feedback service.", handshakeFuture.cause()); } else if (handshakeFuture.isCancelled()) { log.debug("TLS handhsake attempt was cancelled."); } } else { connectFuture.channel().closeFuture().await(); } } else if (connectFuture.cause() != null) { log.warn("Failed to connect to feedback service.", connectFuture.cause()); } else if (connectFuture.isCancelled()) { log.debug("Attempt to connect to feedback service was cancelled."); } // The feedback service will send us a list of device tokens as soon as we connect, then hang up. While we're // waiting to sync with the connection closure, we'll be receiving messages from the feedback service from // another thread. return this.expiredTokens; }
public synchronized List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException { this.expiredTokens = new Vector<ExpiredToken>(); final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(pushManager.getWorkerGroup()); bootstrap.channel(NioSocketChannel.class); final FeedbackServiceClient feedbackClient = this; bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (pushManager.getEnvironment().isTlsRequired()) { pipeline.addLast("ssl", SslHandlerUtil.createSslHandler(pushManager.getKeyStore(), pushManager.getKeyStorePassword())); } pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit)); pipeline.addLast("decoder", new ExpiredTokenDecoder()); pipeline.addLast("handler", new FeedbackClientHandler(feedbackClient)); } }); final ChannelFuture connectFuture = bootstrap.connect( this.pushManager.getEnvironment().getFeedbackHost(), this.pushManager.getEnvironment().getFeedbackPort()).await(); if (connectFuture.isSuccess()) { log.debug("Connected to feedback service."); if (this.pushManager.getEnvironment().isTlsRequired()) { final Future<Channel> handshakeFuture = connectFuture.channel().pipeline().get(SslHandler.class).handshakeFuture().await(); if (handshakeFuture.isSuccess()) { log.debug("Completed TLS handshake with feedback service."); connectFuture.channel().closeFuture().await(); } else if (handshakeFuture.cause() != null) { log.warn("Failed to complete TLS handshake with feedback service.", handshakeFuture.cause()); } else if (handshakeFuture.isCancelled()) { log.debug("TLS handhsake attempt was cancelled."); } } else { connectFuture.channel().closeFuture().await(); } } else if (connectFuture.cause() != null) { log.warn("Failed to connect to feedback service.", connectFuture.cause()); } else if (connectFuture.isCancelled()) { log.debug("Attempt to connect to feedback service was cancelled."); } // The feedback service will send us a list of device tokens as soon as we connect, then hang up. While we're // waiting to sync with the connection closure, we'll be receiving messages from the feedback service from // another thread. return this.expiredTokens; }
diff --git a/src/main/dk/itu/kf04/g4tw/controller/RequestParser.java b/src/main/dk/itu/kf04/g4tw/controller/RequestParser.java index eb3caf5..53bac54 100644 --- a/src/main/dk/itu/kf04/g4tw/controller/RequestParser.java +++ b/src/main/dk/itu/kf04/g4tw/controller/RequestParser.java @@ -1,272 +1,272 @@ package dk.itu.kf04.g4tw.controller; import dk.itu.kf04.g4tw.model.*; import dk.itu.kf04.g4tw.util.DynamicArray; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.logging.Logger; /** * Handles request for the web-server via the paseToInputStream method. */ public class RequestParser { public static Logger Log = Logger.getLogger(RequestParser.class.getName()); /** * Handles input from the server through the input parameter, decodes it and returns an appropriate * message as an array of bytes, ready to dispatch to the sender. * @param model The model to perform searches on * @param input The input string received from the client * @return A series of bytes as a response * @throws IllegalArgumentException If the input is malformed * @throws UnsupportedEncodingException If the input cannot be understood under utf-8 encoding * @throws TransformerException If we fail to transform the xml-document to actual output */ public static byte[] parseToInputStream(MapModel model, String input) throws IllegalArgumentException, UnsupportedEncodingException, TransformerException { // Variables for the request double x1 = 0, x2 = 0, y1 = 0, y2 = 0; int filter = 0; // Decode the input and split it up String[] queries = URLDecoder.decode(input, "UTF-8").split("&"); if (queries.length != 5) { throw new IllegalArgumentException("Must have exactly 5 queries."); } // Iterate through the queries for(String query : queries) { String[] arr = query.split("="); // Something is wrong if there are not exactly 2 values if (arr.length != 2) { throw new IllegalArgumentException("Must have format x1=lowValue&y1=lowValue&x2=highValue&y2=highValue&filter=[1-128]"); } else { // Assign input to local variables for(int i = 0; i < arr.length; i++) { String name = arr[i]; String value = arr[++i]; if(name.equals("x1")) x1 = Double.parseDouble(value); if(name.equals("x2")) x2 = Double.parseDouble(value); if(name.equals("y1")) y1 = Double.parseDouble(value); if(name.equals("y2")) y2 = Double.parseDouble(value); if(name.equals("filter")) filter = Integer.parseInt(value); } } } // Time when the search starts long startTime = System.currentTimeMillis(); // Instantiate the parse XMLDocumentParser xmlParser = new XMLDocumentParser(); // Search the model and concatenate the results with the previous DynamicArray<Road> search = model.search(x1, y1, x2, y2, filter); // Creates an XML document Document docXML = xmlParser.createDocument(); // Creates a roadCollection element inside the root and add namespaces Element roads = docXML.createElement("roadCollection"); roads.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); roads.setAttribute("xsi:noNamespaceSchemaLocation", "kraX.xsd"); docXML.appendChild(roads); // Iterates through the search array, appending the XML element of the current // road to the roadCollection element. This is creating the XML document. for(int i = 0; i < search.length(); i++) { roads.appendChild(search.get(i).toXML(docXML)); } // Create the source Source source = new DOMSource(docXML); // Instantiate output-sources ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); // Instantiate xml-transformers TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // Transform the xml transformer.transform(source, result); // calculates and prints the time taken. long endTime = System.currentTimeMillis() - startTime; Log.info("Found and wrote " + search.length() + " roads in : " + endTime + "ms"); // Return the result-stream as a byte-array return os.toByteArray(); } /** * Handles input from the server through the input parameter and returns an appropriate * message as an array of bytes, ready to dispatch to the sender. * @param model The model to perform the search on * @param input The input string received from the client * @return A series of bytes as a response * @throws IllegalArgumentException If the input is malformed * @throws TransformerException If we fail to transform the xml-document to actual output */ public static byte[] parsePathToInputStream(MapModel model, String input) throws IllegalArgumentException, TransformerException { String[] inputs = input.split("&"); // if there ain't exactly 2 arguments in the request, throw an error! if(!(inputs.length == 2 || inputs.length == 4)) throw new IllegalArgumentException("Must have the format \"adr1=first+address&adr2=second+address\" OR \"adr1=first+address&adr2=second+address&id1=Xid2=Y\""); // The two addresses from the client String adr1 = inputs[0].substring(5); String adr2 = inputs[1].substring(5); int id1 = 0, id2 = 0; // Array over all the roads that match the address. DynamicArray<Road> hits1 = AddressParser.getRoad(adr1); DynamicArray<Road> hits2 = AddressParser.getRoad(adr2); if(inputs.length == 4) { id1 = Integer.parseInt(inputs[2].substring(4)); id2 = Integer.parseInt(inputs[3].substring(4)); if(hits1.length() > 1) { outerloop: for(int i = 0; i < hits1.length(); i++) if(hits1.get(i).getId() == id1) { Road hit = hits1.get(i); hits1 = new DynamicArray<Road>(); hits1.add(hit); break outerloop; } } if(hits2.length() > 1) { outerloop: for(int i = 0; i < hits2.length(); i++) if(hits2.get(i).getId() == id2) { Road hit = hits2.get(i); hits2 = new DynamicArray<Road>(); hits2.add(hit); break outerloop; } } } // Instantiate the parser XMLDocumentParser xmlParser = new XMLDocumentParser(); System.out.println(xmlParser.createDocument().getXmlEncoding()); // Creates an XML document Document docXML = xmlParser.createDocument(); // Creates a roadCollection element inside the root. Element roads = null; if(hits1.length() == 0 || hits2.length() == 0) { // One or both of the addresses gave zero hits. User have to give a new address. // Oh crap, couldn't find at least one of the addresses! roads = docXML.createElement("error"); roads.setAttribute("type", "1"); docXML.appendChild(roads); if(hits1.length() == 0) { Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr1)); roads.appendChild(element); Log.info("Could not find \"" + adr1 + "\" in the system"); } if(hits2.length() == 0) { Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr2)); roads.appendChild(element); Log.info("Could not find \"" + adr2 + "\" in the system"); } } else if(hits1.length() == 1 && hits2.length() == 1) { // The addresses both gave only one hit. We can find a path. // You've found a path. Now go make some cool XML stuff!!! // TODO: Find a way to see if there are any connection between the two roads. Maybe there are no reason for doing that? Log.info("Trying to find path"); Road[] result = DijkstraSP.shortestPath(model, hits1.get(0), hits2.get(0)); // Initialize the roadCollection element and add namespaces roads = docXML.createElement("roadCollection"); roads.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); roads.setAttribute("xsi:noNamespaceSchemaLocation", "kraX.xsd"); docXML.appendChild(roads); // Iterates through the result array, appending the XML element of the current // road to the roadCollection element. This is creating the XML document. int prev = hits2.get(0).getId(); roads.appendChild(hits2.get(0).toXML(docXML)); - do { + while(result[prev] != null) { roads.appendChild(result[prev].toXML(docXML)); prev = result[prev].getId(); - } while(result[prev] != null); + }; System.out.println("Start ID: " + hits1.get(0).getId()); System.out.println("End ID: " + hits2.get(0).getId()); } else { // One or both of the addresses gave more than one hit. Make the user decide. // Alright, we have a problem. Put we can fix this. Right? roads = docXML.createElement("error"); roads.setAttribute("type", "2"); docXML.appendChild(roads); if(hits1.length() > 1) { Element collection = docXML.createElement("collection"); roads.appendChild(collection); Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr1)); collection.appendChild(element); for (int i = 0; i < hits1.length(); i++) { collection.appendChild(hits1.get(i).toErrorXML(docXML)); } Log.info("Found more than one road. \"" + adr1 + "\" in the system"); } if(hits2.length() > 1) { Element collection = docXML.createElement("collection"); roads.appendChild(collection); Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr2)); collection.appendChild(element); for (int i = 0; i < hits2.length(); i++) { collection.appendChild(hits2.get(i).toErrorXML(docXML)); } Log.info("Found more than one road. \"" + adr2 + "\" in the system"); } } // Create the source Source source = new DOMSource(docXML); // Instantiate output-sources ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); // Instantiate xml-transformers TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // Transform the xml transformer.transform(source, result); // Return the result-stream as a byte-array return os.toByteArray(); } }
false
true
public static byte[] parsePathToInputStream(MapModel model, String input) throws IllegalArgumentException, TransformerException { String[] inputs = input.split("&"); // if there ain't exactly 2 arguments in the request, throw an error! if(!(inputs.length == 2 || inputs.length == 4)) throw new IllegalArgumentException("Must have the format \"adr1=first+address&adr2=second+address\" OR \"adr1=first+address&adr2=second+address&id1=Xid2=Y\""); // The two addresses from the client String adr1 = inputs[0].substring(5); String adr2 = inputs[1].substring(5); int id1 = 0, id2 = 0; // Array over all the roads that match the address. DynamicArray<Road> hits1 = AddressParser.getRoad(adr1); DynamicArray<Road> hits2 = AddressParser.getRoad(adr2); if(inputs.length == 4) { id1 = Integer.parseInt(inputs[2].substring(4)); id2 = Integer.parseInt(inputs[3].substring(4)); if(hits1.length() > 1) { outerloop: for(int i = 0; i < hits1.length(); i++) if(hits1.get(i).getId() == id1) { Road hit = hits1.get(i); hits1 = new DynamicArray<Road>(); hits1.add(hit); break outerloop; } } if(hits2.length() > 1) { outerloop: for(int i = 0; i < hits2.length(); i++) if(hits2.get(i).getId() == id2) { Road hit = hits2.get(i); hits2 = new DynamicArray<Road>(); hits2.add(hit); break outerloop; } } } // Instantiate the parser XMLDocumentParser xmlParser = new XMLDocumentParser(); System.out.println(xmlParser.createDocument().getXmlEncoding()); // Creates an XML document Document docXML = xmlParser.createDocument(); // Creates a roadCollection element inside the root. Element roads = null; if(hits1.length() == 0 || hits2.length() == 0) { // One or both of the addresses gave zero hits. User have to give a new address. // Oh crap, couldn't find at least one of the addresses! roads = docXML.createElement("error"); roads.setAttribute("type", "1"); docXML.appendChild(roads); if(hits1.length() == 0) { Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr1)); roads.appendChild(element); Log.info("Could not find \"" + adr1 + "\" in the system"); } if(hits2.length() == 0) { Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr2)); roads.appendChild(element); Log.info("Could not find \"" + adr2 + "\" in the system"); } } else if(hits1.length() == 1 && hits2.length() == 1) { // The addresses both gave only one hit. We can find a path. // You've found a path. Now go make some cool XML stuff!!! // TODO: Find a way to see if there are any connection between the two roads. Maybe there are no reason for doing that? Log.info("Trying to find path"); Road[] result = DijkstraSP.shortestPath(model, hits1.get(0), hits2.get(0)); // Initialize the roadCollection element and add namespaces roads = docXML.createElement("roadCollection"); roads.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); roads.setAttribute("xsi:noNamespaceSchemaLocation", "kraX.xsd"); docXML.appendChild(roads); // Iterates through the result array, appending the XML element of the current // road to the roadCollection element. This is creating the XML document. int prev = hits2.get(0).getId(); roads.appendChild(hits2.get(0).toXML(docXML)); do { roads.appendChild(result[prev].toXML(docXML)); prev = result[prev].getId(); } while(result[prev] != null); System.out.println("Start ID: " + hits1.get(0).getId()); System.out.println("End ID: " + hits2.get(0).getId()); } else { // One or both of the addresses gave more than one hit. Make the user decide. // Alright, we have a problem. Put we can fix this. Right? roads = docXML.createElement("error"); roads.setAttribute("type", "2"); docXML.appendChild(roads); if(hits1.length() > 1) { Element collection = docXML.createElement("collection"); roads.appendChild(collection); Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr1)); collection.appendChild(element); for (int i = 0; i < hits1.length(); i++) { collection.appendChild(hits1.get(i).toErrorXML(docXML)); } Log.info("Found more than one road. \"" + adr1 + "\" in the system"); } if(hits2.length() > 1) { Element collection = docXML.createElement("collection"); roads.appendChild(collection); Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr2)); collection.appendChild(element); for (int i = 0; i < hits2.length(); i++) { collection.appendChild(hits2.get(i).toErrorXML(docXML)); } Log.info("Found more than one road. \"" + adr2 + "\" in the system"); } } // Create the source Source source = new DOMSource(docXML); // Instantiate output-sources ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); // Instantiate xml-transformers TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // Transform the xml transformer.transform(source, result); // Return the result-stream as a byte-array return os.toByteArray(); }
public static byte[] parsePathToInputStream(MapModel model, String input) throws IllegalArgumentException, TransformerException { String[] inputs = input.split("&"); // if there ain't exactly 2 arguments in the request, throw an error! if(!(inputs.length == 2 || inputs.length == 4)) throw new IllegalArgumentException("Must have the format \"adr1=first+address&adr2=second+address\" OR \"adr1=first+address&adr2=second+address&id1=Xid2=Y\""); // The two addresses from the client String adr1 = inputs[0].substring(5); String adr2 = inputs[1].substring(5); int id1 = 0, id2 = 0; // Array over all the roads that match the address. DynamicArray<Road> hits1 = AddressParser.getRoad(adr1); DynamicArray<Road> hits2 = AddressParser.getRoad(adr2); if(inputs.length == 4) { id1 = Integer.parseInt(inputs[2].substring(4)); id2 = Integer.parseInt(inputs[3].substring(4)); if(hits1.length() > 1) { outerloop: for(int i = 0; i < hits1.length(); i++) if(hits1.get(i).getId() == id1) { Road hit = hits1.get(i); hits1 = new DynamicArray<Road>(); hits1.add(hit); break outerloop; } } if(hits2.length() > 1) { outerloop: for(int i = 0; i < hits2.length(); i++) if(hits2.get(i).getId() == id2) { Road hit = hits2.get(i); hits2 = new DynamicArray<Road>(); hits2.add(hit); break outerloop; } } } // Instantiate the parser XMLDocumentParser xmlParser = new XMLDocumentParser(); System.out.println(xmlParser.createDocument().getXmlEncoding()); // Creates an XML document Document docXML = xmlParser.createDocument(); // Creates a roadCollection element inside the root. Element roads = null; if(hits1.length() == 0 || hits2.length() == 0) { // One or both of the addresses gave zero hits. User have to give a new address. // Oh crap, couldn't find at least one of the addresses! roads = docXML.createElement("error"); roads.setAttribute("type", "1"); docXML.appendChild(roads); if(hits1.length() == 0) { Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr1)); roads.appendChild(element); Log.info("Could not find \"" + adr1 + "\" in the system"); } if(hits2.length() == 0) { Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr2)); roads.appendChild(element); Log.info("Could not find \"" + adr2 + "\" in the system"); } } else if(hits1.length() == 1 && hits2.length() == 1) { // The addresses both gave only one hit. We can find a path. // You've found a path. Now go make some cool XML stuff!!! // TODO: Find a way to see if there are any connection between the two roads. Maybe there are no reason for doing that? Log.info("Trying to find path"); Road[] result = DijkstraSP.shortestPath(model, hits1.get(0), hits2.get(0)); // Initialize the roadCollection element and add namespaces roads = docXML.createElement("roadCollection"); roads.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); roads.setAttribute("xsi:noNamespaceSchemaLocation", "kraX.xsd"); docXML.appendChild(roads); // Iterates through the result array, appending the XML element of the current // road to the roadCollection element. This is creating the XML document. int prev = hits2.get(0).getId(); roads.appendChild(hits2.get(0).toXML(docXML)); while(result[prev] != null) { roads.appendChild(result[prev].toXML(docXML)); prev = result[prev].getId(); }; System.out.println("Start ID: " + hits1.get(0).getId()); System.out.println("End ID: " + hits2.get(0).getId()); } else { // One or both of the addresses gave more than one hit. Make the user decide. // Alright, we have a problem. Put we can fix this. Right? roads = docXML.createElement("error"); roads.setAttribute("type", "2"); docXML.appendChild(roads); if(hits1.length() > 1) { Element collection = docXML.createElement("collection"); roads.appendChild(collection); Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr1)); collection.appendChild(element); for (int i = 0; i < hits1.length(); i++) { collection.appendChild(hits1.get(i).toErrorXML(docXML)); } Log.info("Found more than one road. \"" + adr1 + "\" in the system"); } if(hits2.length() > 1) { Element collection = docXML.createElement("collection"); roads.appendChild(collection); Element element = docXML.createElement("address"); element.appendChild(docXML.createTextNode(adr2)); collection.appendChild(element); for (int i = 0; i < hits2.length(); i++) { collection.appendChild(hits2.get(i).toErrorXML(docXML)); } Log.info("Found more than one road. \"" + adr2 + "\" in the system"); } } // Create the source Source source = new DOMSource(docXML); // Instantiate output-sources ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); // Instantiate xml-transformers TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // Transform the xml transformer.transform(source, result); // Return the result-stream as a byte-array return os.toByteArray(); }
diff --git a/OutputButton.java b/OutputButton.java index 6c61b8b..c0ab617 100644 --- a/OutputButton.java +++ b/OutputButton.java @@ -1,43 +1,43 @@ package Mastermind; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class OutputButton extends JComponent { private int currColor; public OutputButton() { currColor = 0; } public void paint(Graphics g) { if (currColor == 1) { g.setColor(Color.WHITE); g.fillOval(0,0,10,10); } else if (currColor == 2) { g.setColor(Color.BLACK); g.fillOval(0,0,10,10); } else { g.setColor(Color.BLACK); - g.drawOval(0,0,30,30); + g.drawOval(0,0,10,10); } } public int getCurrColor() { return currColor; } public void setColor(int newColor) { currColor = newColor; repaint(); } public Dimension getMinimumSize() { return new Dimension(10,10); } public Dimension getPreferredSize() { return new Dimension(10,10); } }
true
true
public void paint(Graphics g) { if (currColor == 1) { g.setColor(Color.WHITE); g.fillOval(0,0,10,10); } else if (currColor == 2) { g.setColor(Color.BLACK); g.fillOval(0,0,10,10); } else { g.setColor(Color.BLACK); g.drawOval(0,0,30,30); } }
public void paint(Graphics g) { if (currColor == 1) { g.setColor(Color.WHITE); g.fillOval(0,0,10,10); } else if (currColor == 2) { g.setColor(Color.BLACK); g.fillOval(0,0,10,10); } else { g.setColor(Color.BLACK); g.drawOval(0,0,10,10); } }
diff --git a/NAKJava/src/de/nordakademie/nakjava/server/shared/proxy/actions/LeaveGameAction.java b/NAKJava/src/de/nordakademie/nakjava/server/shared/proxy/actions/LeaveGameAction.java index bd3e3cc..2fa41ea 100644 --- a/NAKJava/src/de/nordakademie/nakjava/server/shared/proxy/actions/LeaveGameAction.java +++ b/NAKJava/src/de/nordakademie/nakjava/server/shared/proxy/actions/LeaveGameAction.java @@ -1,49 +1,53 @@ package de.nordakademie.nakjava.server.shared.proxy.actions; import java.rmi.RemoteException; import de.nordakademie.nakjava.gamelogic.shared.playerstate.PlayerState; import de.nordakademie.nakjava.gamelogic.stateMachineEvenNewer.states.State; import de.nordakademie.nakjava.server.internal.Players; import de.nordakademie.nakjava.server.internal.Session; import de.nordakademie.nakjava.server.shared.proxy.ActionAbstractImpl; import de.nordakademie.nakjava.server.shared.proxy.ServerAction; import de.nordakademie.nakjava.server.shared.serial.ActionContext; public class LeaveGameAction extends ActionContext { public LeaveGameAction(long sessionNr) { super(sessionNr); } @Override protected ServerAction getAction(long sessionNr) throws RemoteException { return new ActionAbstractImpl(sessionNr) { @Override protected void performImpl(Session session) { if (!session.isActionInvokerCurrentPlayer()) { session.getModel().changeSelfAndOpponent(); } String name = session.getModel().getSelf().getName(); PlayerState opponent = session.getModel().getOpponent(); if (opponent == null) { session.setToBeDeleted(true); } else if (opponent.getState() != State.LOGIN && opponent.getState() != State.CONFIGUREGAME && opponent.getState() != State.EDITDECK) { session.getModel().getOpponent() .setState(State.OTHERPLAYERLEFTGAME); } try { session.getActionInvoker().getControl().remoteClose(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } session.removeActionInvoker(); - Players.getInstance().removeLoggedInPlayerName(name); + if (session.getModel().getSelf().getState() == State.LOGIN) { + Players.getInstance().removeReservedPlayerName(name); + } else { + Players.getInstance().removeLoggedInPlayerName(name); + } } }; } }
true
true
protected ServerAction getAction(long sessionNr) throws RemoteException { return new ActionAbstractImpl(sessionNr) { @Override protected void performImpl(Session session) { if (!session.isActionInvokerCurrentPlayer()) { session.getModel().changeSelfAndOpponent(); } String name = session.getModel().getSelf().getName(); PlayerState opponent = session.getModel().getOpponent(); if (opponent == null) { session.setToBeDeleted(true); } else if (opponent.getState() != State.LOGIN && opponent.getState() != State.CONFIGUREGAME && opponent.getState() != State.EDITDECK) { session.getModel().getOpponent() .setState(State.OTHERPLAYERLEFTGAME); } try { session.getActionInvoker().getControl().remoteClose(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } session.removeActionInvoker(); Players.getInstance().removeLoggedInPlayerName(name); } }; }
protected ServerAction getAction(long sessionNr) throws RemoteException { return new ActionAbstractImpl(sessionNr) { @Override protected void performImpl(Session session) { if (!session.isActionInvokerCurrentPlayer()) { session.getModel().changeSelfAndOpponent(); } String name = session.getModel().getSelf().getName(); PlayerState opponent = session.getModel().getOpponent(); if (opponent == null) { session.setToBeDeleted(true); } else if (opponent.getState() != State.LOGIN && opponent.getState() != State.CONFIGUREGAME && opponent.getState() != State.EDITDECK) { session.getModel().getOpponent() .setState(State.OTHERPLAYERLEFTGAME); } try { session.getActionInvoker().getControl().remoteClose(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } session.removeActionInvoker(); if (session.getModel().getSelf().getState() == State.LOGIN) { Players.getInstance().removeReservedPlayerName(name); } else { Players.getInstance().removeLoggedInPlayerName(name); } } }; }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/APIDeserializer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/APIDeserializer.java index aedb5e5a0..ebbc503fd 100755 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/APIDeserializer.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/APIDeserializer.java @@ -1,182 +1,182 @@ /* * Copyright 2012 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer; import java.util.Arrays; import java.util.List; import org.apache.synapse.mediators.base.SequenceMediator; import org.apache.synapse.rest.API; import org.apache.synapse.rest.Resource; import org.apache.synapse.rest.dispatch.DispatcherHelper; import org.apache.synapse.rest.dispatch.URITemplateHelper; import org.apache.synapse.rest.dispatch.URLMappingHelper; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; import org.eclipse.gmf.runtime.diagram.ui.commands.SetBoundsCommand; import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.APIResource; import org.wso2.developerstudio.eclipse.gmf.esb.ApiResourceUrlStyle; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow; import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty; import org.wso2.developerstudio.eclipse.gmf.esb.SequenceType; import org.wso2.developerstudio.eclipse.gmf.esb.SynapseAPI; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.*; /** * Synapse API deserializer */ public class APIDeserializer extends AbstractEsbNodeDeserializer<API, SynapseAPI> { @Override public SynapseAPI createNode(IGraphicalEditPart part,API api) { SynapseAPI synapseAPI = (SynapseAPI) DeserializerUtils.createNode(part, EsbElementTypes.SynapseAPI_3668); setElementToEdit(synapseAPI); refreshEditPartMap(); executeSetValueCommand(SYNAPSE_API__API_NAME, api.getAPIName()); executeSetValueCommand(SYNAPSE_API__CONTEXT, api.getContext()); if (api.getHost() != null) { executeSetValueCommand(SYNAPSE_API__HOST_NAME, api.getHost()); } if (api.getPort() > 0) { executeSetValueCommand(SYNAPSE_API__PORT, api.getPort()); } GraphicalEditPart apiCompartment = (GraphicalEditPart) getEditpart(synapseAPI).getChildren().get(0); Resource[] resources = api.getResources(); int locationY = 0; for (int i = 0; i < resources.length; i++) { APIResource resource = (APIResource) DeserializerUtils.createNode(apiCompartment, EsbElementTypes.APIResource_3669); refreshEditPartMap(); setElementToEdit(resource); List<String> methodList = Arrays.asList(resources[i].getMethods()); executeSetValueCommand(API_RESOURCE__ALLOW_GET, methodList.contains("GET")); executeSetValueCommand(API_RESOURCE__ALLOW_POST, methodList.contains("POST")); executeSetValueCommand(API_RESOURCE__ALLOW_OPTIONS, methodList.contains("OPTIONS")); executeSetValueCommand(API_RESOURCE__ALLOW_DELETE, methodList.contains("DELETE")); executeSetValueCommand(API_RESOURCE__ALLOW_PUT, methodList.contains("PUT")); DispatcherHelper dispatcherHelper = resources[i].getDispatcherHelper(); if(dispatcherHelper instanceof URITemplateHelper){ URITemplateHelper helper = (URITemplateHelper) dispatcherHelper; executeSetValueCommand(API_RESOURCE__URL_STYLE, ApiResourceUrlStyle.URI_TEMPLATE); - executeSetValueCommand(API_RESOURCE__URI_TEMPLATE, helper.getUriTemplate().toString()); + executeSetValueCommand(API_RESOURCE__URI_TEMPLATE, helper.getString()); } else if(dispatcherHelper instanceof URLMappingHelper){ URLMappingHelper helper = (URLMappingHelper) dispatcherHelper; executeSetValueCommand(API_RESOURCE__URL_STYLE,ApiResourceUrlStyle.URL_MAPPING); executeSetValueCommand(API_RESOURCE__URL_MAPPING, helper.getString()); } else{ executeSetValueCommand(API_RESOURCE__URL_STYLE,ApiResourceUrlStyle.NONE); } addRootInputConnector(resource.getInputConnector()); MediatorFlow mediatorFlow = resource.getContainer().getSequenceAndEndpointContainer().getMediatorFlow(); GraphicalEditPart compartment = (GraphicalEditPart)((getEditpart(mediatorFlow)).getChildren().get(0)); SequenceMediator inSequence = resources[i].getInSequence(); if(inSequence!=null){ setRootCompartment(compartment); deserializeSequence(compartment, inSequence, resource.getOutputConnector()); setRootCompartment(null); } else{ String inSequenceName = resources[i].getInSequenceKey(); if(inSequenceName!=null){ if(inSequenceName.startsWith("/") || inSequenceName.startsWith("conf:") || inSequenceName.startsWith("gov:")){ resource.setInSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(inSequenceName); executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_NAME, inSequenceName); } } } SequenceMediator outSequence = resources[i].getOutSequence(); if(outSequence!=null){ setRootCompartment(compartment); deserializeSequence(compartment, outSequence, resource.getInputConnector()); setRootCompartment(null); } else{ String outSequenceName = resources[i].getOutSequenceKey(); if(outSequenceName!=null){ if(outSequenceName.startsWith("/") || outSequenceName.startsWith("conf:") || outSequenceName.startsWith("gov:")){ resource.setOutSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(outSequenceName); executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_NAME, outSequenceName); } } } SequenceMediator faultSequence = resources[i].getFaultSequence(); if(faultSequence!=null){ MediatorFlow faultMediatorFlow = resource.getContainer().getFaultContainer().getMediatorFlow(); GraphicalEditPart faultCompartment = (GraphicalEditPart)((getEditpart(faultMediatorFlow)).getChildren().get(0)); setRootCompartment(faultCompartment); deserializeSequence(faultCompartment, faultSequence, resource.getFaultInputConnector()); setRootCompartment(null); } else{ String faultSequenceName = resources[i].getFaultSequenceKey(); if(faultSequenceName!=null){ if(faultSequenceName.startsWith("/") || faultSequenceName.startsWith("conf:") || faultSequenceName.startsWith("gov:")){ resource.setFaultSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(faultSequenceName); executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_NAME, faultSequenceName); } } } addPairMediatorFlow(resource.getOutputConnector(),resource.getInputConnector()); IGraphicalEditPart graphicalNode = (IGraphicalEditPart) AbstractEsbNodeDeserializer.getEditpart(resource); if(graphicalNode!=null){ Rectangle rect = new Rectangle(new Point(), graphicalNode.getFigure().getPreferredSize()).getCopy(); rect.x = 0; rect.y = locationY; SetBoundsCommand sbc = new SetBoundsCommand(graphicalNode.getEditingDomain(), "change location", new EObjectAdapter((View) graphicalNode.getModel()), rect); graphicalNode.getDiagramEditDomain().getDiagramCommandStack() .execute(new ICommandProxy(sbc)); locationY += rect.height; locationY += 25; } } return synapseAPI; } }
true
true
public SynapseAPI createNode(IGraphicalEditPart part,API api) { SynapseAPI synapseAPI = (SynapseAPI) DeserializerUtils.createNode(part, EsbElementTypes.SynapseAPI_3668); setElementToEdit(synapseAPI); refreshEditPartMap(); executeSetValueCommand(SYNAPSE_API__API_NAME, api.getAPIName()); executeSetValueCommand(SYNAPSE_API__CONTEXT, api.getContext()); if (api.getHost() != null) { executeSetValueCommand(SYNAPSE_API__HOST_NAME, api.getHost()); } if (api.getPort() > 0) { executeSetValueCommand(SYNAPSE_API__PORT, api.getPort()); } GraphicalEditPart apiCompartment = (GraphicalEditPart) getEditpart(synapseAPI).getChildren().get(0); Resource[] resources = api.getResources(); int locationY = 0; for (int i = 0; i < resources.length; i++) { APIResource resource = (APIResource) DeserializerUtils.createNode(apiCompartment, EsbElementTypes.APIResource_3669); refreshEditPartMap(); setElementToEdit(resource); List<String> methodList = Arrays.asList(resources[i].getMethods()); executeSetValueCommand(API_RESOURCE__ALLOW_GET, methodList.contains("GET")); executeSetValueCommand(API_RESOURCE__ALLOW_POST, methodList.contains("POST")); executeSetValueCommand(API_RESOURCE__ALLOW_OPTIONS, methodList.contains("OPTIONS")); executeSetValueCommand(API_RESOURCE__ALLOW_DELETE, methodList.contains("DELETE")); executeSetValueCommand(API_RESOURCE__ALLOW_PUT, methodList.contains("PUT")); DispatcherHelper dispatcherHelper = resources[i].getDispatcherHelper(); if(dispatcherHelper instanceof URITemplateHelper){ URITemplateHelper helper = (URITemplateHelper) dispatcherHelper; executeSetValueCommand(API_RESOURCE__URL_STYLE, ApiResourceUrlStyle.URI_TEMPLATE); executeSetValueCommand(API_RESOURCE__URI_TEMPLATE, helper.getUriTemplate().toString()); } else if(dispatcherHelper instanceof URLMappingHelper){ URLMappingHelper helper = (URLMappingHelper) dispatcherHelper; executeSetValueCommand(API_RESOURCE__URL_STYLE,ApiResourceUrlStyle.URL_MAPPING); executeSetValueCommand(API_RESOURCE__URL_MAPPING, helper.getString()); } else{ executeSetValueCommand(API_RESOURCE__URL_STYLE,ApiResourceUrlStyle.NONE); } addRootInputConnector(resource.getInputConnector()); MediatorFlow mediatorFlow = resource.getContainer().getSequenceAndEndpointContainer().getMediatorFlow(); GraphicalEditPart compartment = (GraphicalEditPart)((getEditpart(mediatorFlow)).getChildren().get(0)); SequenceMediator inSequence = resources[i].getInSequence(); if(inSequence!=null){ setRootCompartment(compartment); deserializeSequence(compartment, inSequence, resource.getOutputConnector()); setRootCompartment(null); } else{ String inSequenceName = resources[i].getInSequenceKey(); if(inSequenceName!=null){ if(inSequenceName.startsWith("/") || inSequenceName.startsWith("conf:") || inSequenceName.startsWith("gov:")){ resource.setInSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(inSequenceName); executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_NAME, inSequenceName); } } } SequenceMediator outSequence = resources[i].getOutSequence(); if(outSequence!=null){ setRootCompartment(compartment); deserializeSequence(compartment, outSequence, resource.getInputConnector()); setRootCompartment(null); } else{ String outSequenceName = resources[i].getOutSequenceKey(); if(outSequenceName!=null){ if(outSequenceName.startsWith("/") || outSequenceName.startsWith("conf:") || outSequenceName.startsWith("gov:")){ resource.setOutSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(outSequenceName); executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_NAME, outSequenceName); } } } SequenceMediator faultSequence = resources[i].getFaultSequence(); if(faultSequence!=null){ MediatorFlow faultMediatorFlow = resource.getContainer().getFaultContainer().getMediatorFlow(); GraphicalEditPart faultCompartment = (GraphicalEditPart)((getEditpart(faultMediatorFlow)).getChildren().get(0)); setRootCompartment(faultCompartment); deserializeSequence(faultCompartment, faultSequence, resource.getFaultInputConnector()); setRootCompartment(null); } else{ String faultSequenceName = resources[i].getFaultSequenceKey(); if(faultSequenceName!=null){ if(faultSequenceName.startsWith("/") || faultSequenceName.startsWith("conf:") || faultSequenceName.startsWith("gov:")){ resource.setFaultSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(faultSequenceName); executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_NAME, faultSequenceName); } } } addPairMediatorFlow(resource.getOutputConnector(),resource.getInputConnector()); IGraphicalEditPart graphicalNode = (IGraphicalEditPart) AbstractEsbNodeDeserializer.getEditpart(resource); if(graphicalNode!=null){ Rectangle rect = new Rectangle(new Point(), graphicalNode.getFigure().getPreferredSize()).getCopy(); rect.x = 0; rect.y = locationY; SetBoundsCommand sbc = new SetBoundsCommand(graphicalNode.getEditingDomain(), "change location", new EObjectAdapter((View) graphicalNode.getModel()), rect); graphicalNode.getDiagramEditDomain().getDiagramCommandStack() .execute(new ICommandProxy(sbc)); locationY += rect.height; locationY += 25; } } return synapseAPI; }
public SynapseAPI createNode(IGraphicalEditPart part,API api) { SynapseAPI synapseAPI = (SynapseAPI) DeserializerUtils.createNode(part, EsbElementTypes.SynapseAPI_3668); setElementToEdit(synapseAPI); refreshEditPartMap(); executeSetValueCommand(SYNAPSE_API__API_NAME, api.getAPIName()); executeSetValueCommand(SYNAPSE_API__CONTEXT, api.getContext()); if (api.getHost() != null) { executeSetValueCommand(SYNAPSE_API__HOST_NAME, api.getHost()); } if (api.getPort() > 0) { executeSetValueCommand(SYNAPSE_API__PORT, api.getPort()); } GraphicalEditPart apiCompartment = (GraphicalEditPart) getEditpart(synapseAPI).getChildren().get(0); Resource[] resources = api.getResources(); int locationY = 0; for (int i = 0; i < resources.length; i++) { APIResource resource = (APIResource) DeserializerUtils.createNode(apiCompartment, EsbElementTypes.APIResource_3669); refreshEditPartMap(); setElementToEdit(resource); List<String> methodList = Arrays.asList(resources[i].getMethods()); executeSetValueCommand(API_RESOURCE__ALLOW_GET, methodList.contains("GET")); executeSetValueCommand(API_RESOURCE__ALLOW_POST, methodList.contains("POST")); executeSetValueCommand(API_RESOURCE__ALLOW_OPTIONS, methodList.contains("OPTIONS")); executeSetValueCommand(API_RESOURCE__ALLOW_DELETE, methodList.contains("DELETE")); executeSetValueCommand(API_RESOURCE__ALLOW_PUT, methodList.contains("PUT")); DispatcherHelper dispatcherHelper = resources[i].getDispatcherHelper(); if(dispatcherHelper instanceof URITemplateHelper){ URITemplateHelper helper = (URITemplateHelper) dispatcherHelper; executeSetValueCommand(API_RESOURCE__URL_STYLE, ApiResourceUrlStyle.URI_TEMPLATE); executeSetValueCommand(API_RESOURCE__URI_TEMPLATE, helper.getString()); } else if(dispatcherHelper instanceof URLMappingHelper){ URLMappingHelper helper = (URLMappingHelper) dispatcherHelper; executeSetValueCommand(API_RESOURCE__URL_STYLE,ApiResourceUrlStyle.URL_MAPPING); executeSetValueCommand(API_RESOURCE__URL_MAPPING, helper.getString()); } else{ executeSetValueCommand(API_RESOURCE__URL_STYLE,ApiResourceUrlStyle.NONE); } addRootInputConnector(resource.getInputConnector()); MediatorFlow mediatorFlow = resource.getContainer().getSequenceAndEndpointContainer().getMediatorFlow(); GraphicalEditPart compartment = (GraphicalEditPart)((getEditpart(mediatorFlow)).getChildren().get(0)); SequenceMediator inSequence = resources[i].getInSequence(); if(inSequence!=null){ setRootCompartment(compartment); deserializeSequence(compartment, inSequence, resource.getOutputConnector()); setRootCompartment(null); } else{ String inSequenceName = resources[i].getInSequenceKey(); if(inSequenceName!=null){ if(inSequenceName.startsWith("/") || inSequenceName.startsWith("conf:") || inSequenceName.startsWith("gov:")){ resource.setInSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(inSequenceName); executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__IN_SEQUENCE_NAME, inSequenceName); } } } SequenceMediator outSequence = resources[i].getOutSequence(); if(outSequence!=null){ setRootCompartment(compartment); deserializeSequence(compartment, outSequence, resource.getInputConnector()); setRootCompartment(null); } else{ String outSequenceName = resources[i].getOutSequenceKey(); if(outSequenceName!=null){ if(outSequenceName.startsWith("/") || outSequenceName.startsWith("conf:") || outSequenceName.startsWith("gov:")){ resource.setOutSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(outSequenceName); executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__OUT_SEQUENCE_NAME, outSequenceName); } } } SequenceMediator faultSequence = resources[i].getFaultSequence(); if(faultSequence!=null){ MediatorFlow faultMediatorFlow = resource.getContainer().getFaultContainer().getMediatorFlow(); GraphicalEditPart faultCompartment = (GraphicalEditPart)((getEditpart(faultMediatorFlow)).getChildren().get(0)); setRootCompartment(faultCompartment); deserializeSequence(faultCompartment, faultSequence, resource.getFaultInputConnector()); setRootCompartment(null); } else{ String faultSequenceName = resources[i].getFaultSequenceKey(); if(faultSequenceName!=null){ if(faultSequenceName.startsWith("/") || faultSequenceName.startsWith("conf:") || faultSequenceName.startsWith("gov:")){ resource.setFaultSequenceType(SequenceType.REGISTRY_REFERENCE); RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty(); keyProperty.setKeyValue(faultSequenceName); executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_KEY, keyProperty); } else{ executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE); executeSetValueCommand(API_RESOURCE__FAULT_SEQUENCE_NAME, faultSequenceName); } } } addPairMediatorFlow(resource.getOutputConnector(),resource.getInputConnector()); IGraphicalEditPart graphicalNode = (IGraphicalEditPart) AbstractEsbNodeDeserializer.getEditpart(resource); if(graphicalNode!=null){ Rectangle rect = new Rectangle(new Point(), graphicalNode.getFigure().getPreferredSize()).getCopy(); rect.x = 0; rect.y = locationY; SetBoundsCommand sbc = new SetBoundsCommand(graphicalNode.getEditingDomain(), "change location", new EObjectAdapter((View) graphicalNode.getModel()), rect); graphicalNode.getDiagramEditDomain().getDiagramCommandStack() .execute(new ICommandProxy(sbc)); locationY += rect.height; locationY += 25; } } return synapseAPI; }
diff --git a/src/main/java/com/inmobi/databus/Databus.java b/src/main/java/com/inmobi/databus/Databus.java index 5234f623..9352e930 100644 --- a/src/main/java/com/inmobi/databus/Databus.java +++ b/src/main/java/com/inmobi/databus/Databus.java @@ -1,74 +1,74 @@ package com.inmobi.databus; import com.inmobi.databus.DatabusConfig.Cluster; import com.inmobi.databus.consume.DataConsumer; import com.inmobi.databus.distcp.RemoteCopier; import org.apache.hadoop.fs.FileSystem; import org.apache.log4j.Logger; import java.util.*; public class Databus { static Logger logger = Logger.getLogger(Databus.class); private DatabusConfig config; private String myClusterName; public Databus(String myClusterName, String databusconfigFile) throws Exception{ DatabusConfigParser configParser; this.myClusterName = myClusterName; if(databusconfigFile == null) configParser= new DatabusConfigParser(null); else configParser = new DatabusConfigParser(databusconfigFile); Map<String, Cluster> clusterMap = configParser.getClusterMap(); this.config = new DatabusConfig(configParser.getRootDir(), configParser.getStreamMap(), clusterMap, clusterMap.get(myClusterName)); logger.debug("my cluster details " + clusterMap.get(myClusterName)); } public void start() throws Exception { List<AbstractCopier> copiers = new ArrayList<AbstractCopier>(); logger.warn("My clusterName is [" + myClusterName + "] " + config.getDestinationCluster().getName()); for (Cluster c : config.getClusters().values()) { AbstractCopier copier = null; - if (myClusterName.equalsIgnoreCase(config.getDestinationCluster().getName())) { + if (c.getName().equalsIgnoreCase(config.getDestinationCluster().getName())) { logger.warn("Starting data consumer for Cluster[" + - myClusterName + "]"); + c.getName() + "]"); copier = new DataConsumer(config); } else { logger.warn("Starting remote copier for cluster [" + - config.getDestinationCluster().getName() + "]"); + c.getName() + "]"); copier = new RemoteCopier(config, c); } copiers.add(copier); copier.start(); } for (AbstractCopier copier : copiers) { copier.join(); } //cleanup FileSystem fs = FileSystem.get(config.getHadoopConf()); fs.delete(config.getTmpPath()); } public static void main(String[] args) throws Exception { String myClusterName = null; Databus databus; if (args != null && args.length >=1) myClusterName = args[0].trim(); else { logger.warn("Specify this cluster name."); return; } if(args.length <= 1) databus = new Databus(myClusterName, null); else { String databusconfigFile = args[1].trim(); databus = new Databus(myClusterName, databusconfigFile); } databus.start(); } }
false
true
public void start() throws Exception { List<AbstractCopier> copiers = new ArrayList<AbstractCopier>(); logger.warn("My clusterName is [" + myClusterName + "] " + config.getDestinationCluster().getName()); for (Cluster c : config.getClusters().values()) { AbstractCopier copier = null; if (myClusterName.equalsIgnoreCase(config.getDestinationCluster().getName())) { logger.warn("Starting data consumer for Cluster[" + myClusterName + "]"); copier = new DataConsumer(config); } else { logger.warn("Starting remote copier for cluster [" + config.getDestinationCluster().getName() + "]"); copier = new RemoteCopier(config, c); } copiers.add(copier); copier.start(); } for (AbstractCopier copier : copiers) { copier.join(); } //cleanup FileSystem fs = FileSystem.get(config.getHadoopConf()); fs.delete(config.getTmpPath()); }
public void start() throws Exception { List<AbstractCopier> copiers = new ArrayList<AbstractCopier>(); logger.warn("My clusterName is [" + myClusterName + "] " + config.getDestinationCluster().getName()); for (Cluster c : config.getClusters().values()) { AbstractCopier copier = null; if (c.getName().equalsIgnoreCase(config.getDestinationCluster().getName())) { logger.warn("Starting data consumer for Cluster[" + c.getName() + "]"); copier = new DataConsumer(config); } else { logger.warn("Starting remote copier for cluster [" + c.getName() + "]"); copier = new RemoteCopier(config, c); } copiers.add(copier); copier.start(); } for (AbstractCopier copier : copiers) { copier.join(); } //cleanup FileSystem fs = FileSystem.get(config.getHadoopConf()); fs.delete(config.getTmpPath()); }
diff --git a/src/main/java/com/topsy/jmxproxy/jmx/ConnectionCredentials.java b/src/main/java/com/topsy/jmxproxy/jmx/ConnectionCredentials.java index fd0cf30..245e1a9 100644 --- a/src/main/java/com/topsy/jmxproxy/jmx/ConnectionCredentials.java +++ b/src/main/java/com/topsy/jmxproxy/jmx/ConnectionCredentials.java @@ -1,35 +1,35 @@ package com.topsy.jmxproxy.jmx; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; public class ConnectionCredentials { @NotEmpty @JsonProperty private final String username; @NotEmpty @JsonProperty private final String password; public ConnectionCredentials(@JsonProperty("username") String username, @JsonProperty("password") String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } @Override public boolean equals(Object peer) { ConnectionCredentials auth = (ConnectionCredentials) peer; - return auth != null && username == auth.getUsername() && password == auth.getPassword(); + return auth != null && username.equals(auth.getUsername()) && password.equals(auth.getPassword()); } }
true
true
public boolean equals(Object peer) { ConnectionCredentials auth = (ConnectionCredentials) peer; return auth != null && username == auth.getUsername() && password == auth.getPassword(); }
public boolean equals(Object peer) { ConnectionCredentials auth = (ConnectionCredentials) peer; return auth != null && username.equals(auth.getUsername()) && password.equals(auth.getPassword()); }
diff --git a/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java b/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java index 3bb324085f..da49f78ade 100644 --- a/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java +++ b/deegree-tests/deegree-wms-similarity-tests/src/test/java/org/deegree/services/wms/WMSSimilarityIntegrationTest.java @@ -1,154 +1,155 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ Occam Labs UG (haftungsbeschränkt) Godesberger Allee 139, 53175 Bonn Germany http://www.occamlabs.de/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.services.wms; import static org.deegree.commons.utils.io.Utils.determineSimilarity; import static org.deegree.commons.utils.net.HttpUtils.STREAM; import static org.deegree.commons.utils.net.HttpUtils.retrieve; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.List; import java.util.ListIterator; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.deegree.commons.utils.math.MathUtils; import org.deegree.commons.utils.test.IntegrationTestUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * <code>WMSSimilarityIntegrationTest</code> * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author: mschneider $ * * @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $ */ @RunWith(Parameterized.class) public class WMSSimilarityIntegrationTest { private static int numFailed = 0; private String request; private List<byte[]> response; public WMSSimilarityIntegrationTest( Object wasXml, String request, List<byte[]> response ) { // we only use .kvp for WMS this.request = request; if ( !this.request.startsWith( "?" ) ) { this.request = "?" + this.request; } this.response = response; } @Parameters public static Collection<Object[]> getParameters() { return IntegrationTestUtils.getTestRequests(); } @Test public void testSimilarity() throws IOException { String base = "http://localhost:" + System.getProperty( "portnumber" ); base += "/deegree-wms-similarity-tests/services" + request; InputStream in = retrieve( STREAM, base ); byte[] bs = null; ListIterator<byte[]> iter = response.listIterator(); while ( iter.hasNext() ) { byte[] resp = iter.next(); try { BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( resp ) ); bs = IOUtils.toByteArray( in ); BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write( img1, "tif", bos ); bos.close(); in = new ByteArrayInputStream( bs = bos.toByteArray() ); bos = new ByteArrayOutputStream(); bos.close(); ImageIO.write( img2, "tif", bos ); iter.set( bos.toByteArray() ); } catch ( Throwable t ) { t.printStackTrace(); // just compare initial byte arrays } } double sim = 0; for ( byte[] response : this.response ) { - if ( MathUtils.isZero( sim ) || Math.abs( 1.0 - sim ) > 0.01 ) { + in = new ByteArrayInputStream( bs ); + if ( MathUtils.isZero( sim ) || Math.abs( 1.0 - sim ) > 0.01 || Double.isNaN( sim ) ) { sim = Math.max( sim, determineSimilarity( in, new ByteArrayInputStream( response ) ) ); } } if ( Math.abs( 1.0 - sim ) > 0.01 ) { System.out.println( "Trying to store request/response in tempdir: expected/response" + ++numFailed + ".tif" ); try { int idx = 0; for ( byte[] response : this.response ) { IOUtils.write( response, new FileOutputStream( System.getProperty( "java.io.tmpdir" ) + "/expected" + ++idx + "_" + numFailed + ".tif" ) ); } IOUtils.write( bs, new FileOutputStream( System.getProperty( "java.io.tmpdir" ) + "/response" + numFailed + ".tif" ) ); } catch ( Throwable t ) { } } Assert.assertEquals( "Images are not similar enough. Request: " + request, 1.0, sim, 0.01 ); } }
true
true
public void testSimilarity() throws IOException { String base = "http://localhost:" + System.getProperty( "portnumber" ); base += "/deegree-wms-similarity-tests/services" + request; InputStream in = retrieve( STREAM, base ); byte[] bs = null; ListIterator<byte[]> iter = response.listIterator(); while ( iter.hasNext() ) { byte[] resp = iter.next(); try { BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( resp ) ); bs = IOUtils.toByteArray( in ); BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write( img1, "tif", bos ); bos.close(); in = new ByteArrayInputStream( bs = bos.toByteArray() ); bos = new ByteArrayOutputStream(); bos.close(); ImageIO.write( img2, "tif", bos ); iter.set( bos.toByteArray() ); } catch ( Throwable t ) { t.printStackTrace(); // just compare initial byte arrays } } double sim = 0; for ( byte[] response : this.response ) { if ( MathUtils.isZero( sim ) || Math.abs( 1.0 - sim ) > 0.01 ) { sim = Math.max( sim, determineSimilarity( in, new ByteArrayInputStream( response ) ) ); } } if ( Math.abs( 1.0 - sim ) > 0.01 ) { System.out.println( "Trying to store request/response in tempdir: expected/response" + ++numFailed + ".tif" ); try { int idx = 0; for ( byte[] response : this.response ) { IOUtils.write( response, new FileOutputStream( System.getProperty( "java.io.tmpdir" ) + "/expected" + ++idx + "_" + numFailed + ".tif" ) ); } IOUtils.write( bs, new FileOutputStream( System.getProperty( "java.io.tmpdir" ) + "/response" + numFailed + ".tif" ) ); } catch ( Throwable t ) { } } Assert.assertEquals( "Images are not similar enough. Request: " + request, 1.0, sim, 0.01 ); }
public void testSimilarity() throws IOException { String base = "http://localhost:" + System.getProperty( "portnumber" ); base += "/deegree-wms-similarity-tests/services" + request; InputStream in = retrieve( STREAM, base ); byte[] bs = null; ListIterator<byte[]> iter = response.listIterator(); while ( iter.hasNext() ) { byte[] resp = iter.next(); try { BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( resp ) ); bs = IOUtils.toByteArray( in ); BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write( img1, "tif", bos ); bos.close(); in = new ByteArrayInputStream( bs = bos.toByteArray() ); bos = new ByteArrayOutputStream(); bos.close(); ImageIO.write( img2, "tif", bos ); iter.set( bos.toByteArray() ); } catch ( Throwable t ) { t.printStackTrace(); // just compare initial byte arrays } } double sim = 0; for ( byte[] response : this.response ) { in = new ByteArrayInputStream( bs ); if ( MathUtils.isZero( sim ) || Math.abs( 1.0 - sim ) > 0.01 || Double.isNaN( sim ) ) { sim = Math.max( sim, determineSimilarity( in, new ByteArrayInputStream( response ) ) ); } } if ( Math.abs( 1.0 - sim ) > 0.01 ) { System.out.println( "Trying to store request/response in tempdir: expected/response" + ++numFailed + ".tif" ); try { int idx = 0; for ( byte[] response : this.response ) { IOUtils.write( response, new FileOutputStream( System.getProperty( "java.io.tmpdir" ) + "/expected" + ++idx + "_" + numFailed + ".tif" ) ); } IOUtils.write( bs, new FileOutputStream( System.getProperty( "java.io.tmpdir" ) + "/response" + numFailed + ".tif" ) ); } catch ( Throwable t ) { } } Assert.assertEquals( "Images are not similar enough. Request: " + request, 1.0, sim, 0.01 ); }
diff --git a/src/realtalk/util/ChatManager.java b/src/realtalk/util/ChatManager.java index 814f4ba..574e1ca 100644 --- a/src/realtalk/util/ChatManager.java +++ b/src/realtalk/util/ChatManager.java @@ -1,476 +1,475 @@ package realtalk.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.io.IOException; import java.io.InputStream; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * ChatManager is a helper class that allows the Android side of RealTalk to cleanly * communicate with the server while keeping it abstracted. * * @author Taylor Williams * */ public final class ChatManager { //HUNGARIAN TAGS: // rrs RequestResultSet // pmrs PullMessageResultSet // crrs ChatRoomResultSet public static final String URL_QUALIFIER = CommonUtilities.URL_QUALIFIER; //User servlets public static final String URL_ADD_USER = CommonUtilities.URL_ADD_USER; public static final String URL_REMOVE_USER = CommonUtilities.URL_REMOVE_USER; public static final String URL_AUTHENTICATE = CommonUtilities.URL_AUTHENTICATE; public static final String URL_CHANGE_PASSWORD = CommonUtilities.URL_CHANGE_PASSWORD; public static final String URL_CHANGE_ID = CommonUtilities.URL_CHANGE_ID; //Chat room servlets public static final String URL_ADD_ROOM = CommonUtilities.URL_ADD_ROOM; public static final String URL_JOIN_ROOM = CommonUtilities.URL_JOIN_ROOM; public static final String URL_LEAVE_ROOM = CommonUtilities.URL_LEAVE_ROOM; public static final String URL_POST_MESSAGE = CommonUtilities.URL_POST_MESSAGE; public static final String URL_GET_RECENT_MESSAGES = CommonUtilities.URL_GET_RECENT_MESSAGES; public static final String URL_GET_ALL_MESSAGES = CommonUtilities.URL_GET_ALL_MESSAGES; public static final String URL_GET_NEARBY_CHATROOMS = CommonUtilities.URL_GET_NEARBY_CHATROOMS; public static final String URL_GET_USERS_ROOMS = CommonUtilities.URL_GET_USERS_ROOMS; /** * Private contructor prevents this class from being instantiated. */ private ChatManager() { throw new UnsupportedOperationException("ChatManager is a utility class and should not be instantiated."); } /** * This method makes a request to the server using the given url and params and parses * the expected JSON response as a JSON Object. If the call fails or if the response is * not valid json, an empty JSON Object is returned. * * @param stUrl Url to query from. * @param rgparams Params to use. * @return JSONObject that describes the response. */ private static JSONObject makeRequest(String stUrl, List<NameValuePair> rgparams) { // Retrieve Stream from URL InputStream inputstreamResponse = null; try { inputstreamResponse = HttpUtility.sendPostRequest(stUrl, rgparams); } catch (UnsupportedOperationException e) { e.printStackTrace(); return new JSONObject(); } catch (ClientProtocolException e) { e.printStackTrace(); return new JSONObject(); } catch (IOException e) { e.printStackTrace(); return new JSONObject(); } // Parse Stream to JSON Object JSONObject jsonobjectResponse = null; try { jsonobjectResponse = JSONParser.parseStream(inputstreamResponse); } catch (JSONException e) { e.printStackTrace(); return new JSONObject(); } catch (IOException e) { e.printStackTrace(); return new JSONObject(); } return jsonobjectResponse; } /** * @param messageinfo Message info object * @return the list of parameters as basic name value pairs * @throws UnsupportedEncodingException */ private static List<NameValuePair> rgparamsMessageInfo(MessageInfo messageinfo) throws UnsupportedEncodingException { List<NameValuePair> rgparams = new ArrayList<NameValuePair>(); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_MESSAGE_TIMESTAMP, Long.valueOf(messageinfo.timestampGet().getTime()).toString())); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_MESSAGE_BODY, URLEncoder.encode(messageinfo.stBody(), "UTF-8"))); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_MESSAGE_SENDER, URLEncoder.encode(messageinfo.stSender(), "UTF-8"))); return rgparams; } /** * @param userinfo User info object * @return the list of parameters as basic name value pairs * @throws UnsupportedEncodingException */ private static List<NameValuePair> rgparamsUserBasicInfo(UserInfo userinfo) throws UnsupportedEncodingException { List<NameValuePair> rgparams = new ArrayList<NameValuePair>(); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_REG_ID, userinfo.stRegistrationId())); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_USER, URLEncoder.encode(userinfo.stUserName(), "UTF-8"))); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_PWORD, userinfo.stPassword())); return rgparams; } /** * @param chatroominfo Chat room info object * @return the list of parameters as basic name value pairs * @throws UnsupportedEncodingException */ private static List<NameValuePair> rgparamsChatRoomBasicInfo(ChatRoomInfo chatroominfo) throws UnsupportedEncodingException { List<NameValuePair> rgparams = new ArrayList<NameValuePair>(); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_ROOM_NAME, URLEncoder.encode(chatroominfo.stName(), "UTF_8"))); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_ROOM_ID, chatroominfo.stId())); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_ROOM_DESCRIPTION, URLEncoder.encode(chatroominfo.stDescription(), "UTF-8"))); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_USER_LATITUDE, Double.valueOf(chatroominfo.getLatitude()).toString())); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_USER_LONGITUDE, Double.valueOf(chatroominfo.getLongitude()).toString())); return rgparams; } /** * @param latitude * @param longitude * @param radiusMeters * @return the list of parameters as basic name value pairs */ private static List<NameValuePair> rgparamsLocationInfo(double latitude, double longitude, double radiusMeters) { List<NameValuePair> rgparams = new ArrayList<NameValuePair>(); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_USER_LATITUDE, Double.valueOf(latitude).toString())); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_USER_LONGITUDE, Double.valueOf(longitude).toString())); rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_USER_RADIUS, Double.valueOf(radiusMeters).toString())); return rgparams; } /** * * @param fAnon * @return a parameter for anonymous login as a basic name value pair */ private static NameValuePair paramAnonymous(boolean fAnon) { return new BasicNameValuePair(RequestParameters.PARAMETER_ANON, String.valueOf(fAnon)); } /** * @param rgparam List of parameters to embed in the request * @param stUrl The url to send the request to * @return A RequestResultSet containing the result of the request */ private static RequestResultSet rrsPostRequest(List<NameValuePair> rgparam, String stUrl) { JSONObject json = makeRequest(stUrl, rgparam); try { boolean fSucceeded = json.getString(RequestParameters.PARAMETER_SUCCESS).equals("true"); String stErrorCode = fSucceeded ? "NO ERROR MESSAGE" : json.getString(ResponseParameters.PARAMETER_ERROR_CODE); String stErrorMessage = fSucceeded ? "NO ERROR MESSAGE" : json.getString(ResponseParameters.PARAMETER_ERROR_MSG); return new RequestResultSet(fSucceeded, stErrorCode, stErrorMessage); } catch (JSONException e) { e.printStackTrace(); //if all else fails, return generic error code and message return new RequestResultSet(false, "REQUEST FAILED", "REQUEST FAILED"); } } /** * @param rgparam List of parameters to embed in the request * @param stUrl The url to send the request to * @return A RequestResultSet containing the result of the request */ private static ChatRoomResultSet crrsPostRequest(List<NameValuePair> rgparam, String stUrl) { JSONObject json = makeRequest(stUrl, rgparam); try { boolean fSucceeded = json.getString(RequestParameters.PARAMETER_SUCCESS).equals("true"); if (fSucceeded) { List<ChatRoomInfo> rgchatroominfo = new ArrayList<ChatRoomInfo>(); //get list of rooms from response JSONArray rgroom = json.getJSONArray(RequestParameters.PARAMETER_ROOM_ROOMS); for (int i = 0; i < rgroom.length(); i++) { JSONObject jsonobject = rgroom.getJSONObject(i); String stName = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_NAME), "UTF-8"); String stId = jsonobject.getString(RequestParameters.PARAMETER_ROOM_ID); String stDescription = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_DESCRIPTION), "UTF-8"); double latitude = jsonobject.getDouble(RequestParameters.PARAMETER_ROOM_LATITUDE); double longitude = jsonobject.getDouble(RequestParameters.PARAMETER_ROOM_LONGITUDE); String stCreator = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_CREATOR), "UTF-8"); int numUsers = jsonobject.getInt(RequestParameters.PARAMETER_ROOM_NUM_USERS); long ticks = jsonobject.getLong(RequestParameters.PARAMETER_TIMESTAMP); rgchatroominfo.add(new ChatRoomInfo(stName, stId, stDescription, latitude, longitude, stCreator, numUsers, new Timestamp(ticks))); } return new ChatRoomResultSet(true, rgchatroominfo, "NO ERROR CODE", "NO ERROR MESSAGE"); } return new ChatRoomResultSet(false, ResponseParameters.RESPONSE_ERROR_CODE_ROOM, ResponseParameters.RESPONSE_MESSAGE_ERROR); } catch (JSONException e) { e.printStackTrace(); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //if all else fails, return generic error code and message return new ChatRoomResultSet(false, "REQUEST FAILED", "REQUEST FAILED"); } /** Sends a message/chatroom specific request. * @param rgparam List of parameters to embed in the request * @param stUrl The url to send the request to * @return A PullMessageResultSet containing the result of the request */ private static PullMessageResultSet pmrsPostRequest(List<NameValuePair> rgparam, String stUrl) { JSONObject json = makeRequest(stUrl, rgparam); try { boolean fSucceeded = json.getString(RequestParameters.PARAMETER_SUCCESS).equals("true"); if (fSucceeded) { List<MessageInfo> rgmessageinfo = new ArrayList<MessageInfo>(); JSONArray rgmessage = json.getJSONArray(RequestParameters.PARAMETER_MESSAGE_MESSAGES); for (int i = 0; i < rgmessage.length(); i++) { JSONObject jsonobject = rgmessage.getJSONObject(i); String stBody = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_MESSAGE_BODY), "UTF-8"); long ticks = jsonobject.getLong(RequestParameters.PARAMETER_MESSAGE_TIMESTAMP); String stSender = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_MESSAGE_SENDER), "UTF-8"); rgmessageinfo.add(new MessageInfo(stBody, stSender, ticks)); } return new PullMessageResultSet(true, rgmessageinfo, "NO ERROR CODE", "NO ERROR MESSAGE"); } return new PullMessageResultSet(false, new ArrayList<MessageInfo>(), json.getString(ResponseParameters.PARAMETER_ERROR_CODE), json.getString(ResponseParameters.PARAMETER_ERROR_MSG)); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //if all else fails, return generic error code and message return new PullMessageResultSet(false, "REQUEST FAILED", "REQUEST FAILED"); } /** Authenticates a user * @param userinfo The user to authenticate * @return A resultset containing the result of the authentication */ public static RequestResultSet rrsAuthenticateUser(UserInfo userinfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_AUTHENTICATE); } /** Adds a user * @param userinfo The user to add * @return A resultset containing the result of the addition */ public static RequestResultSet rrsAddUser(UserInfo userinfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_ADD_USER); } /** Remove a user * @param userinfo The user to remove * @return A resultset containing the result of the removal */ public static RequestResultSet rrsRemoveUser(UserInfo userinfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_REMOVE_USER); } /** Changes a user's password * @param userinfo The user to change * @param stPasswordNew The new password * @return A resultset containing the result of the change */ public static RequestResultSet rrsChangePassword(UserInfo userinfo, String stPasswordNew) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_NEW_PWORD, stPasswordNew)); return rrsPostRequest(rgparams, URL_CHANGE_PASSWORD); } /** Changes a user's ID * @param userinfo The user to change * @param stIdNew The new ID * @return A resultset containing the result of the change */ public static RequestResultSet rrsChangeID(UserInfo userinfo, String stIdNew) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_NEW_REG_ID, stIdNew)); return rrsPostRequest(rgparams, URL_CHANGE_ID); } /** Adds a new chatroom * @param chatroominfo The chatroom to add * @param userinfo The user to associate with the new room * @return A resultset containing the result of the addition */ public static RequestResultSet rrsAddRoom(ChatRoomInfo chatroominfo, UserInfo userinfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsChatRoomBasicInfo(chatroominfo); rgparams.addAll(rgparamsUserBasicInfo(userinfo)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_ADD_ROOM); } /** Joins a user to a chatroom * @param chatroominfo The chatroom to join * @param userinfo The user to join into the room * @return A resultset containing the result of the join */ public static RequestResultSet rrsJoinRoom(UserInfo userinfo, ChatRoomInfo chatroominfo, boolean fAnon) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); rgparams.addAll(rgparamsChatRoomBasicInfo(chatroominfo)); rgparams.add(paramAnonymous(fAnon)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_JOIN_ROOM); } /** Leaves a chatroom * @param chatroominfo The chatroom to leave * @param userinfo The user leaving the room * @return A resultset containing the result of the leave */ public static RequestResultSet rrsLeaveRoom(UserInfo userinfo, ChatRoomInfo chatroominfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); rgparams.addAll(rgparamsChatRoomBasicInfo(chatroominfo)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_LEAVE_ROOM); } /** Posts a message to a chatroom * @param chatroominfo The chatroom to post a message to * @param userinfo The user posting the message * @return A resultset containing the result of the post */ public static RequestResultSet rrsPostMessage(UserInfo userinfo, ChatRoomInfo chatroominfo, MessageInfo message) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); rgparams.addAll(rgparamsChatRoomBasicInfo(chatroominfo)); rgparams.addAll(rgparamsMessageInfo(message)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rrsPostRequest(rgparams, URL_POST_MESSAGE); } /** Returns the chatlog for a certain chatroom * @param chatroominfo The chatroom to pull the log from * @return A resultset containing the result of the pull */ public static PullMessageResultSet pmrsChatLogGet(ChatRoomInfo chatroominfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsChatRoomBasicInfo(chatroominfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return pmrsPostRequest(rgparams, URL_GET_ALL_MESSAGES); } /** * This method pulls all recent messages to a specific given chatroom after a given time as indicated * in timestamp * * @param chatroominfo Information about chatroom to pull messages from. * @param timestamp Time * @return Result set that contains a boolean that indicates success or failure and * returns an error code and message if failure was occurred. If success, * it returns a list of MessageInfo that have a timestamp later than the given * timestamp * */ @Deprecated public static PullMessageResultSet pmrsChatRecentChat(ChatRoomInfo chatroominfo, Timestamp timestamp) { long rawtimestamp = timestamp.getTime(); String stTimestamp = ""; try { stTimestamp = String.valueOf(rawtimestamp); } catch (NumberFormatException e) { e.printStackTrace(); return new PullMessageResultSet(false, "ERROR_INVALID_TIMESTAMP", "ERROR_MESSAGE_PARSING_ERROR"); } List<NameValuePair> rgparams = null; try { rgparams = rgparamsChatRoomBasicInfo(chatroominfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } rgparams.add(new BasicNameValuePair(RequestParameters.PARAMETER_TIMESTAMP, stTimestamp)); return pmrsPostRequest(rgparams, URL_GET_RECENT_MESSAGES); } /** * This method pulls all nearby chatrooms, given a latitude, longitude, and a radius. * * @param latitude users latitude * @param longitude users longitude * @param radiusMeters radius from the user in which to find chatrooms * @return Result set that contains a boolean that indicates success or failure and * returns an error code and message if failure was occurred. If success, * it holds a list of ChatRoomInfo objects describing the nearby rooms. */ public static ChatRoomResultSet crrsNearbyChatrooms(double latitude, double longitude, double radiusMeters) { List<NameValuePair> rgparams = rgparamsLocationInfo(latitude, longitude, radiusMeters); return crrsPostRequest(rgparams, URL_GET_NEARBY_CHATROOMS); } /** * This method pulls all chatrooms that the given user has joined from the server * * @param userinfo Information about the user * @return Result set that contains a boolean that indicates success or failure and * returns an error code and message if failure was occurred. If success, * it holds a list of ChatRoomInfo objects describing the user's rooms. */ public static ChatRoomResultSet crrsUsersChatrooms(UserInfo userinfo) { List<NameValuePair> rgparams = null; try { rgparams = rgparamsUserBasicInfo(userinfo); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return crrsPostRequest(rgparams, URL_GET_USERS_ROOMS); } }
true
true
private static ChatRoomResultSet crrsPostRequest(List<NameValuePair> rgparam, String stUrl) { JSONObject json = makeRequest(stUrl, rgparam); try { boolean fSucceeded = json.getString(RequestParameters.PARAMETER_SUCCESS).equals("true"); if (fSucceeded) { List<ChatRoomInfo> rgchatroominfo = new ArrayList<ChatRoomInfo>(); //get list of rooms from response JSONArray rgroom = json.getJSONArray(RequestParameters.PARAMETER_ROOM_ROOMS); for (int i = 0; i < rgroom.length(); i++) { JSONObject jsonobject = rgroom.getJSONObject(i); String stName = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_NAME), "UTF-8"); String stId = jsonobject.getString(RequestParameters.PARAMETER_ROOM_ID); String stDescription = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_DESCRIPTION), "UTF-8"); double latitude = jsonobject.getDouble(RequestParameters.PARAMETER_ROOM_LATITUDE); double longitude = jsonobject.getDouble(RequestParameters.PARAMETER_ROOM_LONGITUDE); String stCreator = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_CREATOR), "UTF-8"); int numUsers = jsonobject.getInt(RequestParameters.PARAMETER_ROOM_NUM_USERS); long ticks = jsonobject.getLong(RequestParameters.PARAMETER_TIMESTAMP); rgchatroominfo.add(new ChatRoomInfo(stName, stId, stDescription, latitude, longitude, stCreator, numUsers, new Timestamp(ticks))); } return new ChatRoomResultSet(true, rgchatroominfo, "NO ERROR CODE", "NO ERROR MESSAGE"); } return new ChatRoomResultSet(false, ResponseParameters.RESPONSE_ERROR_CODE_ROOM, ResponseParameters.RESPONSE_MESSAGE_ERROR); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //if all else fails, return generic error code and message return new ChatRoomResultSet(false, "REQUEST FAILED", "REQUEST FAILED"); }
private static ChatRoomResultSet crrsPostRequest(List<NameValuePair> rgparam, String stUrl) { JSONObject json = makeRequest(stUrl, rgparam); try { boolean fSucceeded = json.getString(RequestParameters.PARAMETER_SUCCESS).equals("true"); if (fSucceeded) { List<ChatRoomInfo> rgchatroominfo = new ArrayList<ChatRoomInfo>(); //get list of rooms from response JSONArray rgroom = json.getJSONArray(RequestParameters.PARAMETER_ROOM_ROOMS); for (int i = 0; i < rgroom.length(); i++) { JSONObject jsonobject = rgroom.getJSONObject(i); String stName = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_NAME), "UTF-8"); String stId = jsonobject.getString(RequestParameters.PARAMETER_ROOM_ID); String stDescription = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_DESCRIPTION), "UTF-8"); double latitude = jsonobject.getDouble(RequestParameters.PARAMETER_ROOM_LATITUDE); double longitude = jsonobject.getDouble(RequestParameters.PARAMETER_ROOM_LONGITUDE); String stCreator = URLDecoder.decode(jsonobject.getString(RequestParameters.PARAMETER_ROOM_CREATOR), "UTF-8"); int numUsers = jsonobject.getInt(RequestParameters.PARAMETER_ROOM_NUM_USERS); long ticks = jsonobject.getLong(RequestParameters.PARAMETER_TIMESTAMP); rgchatroominfo.add(new ChatRoomInfo(stName, stId, stDescription, latitude, longitude, stCreator, numUsers, new Timestamp(ticks))); } return new ChatRoomResultSet(true, rgchatroominfo, "NO ERROR CODE", "NO ERROR MESSAGE"); } return new ChatRoomResultSet(false, ResponseParameters.RESPONSE_ERROR_CODE_ROOM, ResponseParameters.RESPONSE_MESSAGE_ERROR); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //if all else fails, return generic error code and message return new ChatRoomResultSet(false, "REQUEST FAILED", "REQUEST FAILED"); }
diff --git a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java index a6017da4..b48a43d6 100644 --- a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java +++ b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java @@ -1,171 +1,172 @@ /* Copyright (c) 2002-2011 by XMLVM.org * * Project Info: http://www.xmlvm.org * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package org.xmlvm.iphone; import java.io.File; import java.io.FileInputStream; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public class NSBundle extends NSObject { private static final String SYSRES = "/sys_resources"; private static final String CLASS_RESOURCE_LIST = "/META-INF/list.resources"; private static final String XCODE_RESOURCE_LIST = System.getProperty("user.dir") + File.separator + "xmlvm.properties"; private static NSBundle mainBundle = new NSBundle(); private static Set<String> runtime_res; private NSBundle() { } public static NSBundle mainBundle() { return mainBundle; } public String pathForResource(String resource, String type, String directory) { /* Calculate file name */ String filename = type == null ? resource : resource + "." + type; if (directory != null && !directory.equals("")) { filename = directory + "/" + filename; } /* Check if the resource file has an absolute pathname */ - if (filename.startsWith(File.separator) && new File(filename).exists()) { + File file = new File(filename); + if (file.isAbsolute() && file.exists()) { return filename; } /* Check it as a local resource file */ for (String dname : getDeclaredResources()) { File dfile = new File(dname); try { if (dfile.isFile()) { // Resource is a file if (dfile.getName().equals(filename)) return dfile.getAbsolutePath(); } else { // Resource is a directory File req = null; if (dname.endsWith("/")) // Search inside directory req = new File(dfile, filename); else { // Take into account resource directory int slash = filename.indexOf('/'); String doubledir = filename.substring(0, slash); if (doubledir.equals(dfile.getName())) // Only if both // directories // are the same req = new File(dfile, filename.substring(slash + 1)); } if (req != null && req.exists()) return req.getAbsolutePath(); } } catch (Exception ex) { } } /* * If file was not found, search as a system resource file. This is a * rare case and used only internally for the emulator. * * Please do not use it in your own projects. Use "xmlvm.resource" in * file "xmlvm.properties" instead. */ String sysfilename = SYSRES + (filename.startsWith("/") ? "" : "/") + filename; try { String path = getClass().getResource(sysfilename).toURI().toURL().toString(); if (path != null) { return path; } } catch (Exception ex) { } /* Not found */ return null; } public String pathForResource(String resource, String type) { return pathForResource(resource, type, null); } public String bundlePath() { // First we assume that we are running an Android app and we use the // 'res' directory // to locate the proper classpath location. We have to do this since the // classpath // usually consists of several directories and we use 'res' as a unique // identifier // to locate the correct location. String path = pathForResource("", null, "res"); if (path == null) { // We are not running an Android app. Just return the main directory // in this case File res = new File(getClass().getResource("/").getFile()); if (res.exists()) { return res.getAbsolutePath(); } return null; } return new File(path).getParent(); } /** * Runtime resources, given as a special file under * ${CLASSPATH}/META-INF/xmlvm.properties or under * ${user.dir}/xmlvm.properties * * This is required in order to run applications as Java from the command * line. */ private static Set<String> getDeclaredResources() { if (runtime_res == null) { runtime_res = new HashSet<String>(); Properties pr = new Properties(); try { // Load resources definition in the META-INF directory pr.load(NSBundle.class.getResourceAsStream(CLASS_RESOURCE_LIST)); } catch (Exception ex1) { try { pr.load(new FileInputStream(XCODE_RESOURCE_LIST)); } catch (Exception ex2) { return runtime_res; } } String path = pr.getProperty("xmlvm.resource.path", System.getProperty("user.dir")); if (!path.endsWith(File.separator)) path += File.separator; String list = pr.getProperty("xmlvm.resource", ""); StringTokenizer tk = new StringTokenizer(list, ":"); while (tk.hasMoreTokens()) { String item = tk.nextToken(); if (item.startsWith(File.separator)) runtime_res.add(item); else runtime_res.add(path + item); } } return runtime_res; } }
true
true
public String pathForResource(String resource, String type, String directory) { /* Calculate file name */ String filename = type == null ? resource : resource + "." + type; if (directory != null && !directory.equals("")) { filename = directory + "/" + filename; } /* Check if the resource file has an absolute pathname */ if (filename.startsWith(File.separator) && new File(filename).exists()) { return filename; } /* Check it as a local resource file */ for (String dname : getDeclaredResources()) { File dfile = new File(dname); try { if (dfile.isFile()) { // Resource is a file if (dfile.getName().equals(filename)) return dfile.getAbsolutePath(); } else { // Resource is a directory File req = null; if (dname.endsWith("/")) // Search inside directory req = new File(dfile, filename); else { // Take into account resource directory int slash = filename.indexOf('/'); String doubledir = filename.substring(0, slash); if (doubledir.equals(dfile.getName())) // Only if both // directories // are the same req = new File(dfile, filename.substring(slash + 1)); } if (req != null && req.exists()) return req.getAbsolutePath(); } } catch (Exception ex) { } } /* * If file was not found, search as a system resource file. This is a * rare case and used only internally for the emulator. * * Please do not use it in your own projects. Use "xmlvm.resource" in * file "xmlvm.properties" instead. */ String sysfilename = SYSRES + (filename.startsWith("/") ? "" : "/") + filename; try { String path = getClass().getResource(sysfilename).toURI().toURL().toString(); if (path != null) { return path; } } catch (Exception ex) { } /* Not found */ return null; }
public String pathForResource(String resource, String type, String directory) { /* Calculate file name */ String filename = type == null ? resource : resource + "." + type; if (directory != null && !directory.equals("")) { filename = directory + "/" + filename; } /* Check if the resource file has an absolute pathname */ File file = new File(filename); if (file.isAbsolute() && file.exists()) { return filename; } /* Check it as a local resource file */ for (String dname : getDeclaredResources()) { File dfile = new File(dname); try { if (dfile.isFile()) { // Resource is a file if (dfile.getName().equals(filename)) return dfile.getAbsolutePath(); } else { // Resource is a directory File req = null; if (dname.endsWith("/")) // Search inside directory req = new File(dfile, filename); else { // Take into account resource directory int slash = filename.indexOf('/'); String doubledir = filename.substring(0, slash); if (doubledir.equals(dfile.getName())) // Only if both // directories // are the same req = new File(dfile, filename.substring(slash + 1)); } if (req != null && req.exists()) return req.getAbsolutePath(); } } catch (Exception ex) { } } /* * If file was not found, search as a system resource file. This is a * rare case and used only internally for the emulator. * * Please do not use it in your own projects. Use "xmlvm.resource" in * file "xmlvm.properties" instead. */ String sysfilename = SYSRES + (filename.startsWith("/") ? "" : "/") + filename; try { String path = getClass().getResource(sysfilename).toURI().toURL().toString(); if (path != null) { return path; } } catch (Exception ex) { } /* Not found */ return null; }
diff --git a/server/co2-restlet/src/restlet/gc/carbon/environment/ItemValueDefinitionResource.java b/server/co2-restlet/src/restlet/gc/carbon/environment/ItemValueDefinitionResource.java index a3eedecc..59410984 100644 --- a/server/co2-restlet/src/restlet/gc/carbon/environment/ItemValueDefinitionResource.java +++ b/server/co2-restlet/src/restlet/gc/carbon/environment/ItemValueDefinitionResource.java @@ -1,170 +1,168 @@ /** * This file is part of AMEE. * * 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. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Created by http://www.dgen.net. * Website http://www.amee.cc */ package gc.carbon.environment; import com.jellymold.utils.BaseResource; import gc.carbon.data.DataConstants; import gc.carbon.definition.DefinitionServiceDAO; import gc.carbon.domain.data.ItemValueDefinition; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Context; import org.restlet.data.Form; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.resource.Representation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.Serializable; import java.util.Map; import java.util.Set; // TODO: Add ValueDefinition choice. @Component @Scope("prototype") public class ItemValueDefinitionResource extends BaseResource implements Serializable { private final Log log = LogFactory.getLog(getClass()); @Autowired private DefinitionServiceDAO definitionServiceDAO; @Autowired private DefinitionBrowser definitionBrowser; @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); definitionBrowser.setEnvironmentUid(request.getAttributes().get("environmentUid").toString()); definitionBrowser.setItemDefinitionUid(request.getAttributes().get("itemDefinitionUid").toString()); definitionBrowser.setItemValueDefinitionUid(request.getAttributes().get("itemValueDefinitionUid").toString()); } @Override public boolean isValid() { return super.isValid() && (definitionBrowser.getItemValueDefinition() != null); } @Override public String getTemplatePath() { return DataConstants.VIEW_ITEM_VALUE_DEFINITION; } @Override public Map<String, Object> getTemplateValues() { Map<String, Object> values = super.getTemplateValues(); values.put("browser", definitionBrowser); values.put("environment", definitionBrowser.getEnvironment()); values.put("itemDefinition", definitionBrowser.getItemDefinition()); values.put("itemValueDefinition", definitionBrowser.getItemValueDefinition()); return values; } @Override public JSONObject getJSONObject() throws JSONException { JSONObject obj = new JSONObject(); obj.put("itemValueDefinition", definitionBrowser.getItemValueDefinition().getJSONObject()); return obj; } @Override public Element getElement(Document document) { Element element = document.createElement("ItemValueDefinitionResource"); element.appendChild(definitionBrowser.getItemValueDefinition().getElement(document)); return element; } @Override public void handleGet() { log.debug("handleGet()"); if (definitionBrowser.getItemDefinitionActions().isAllowView()) { super.handleGet(); } else { notAuthorized(); } } @Override public boolean allowPut() { return true; } @Override public void storeRepresentation(Representation entity) { log.debug("storeRepresentation()"); if (definitionBrowser.getItemDefinitionActions().isAllowModify()) { ItemValueDefinition itemValueDefinition = definitionBrowser.getItemValueDefinition(); Form form = getForm(); Set<String> names = form.getNames(); if (names.contains("name")) { itemValueDefinition.setName(form.getFirstValue("name")); } if (names.contains("path")) { itemValueDefinition.setPath(form.getFirstValue("path")); } if (names.contains("value")) { // TODO: validation based on ValueType - pass to ValueType? itemValueDefinition.setValue(form.getFirstValue("value")); } if (names.contains("choices")) { itemValueDefinition.setChoices(form.getFirstValue("choices")); } if (names.contains("fromProfile")) { itemValueDefinition.setFromProfile(Boolean.valueOf(form.getFirstValue("fromProfile"))); } if (names.contains("fromData")) { itemValueDefinition.setFromData(Boolean.valueOf(form.getFirstValue("fromData"))); } if (names.contains("allowedRoles")) { itemValueDefinition.setAllowedRoles(form.getFirstValue("allowedRoles")); } success(); - Integer x = null; - x.byteValue(); } else { notAuthorized(); } } @Override public boolean allowDelete() { return true; } @Override public void removeRepresentations() { log.debug("removeRepresentations()"); if (definitionBrowser.getItemDefinitionActions().isAllowModify()) { ItemValueDefinition itemValueDefinition = definitionBrowser.getItemValueDefinition(); definitionBrowser.getItemDefinition().remove(itemValueDefinition); definitionServiceDAO.remove(itemValueDefinition); success(); } else { notAuthorized(); } } }
true
true
public void storeRepresentation(Representation entity) { log.debug("storeRepresentation()"); if (definitionBrowser.getItemDefinitionActions().isAllowModify()) { ItemValueDefinition itemValueDefinition = definitionBrowser.getItemValueDefinition(); Form form = getForm(); Set<String> names = form.getNames(); if (names.contains("name")) { itemValueDefinition.setName(form.getFirstValue("name")); } if (names.contains("path")) { itemValueDefinition.setPath(form.getFirstValue("path")); } if (names.contains("value")) { // TODO: validation based on ValueType - pass to ValueType? itemValueDefinition.setValue(form.getFirstValue("value")); } if (names.contains("choices")) { itemValueDefinition.setChoices(form.getFirstValue("choices")); } if (names.contains("fromProfile")) { itemValueDefinition.setFromProfile(Boolean.valueOf(form.getFirstValue("fromProfile"))); } if (names.contains("fromData")) { itemValueDefinition.setFromData(Boolean.valueOf(form.getFirstValue("fromData"))); } if (names.contains("allowedRoles")) { itemValueDefinition.setAllowedRoles(form.getFirstValue("allowedRoles")); } success(); Integer x = null; x.byteValue(); } else { notAuthorized(); } }
public void storeRepresentation(Representation entity) { log.debug("storeRepresentation()"); if (definitionBrowser.getItemDefinitionActions().isAllowModify()) { ItemValueDefinition itemValueDefinition = definitionBrowser.getItemValueDefinition(); Form form = getForm(); Set<String> names = form.getNames(); if (names.contains("name")) { itemValueDefinition.setName(form.getFirstValue("name")); } if (names.contains("path")) { itemValueDefinition.setPath(form.getFirstValue("path")); } if (names.contains("value")) { // TODO: validation based on ValueType - pass to ValueType? itemValueDefinition.setValue(form.getFirstValue("value")); } if (names.contains("choices")) { itemValueDefinition.setChoices(form.getFirstValue("choices")); } if (names.contains("fromProfile")) { itemValueDefinition.setFromProfile(Boolean.valueOf(form.getFirstValue("fromProfile"))); } if (names.contains("fromData")) { itemValueDefinition.setFromData(Boolean.valueOf(form.getFirstValue("fromData"))); } if (names.contains("allowedRoles")) { itemValueDefinition.setAllowedRoles(form.getFirstValue("allowedRoles")); } success(); } else { notAuthorized(); } }
diff --git a/src/main/java/com/norcode/bukkit/buildinabox/datastore/YamlDataStore.java b/src/main/java/com/norcode/bukkit/buildinabox/datastore/YamlDataStore.java index 1472626..49dc2f4 100644 --- a/src/main/java/com/norcode/bukkit/buildinabox/datastore/YamlDataStore.java +++ b/src/main/java/com/norcode/bukkit/buildinabox/datastore/YamlDataStore.java @@ -1,253 +1,252 @@ package com.norcode.bukkit.buildinabox.datastore; import com.norcode.bukkit.buildinabox.BuildChest; import com.norcode.bukkit.buildinabox.BuildInABox; import com.norcode.bukkit.buildinabox.BuildingPlan; import com.norcode.bukkit.buildinabox.ChestData; import com.norcode.bukkit.buildinabox.util.ConfigAccessor; import com.norcode.bukkit.buildinabox.util.SerializationUtil; import com.norcode.bukkit.schematica.ClipboardBlock; import net.minecraft.server.v1_5_R3.NBTTagCompound; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.BlockVector; import java.util.*; public class YamlDataStore extends DataStore { BuildInABox plugin; ConfigAccessor planCfg; ConfigAccessor chestCfg; int nextChestId = 0; HashMap<String, HashSet<Integer>> worldCache = new HashMap<String, HashSet<Integer>>(); HashMap<Integer, ChestData> chests = new HashMap<Integer, ChestData>(); HashMap<String, BuildingPlan> plans = new HashMap<String, BuildingPlan>(); boolean dirty = false; public YamlDataStore(BuildInABox plugin) { this.plugin = plugin; this.planCfg = new ConfigAccessor(plugin, "plans.yml"); this.chestCfg = new ConfigAccessor(plugin, "chests.yml"); } void loadPlans() { this.planCfg.reloadConfig(); this.plans.clear(); // Load Plans ConfigurationSection sec; for (String key: this.planCfg.getConfig().getKeys(false)) { sec = this.planCfg.getConfig().getConfigurationSection(key); if (sec != null) { BuildingPlan plan = new BuildingPlan(plugin, sec.getString("name"), sec.getString("filename"), sec.getString("display-name", sec.getString("name")), sec.getStringList("description")); this.plans.put(plan.getName().toLowerCase(), plan); plan.registerPermissions(); } } } void loadChests() { HashSet<Chunk> loadedChunks = new HashSet<Chunk>(); this.chestCfg.reloadConfig(); this.chests.clear(); // Load Chests ConfigurationSection sec; int maxId = 0; int id; World world; String worldName = null; Integer x = null, y = null, z = null; for (String key: this.chestCfg.getConfig().getKeys(false)) { plugin.debug("Loading chest: " + key); sec = this.chestCfg.getConfig().getConfigurationSection(key); world = null; id = sec.getInt("id", 0); plugin.debug(" ... id " + id); if (id > 0) { if (id > maxId) maxId = id; String locStr = sec.getString("location"); if (locStr != null && !locStr.equals("")) { String[] parts = locStr.split(";"); plugin.debug(" ... location: " + locStr); if (parts.length == 4) { worldName = parts[0]; world = plugin.getServer().createWorld(new WorldCreator(worldName)); x = Integer.parseInt(parts[1]); y = Integer.parseInt(parts[2]); z = Integer.parseInt(parts[3]); } } else { plugin.debug(" ... no location data."); - continue; } // Store the id in a map keyed on world name // for quicker lookups at world load time. + HashMap<BlockVector, NBTTagCompound> tileEntities = SerializationUtil.deserializeTileEntities(sec.getString("tile-entities")); + HashMap<BlockVector, ClipboardBlock> replacedBlocks = SerializationUtil.deserializeReplacedBlocks(sec.getString("replaced-blocks")); + ChestData cd = new ChestData(id, sec.getString("plan"), sec.getString("locked-by"), sec.getLong("last-activity"), worldName, x, y, z, tileEntities, replacedBlocks); + chests.put(id,cd); + BuildChest bc = new BuildChest(cd); if (world != null) { - HashMap<BlockVector, NBTTagCompound> tileEntities = SerializationUtil.deserializeTileEntities(sec.getString("tile-entities")); - HashMap<BlockVector, ClipboardBlock> replacedBlocks = SerializationUtil.deserializeReplacedBlocks(sec.getString("replaced-blocks")); - ChestData cd = new ChestData(id, sec.getString("plan"), sec.getString("locked-by"), sec.getLong("last-activity"), world.getName(), x, y, z, tileEntities, replacedBlocks); - chests.put(id,cd); - BuildChest bc = new BuildChest(cd); if (!bc.getLocation().getChunk().isLoaded()) { if (!bc.getLocation().getChunk().load()) { continue; } } if (bc.getBlock().getTypeId() != plugin.cfg.getChestBlockId()) { plugin.getDataStore().deleteChest(cd.getId()); continue; } bc.getBlock().setMetadata("buildInABox", new FixedMetadataValue(plugin, bc)); if (!plugin.cfg.isBuildingProtectionEnabled()) continue; Set<Chunk> protectedChunks = bc.protectBlocks(null); if (protectedChunks == null) continue; loadedChunks.addAll(protectedChunks); } else { plugin.debug("Chest w/ key: " + key + " has an invalid world."); } } else { plugin.debug("Chest w/ key: " + key + " has no id."); } } for (Chunk c: loadedChunks) { c.getWorld().unloadChunkRequest(c.getX(), c.getZ(), true); } nextChestId = maxId; } @Override public void load() { loadPlans(); loadChests(); } @Override public void save() { if (this.dirty) { this.dirty = false; this.chestCfg.saveConfig(); this.planCfg.saveConfig(); } } @Override public ChestData getChest(int id) { return this.chests.get(id); } @Override public ChestData createChest(String plan) { nextChestId++; ConfigurationSection sec = this.chestCfg.getConfig().createSection(Integer.toString(nextChestId)); long now = System.currentTimeMillis(); sec.set("plan", plan); sec.set("last-activity", now); sec.set("id", nextChestId); setDirty(); ChestData data = new ChestData(nextChestId, plan, null, now, null, null, null, null, // world, x, y, z null, null); // tileEntities, replacedBlocks chests.put(nextChestId, data); return data; } @Override public void saveChest(ChestData data) { ConfigurationSection sec = this.chestCfg.getConfig().getConfigurationSection(Integer.toString(data.getId())); sec.set("plan", data.getPlanName()); sec.set("last-activity", data.getLastActivity()); sec.set("location", data.getSerializedLocation()); sec.set("locked-by", data.getLockedBy()); sec.set("replaced-blocks", SerializationUtil.serializeReplacedBlocks(data.getReplacedBlocks())); sec.set("tile-entities", SerializationUtil.serializeTileEntities(data.getTileEntities())); this.setDirty(); } @Override public void deleteChest(int id) { plugin.debug("Deleting Chest ID#" + id); this.chests.remove(id); this.chestCfg.getConfig().set(Integer.toString(id), null); this.setDirty(); } @Override public void setWorldChests(World world, Collection<ChestData> chests) { HashSet<Integer> ids = new HashSet<Integer>(); for (ChestData cd: chests) { ids.add(cd.getId()); } worldCache.put(world.getName(), ids); } @Override public void clearWorldChests(World world) { worldCache.put(world.getName(), new HashSet<Integer>()); } @Override public Collection<ChestData> getWorldChests(World world) { if (worldCache.containsKey(world.getName())) { Set<Integer> ids = worldCache.get(world.getName()); List<ChestData> results = new ArrayList<ChestData>(ids.size()); for (int i: worldCache.get(world.getName())) { results.add(chests.get(i)); } return results; } return null; } @Override public void saveBuildingPlan(BuildingPlan plan) { ConfigurationSection sec = planCfg.getConfig().getConfigurationSection(plan.getName()); if (sec == null) { sec = planCfg.getConfig().createSection(plan.getName()); } sec.set("name", plan.getName()); sec.set("display-name", plan.getDisplayName()); sec.set("filename", plan.getFilename()); sec.set("description", plan.getDescription()); this.plans.put(plan.getName().toLowerCase(), plan); setDirty(); } @Override public Collection<ChestData> getAllChests() { return chests.values(); } @Override public Collection<BuildingPlan> getAllBuildingPlans() { return plans.values(); } @Override public BuildingPlan getBuildingPlan(String name) { return plans.get(name.toLowerCase()); } private void setDirty() { this.dirty = true; } @Override public void deleteBuildingPlan(BuildingPlan plan) { this.plans.remove(plan.getName().toLowerCase()); plan.getSchematicFile().delete(); this.planCfg.getConfig().set(plan.getName(), ""); } }
false
true
void loadChests() { HashSet<Chunk> loadedChunks = new HashSet<Chunk>(); this.chestCfg.reloadConfig(); this.chests.clear(); // Load Chests ConfigurationSection sec; int maxId = 0; int id; World world; String worldName = null; Integer x = null, y = null, z = null; for (String key: this.chestCfg.getConfig().getKeys(false)) { plugin.debug("Loading chest: " + key); sec = this.chestCfg.getConfig().getConfigurationSection(key); world = null; id = sec.getInt("id", 0); plugin.debug(" ... id " + id); if (id > 0) { if (id > maxId) maxId = id; String locStr = sec.getString("location"); if (locStr != null && !locStr.equals("")) { String[] parts = locStr.split(";"); plugin.debug(" ... location: " + locStr); if (parts.length == 4) { worldName = parts[0]; world = plugin.getServer().createWorld(new WorldCreator(worldName)); x = Integer.parseInt(parts[1]); y = Integer.parseInt(parts[2]); z = Integer.parseInt(parts[3]); } } else { plugin.debug(" ... no location data."); continue; } // Store the id in a map keyed on world name // for quicker lookups at world load time. if (world != null) { HashMap<BlockVector, NBTTagCompound> tileEntities = SerializationUtil.deserializeTileEntities(sec.getString("tile-entities")); HashMap<BlockVector, ClipboardBlock> replacedBlocks = SerializationUtil.deserializeReplacedBlocks(sec.getString("replaced-blocks")); ChestData cd = new ChestData(id, sec.getString("plan"), sec.getString("locked-by"), sec.getLong("last-activity"), world.getName(), x, y, z, tileEntities, replacedBlocks); chests.put(id,cd); BuildChest bc = new BuildChest(cd); if (!bc.getLocation().getChunk().isLoaded()) { if (!bc.getLocation().getChunk().load()) { continue; } } if (bc.getBlock().getTypeId() != plugin.cfg.getChestBlockId()) { plugin.getDataStore().deleteChest(cd.getId()); continue; } bc.getBlock().setMetadata("buildInABox", new FixedMetadataValue(plugin, bc)); if (!plugin.cfg.isBuildingProtectionEnabled()) continue; Set<Chunk> protectedChunks = bc.protectBlocks(null); if (protectedChunks == null) continue; loadedChunks.addAll(protectedChunks); } else { plugin.debug("Chest w/ key: " + key + " has an invalid world."); } } else { plugin.debug("Chest w/ key: " + key + " has no id."); } } for (Chunk c: loadedChunks) { c.getWorld().unloadChunkRequest(c.getX(), c.getZ(), true); } nextChestId = maxId; }
void loadChests() { HashSet<Chunk> loadedChunks = new HashSet<Chunk>(); this.chestCfg.reloadConfig(); this.chests.clear(); // Load Chests ConfigurationSection sec; int maxId = 0; int id; World world; String worldName = null; Integer x = null, y = null, z = null; for (String key: this.chestCfg.getConfig().getKeys(false)) { plugin.debug("Loading chest: " + key); sec = this.chestCfg.getConfig().getConfigurationSection(key); world = null; id = sec.getInt("id", 0); plugin.debug(" ... id " + id); if (id > 0) { if (id > maxId) maxId = id; String locStr = sec.getString("location"); if (locStr != null && !locStr.equals("")) { String[] parts = locStr.split(";"); plugin.debug(" ... location: " + locStr); if (parts.length == 4) { worldName = parts[0]; world = plugin.getServer().createWorld(new WorldCreator(worldName)); x = Integer.parseInt(parts[1]); y = Integer.parseInt(parts[2]); z = Integer.parseInt(parts[3]); } } else { plugin.debug(" ... no location data."); } // Store the id in a map keyed on world name // for quicker lookups at world load time. HashMap<BlockVector, NBTTagCompound> tileEntities = SerializationUtil.deserializeTileEntities(sec.getString("tile-entities")); HashMap<BlockVector, ClipboardBlock> replacedBlocks = SerializationUtil.deserializeReplacedBlocks(sec.getString("replaced-blocks")); ChestData cd = new ChestData(id, sec.getString("plan"), sec.getString("locked-by"), sec.getLong("last-activity"), worldName, x, y, z, tileEntities, replacedBlocks); chests.put(id,cd); BuildChest bc = new BuildChest(cd); if (world != null) { if (!bc.getLocation().getChunk().isLoaded()) { if (!bc.getLocation().getChunk().load()) { continue; } } if (bc.getBlock().getTypeId() != plugin.cfg.getChestBlockId()) { plugin.getDataStore().deleteChest(cd.getId()); continue; } bc.getBlock().setMetadata("buildInABox", new FixedMetadataValue(plugin, bc)); if (!plugin.cfg.isBuildingProtectionEnabled()) continue; Set<Chunk> protectedChunks = bc.protectBlocks(null); if (protectedChunks == null) continue; loadedChunks.addAll(protectedChunks); } else { plugin.debug("Chest w/ key: " + key + " has an invalid world."); } } else { plugin.debug("Chest w/ key: " + key + " has no id."); } } for (Chunk c: loadedChunks) { c.getWorld().unloadChunkRequest(c.getX(), c.getZ(), true); } nextChestId = maxId; }
diff --git a/src/net/holyc/ofcomm/OFCommService.java b/src/net/holyc/ofcomm/OFCommService.java index be691ab..9e13466 100644 --- a/src/net/holyc/ofcomm/OFCommService.java +++ b/src/net/holyc/ofcomm/OFCommService.java @@ -1,341 +1,342 @@ package net.holyc.ofcomm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.holyc.HolyCMessage; import net.holyc.R; import net.holyc.dispatcher.OFEvent; import net.holyc.dispatcher.OFReplyEvent; import org.openflow.protocol.OFHello; import com.google.gson.Gson; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; import android.widget.Toast; /** * The Thread Create and Maintain Connections to Openflowd * * @author Te-Yuan Huang ([email protected]) * */ public class OFCommService extends Service{ int bind_port = 6633; ServerSocketChannel ctlServer = null; Selector selector = null; String TAG = "HOLYC.OFCOMM"; private Map<Integer, Socket> socketMap = new HashMap<Integer, Socket>(); AcceptThread mAcceptThread = null; /** For showing and hiding our notification. */ NotificationManager mNM; /** Keeps track of all current registered clients. */ ArrayList<Messenger> mClients = new ArrayList<Messenger>(); Gson gson = new Gson(); /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case HolyCMessage.OFCOMM_REGISTER.type: mClients.add(msg.replyTo); break; case HolyCMessage.OFCOMM_UNREGISTER.type: mClients.remove(msg.replyTo); break; case HolyCMessage.OFCOMM_START_OPENFLOWD.type: bind_port = msg.arg1; sendReportToUI("Bind on port: " + bind_port); Log.d(TAG, "Send msg on bind: " + bind_port); startOpenflowController(); break; case HolyCMessage.OFREPLY_EVENT.type: String json = msg.getData().getString(HolyCMessage.OFREPLY_EVENT.str_key); Log.d(TAG, "serialized json = " + json); OFReplyEvent ofpoe = gson.fromJson(json, OFReplyEvent.class); int scn = ofpoe.getSocketChannelNumber(); Log.d(TAG, "Send OFReply through socket channel with Remote Port "+scn); if(!socketMap.containsKey(new Integer(scn))){ Log.e(TAG, "there is no SocketChannel left"); }else{ Socket socket = socketMap.get(new Integer(scn)); if(socket != null){ sendOFPacket(socket, ofpoe.getData()); } /** for debug */ //sendReportToUI("Send OFReply packet = " + ofpoe.getOFMessage().toString()); Log.d(TAG, "Send OFReply packet = "+ ofpoe.getOFMessage().toString()); } break; default: super.handleMessage(msg); } } } /** * Target we publish for clients to send messages to IncomingHandler. */ final Messenger mMessenger = new Messenger(new IncomingHandler()); @Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancel(R.string.openflow_channel_started); //close server socket before leaving the service try{ if(ctlServer != null && ctlServer.isOpen()){ ctlServer.socket().close(); ctlServer.close(); } }catch(IOException e){ } stopOpenflowController(); // Tell the user we stopped. Toast.makeText(this, R.string.openflow_channel_stopped, Toast.LENGTH_SHORT).show(); } public void sendReportToUI(String str){ for (int i=mClients.size()-1; i>=0; i--) { try { Message msg = Message.obtain(null, HolyCMessage.UIREPORT_UPDATE.type); Bundle data = new Bundle(); data.putString(HolyCMessage.UIREPORT_UPDATE.str_key, str+"\n -------------------------------"); msg.setData(data); mClients.get(i).send(msg); } catch (RemoteException e) { mClients.remove(i); } } } public void sendOFEventToDispatchService(Integer remotePort, byte[] ofdata){ Gson gson = new Gson(); for (int i=mClients.size()-1; i>=0; i--) { try { Message msg = Message.obtain(null, HolyCMessage.OFCOMM_EVENT.type); OFEvent ofe = new OFEvent(remotePort.intValue(), ofdata); //sendReportToUI("Recevie OFMessage: " + ofe.getOFMessage().toString()); Log.d(TAG, "Recevie OFMessage: " + ofe.getOFMessage().toString()); Log.d(TAG, "OFMessage length = " + ofe.getOFMessage().getLength() + " ofdata length = " + ofdata.length); Bundle data = new Bundle(); data.putString(HolyCMessage.OFCOMM_EVENT.str_key, gson.toJson(ofe, OFEvent.class)); msg.setData(data); mClients.get(i).send(msg); } catch (RemoteException e) { mClients.remove(i); } } } public void startOpenflowController(){ mAcceptThread = new AcceptThread(); mAcceptThread.start(); sendReportToUI("Start Controller Daemon"); } public void stopOpenflowController(){ if (mAcceptThread != null) { mAcceptThread.close(); mAcceptThread = null; } } /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ @Override public IBinder onBind(Intent intent) { return mMessenger.getBinder(); } private void sendOFPacket(Socket socket, byte[] data ){ try { OutputStream out = socket.getOutputStream(); out.write(data); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private class AcceptThread extends Thread { // The local server socket private final ServerSocket mmServerSocket; public AcceptThread() { ServerSocket tmp = null; try { tmp = new ServerSocket(bind_port); tmp.setReuseAddress(true); } catch (IOException e) { System.err.println("Could not open server socket"); e.printStackTrace(System.err); } mmServerSocket = tmp; } public void run() { setName("HolycAccpetThread"); while (true) { Socket socket = null; try { // This is a blocking call and will only return on a // successful connection or an exception Log.d(TAG, "waiting for openflow client ..."); socket = mmServerSocket.accept(); socket.setTcpNoDelay(true); Log.d(TAG, "Client connected!"); } catch (SocketException e) { } catch (IOException e) { Log.e(TAG, "accept() failed", e); break; } // If a connection was accepted if (socket == null) { break; } //immediately send an OFHello back OFHello ofh = new OFHello(); ByteBuffer bb = ByteBuffer.allocate(ofh.getLength()); ofh.writeTo(bb); sendOFPacket(socket, bb.array()); Integer remotePort = new Integer(socket.getPort()); socketMap.put(remotePort, socket); ConnectedThread conThread = new ConnectedThread(remotePort, socket); conThread.start(); } Log.d(TAG, "END mAcceptThread"); } public void close() { Log.d(TAG, "close " + this); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of server failed", e); } } } private class ConnectedThread extends Thread { private final Socket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; private final int BUFFER_LENGTH = 2048; private final Integer mRemotePort; public ConnectedThread(Integer remotePort, Socket socket) { mRemotePort = new Integer(remotePort); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { mmSocket.setTcpNoDelay(true); tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[BUFFER_LENGTH]; int bytes; if (mmInStream == null || mmOutStream == null) return; // Receive until client closes connection, indicated by -1 byte[] leftOverData = new byte[0]; //Log.d(TAG, "leftOverData size = " + leftOverData.length); try{ while (( bytes = mmInStream.read(buffer)) != -1) { byte[] ofdata = new byte[bytes+leftOverData.length]; //copy leftOverData to the beginning of OFdata if there is any if(leftOverData.length >0){ System.arraycopy(leftOverData, 0, ofdata, 0, leftOverData.length); System.arraycopy(buffer, 0, ofdata, leftOverData.length, bytes); leftOverData = new byte[0]; }else{ System.arraycopy(buffer, 0, ofdata, 0, bytes); } while(ofdata.length > 0){ //for each message, get the packet length, which is the 3rd and 4th bytes in the OF Header ByteBuffer bb = ByteBuffer.allocate(2); bb.put(ofdata[2]); bb.put(ofdata[3]); bb.flip(); short length = bb.getShort(); if(ofdata.length >= length){ byte[] ofmessage = new byte[length]; System.arraycopy(ofdata, 0, ofmessage, 0, length); //send data up to Dispatch Service sendOFEventToDispatchService(mRemotePort, ofmessage); int leftOverLen = (ofdata.length - length); byte[] temp = new byte[leftOverLen]; - System.arraycopy(ofdata, 0, temp, 0, leftOverLen); + System.arraycopy(ofdata, length, temp, 0, leftOverLen); ofdata = temp; }else{ leftOverData = new byte[ofdata.length]; System.arraycopy(ofdata, 0, leftOverData, 0, ofdata.length); ofdata = new byte[0]; Log.d(TAG, "there are left over, with size = " + leftOverData.length); } } + Log.d(TAG, "Finish retrieve data from buffer, read one more time"); } }catch (Exception e) { Log.e(TAG, "Error reading connection header", e); } close(); } public void close() { try { mmSocket.close(); } catch (IOException e) { } } } }
false
true
public void run() { byte[] buffer = new byte[BUFFER_LENGTH]; int bytes; if (mmInStream == null || mmOutStream == null) return; // Receive until client closes connection, indicated by -1 byte[] leftOverData = new byte[0]; //Log.d(TAG, "leftOverData size = " + leftOverData.length); try{ while (( bytes = mmInStream.read(buffer)) != -1) { byte[] ofdata = new byte[bytes+leftOverData.length]; //copy leftOverData to the beginning of OFdata if there is any if(leftOverData.length >0){ System.arraycopy(leftOverData, 0, ofdata, 0, leftOverData.length); System.arraycopy(buffer, 0, ofdata, leftOverData.length, bytes); leftOverData = new byte[0]; }else{ System.arraycopy(buffer, 0, ofdata, 0, bytes); } while(ofdata.length > 0){ //for each message, get the packet length, which is the 3rd and 4th bytes in the OF Header ByteBuffer bb = ByteBuffer.allocate(2); bb.put(ofdata[2]); bb.put(ofdata[3]); bb.flip(); short length = bb.getShort(); if(ofdata.length >= length){ byte[] ofmessage = new byte[length]; System.arraycopy(ofdata, 0, ofmessage, 0, length); //send data up to Dispatch Service sendOFEventToDispatchService(mRemotePort, ofmessage); int leftOverLen = (ofdata.length - length); byte[] temp = new byte[leftOverLen]; System.arraycopy(ofdata, 0, temp, 0, leftOverLen); ofdata = temp; }else{ leftOverData = new byte[ofdata.length]; System.arraycopy(ofdata, 0, leftOverData, 0, ofdata.length); ofdata = new byte[0]; Log.d(TAG, "there are left over, with size = " + leftOverData.length); } } } }catch (Exception e) { Log.e(TAG, "Error reading connection header", e); } close(); }
public void run() { byte[] buffer = new byte[BUFFER_LENGTH]; int bytes; if (mmInStream == null || mmOutStream == null) return; // Receive until client closes connection, indicated by -1 byte[] leftOverData = new byte[0]; //Log.d(TAG, "leftOverData size = " + leftOverData.length); try{ while (( bytes = mmInStream.read(buffer)) != -1) { byte[] ofdata = new byte[bytes+leftOverData.length]; //copy leftOverData to the beginning of OFdata if there is any if(leftOverData.length >0){ System.arraycopy(leftOverData, 0, ofdata, 0, leftOverData.length); System.arraycopy(buffer, 0, ofdata, leftOverData.length, bytes); leftOverData = new byte[0]; }else{ System.arraycopy(buffer, 0, ofdata, 0, bytes); } while(ofdata.length > 0){ //for each message, get the packet length, which is the 3rd and 4th bytes in the OF Header ByteBuffer bb = ByteBuffer.allocate(2); bb.put(ofdata[2]); bb.put(ofdata[3]); bb.flip(); short length = bb.getShort(); if(ofdata.length >= length){ byte[] ofmessage = new byte[length]; System.arraycopy(ofdata, 0, ofmessage, 0, length); //send data up to Dispatch Service sendOFEventToDispatchService(mRemotePort, ofmessage); int leftOverLen = (ofdata.length - length); byte[] temp = new byte[leftOverLen]; System.arraycopy(ofdata, length, temp, 0, leftOverLen); ofdata = temp; }else{ leftOverData = new byte[ofdata.length]; System.arraycopy(ofdata, 0, leftOverData, 0, ofdata.length); ofdata = new byte[0]; Log.d(TAG, "there are left over, with size = " + leftOverData.length); } } Log.d(TAG, "Finish retrieve data from buffer, read one more time"); } }catch (Exception e) { Log.e(TAG, "Error reading connection header", e); } close(); }
diff --git a/src/javamop/output/combinedaspect/event/advice/AdviceAndPointCut.java b/src/javamop/output/combinedaspect/event/advice/AdviceAndPointCut.java index a8c872b..b4d9f90 100644 --- a/src/javamop/output/combinedaspect/event/advice/AdviceAndPointCut.java +++ b/src/javamop/output/combinedaspect/event/advice/AdviceAndPointCut.java @@ -1,503 +1,503 @@ package javamop.output.combinedaspect.event.advice; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import javamop.MOPException; import javamop.Main; import javamop.output.MOPVariable; import javamop.output.combinedaspect.ActivatorManager; import javamop.output.combinedaspect.CombinedAspect; import javamop.output.combinedaspect.GlobalLock; import javamop.output.combinedaspect.MOPStatManager; import javamop.output.combinedaspect.MOPStatistics; import javamop.parser.ast.aspectj.PointCut; import javamop.parser.ast.mopspec.EventDefinition; import javamop.parser.ast.mopspec.JavaMOPSpec; import javamop.parser.ast.mopspec.MOPParameter; import javamop.parser.ast.mopspec.MOPParameters; public class AdviceAndPointCut { public MOPStatManager statManager; public ActivatorManager activatorsManager; MOPVariable inlineFuncName; MOPParameters inlineParameters; MOPVariable pointcutName; public PointCut pointcut; MOPParameters parameters; String specName; boolean hasThisJoinPoint; public boolean isAround = false; public boolean beCounted = false; public String retType; public String pos; public MOPParameters retVal; public MOPParameters throwVal; public MOPParameters threadVars = new MOPParameters(); GlobalLock globalLock; boolean isSync; LinkedList<EventDefinition> events = new LinkedList<EventDefinition>(); HashSet<JavaMOPSpec> specsForActivation = new HashSet<JavaMOPSpec>(); HashSet<JavaMOPSpec> specsForChecking = new HashSet<JavaMOPSpec>(); HashMap<EventDefinition, AdviceBody> advices = new HashMap<EventDefinition, AdviceBody>(); MOPVariable commonPointcut = new MOPVariable("MOP_CommonPointCut"); AroundAdviceLocalDecl aroundLocalDecl = null; AroundAdviceReturn aroundAdviceReturn = null; public AdviceAndPointCut(JavaMOPSpec mopSpec, EventDefinition event, CombinedAspect combinedAspect) throws MOPException { this.hasThisJoinPoint = mopSpec.hasThisJoinPoint(); this.specName = mopSpec.getName(); this.pointcutName = new MOPVariable(mopSpec.getName() + "_" + event.getUniqueId()); this.inlineFuncName = new MOPVariable("MOPInline" + mopSpec.getName() + "_" + event.getUniqueId()); this.parameters = event.getParametersWithoutThreadVar(); this.inlineParameters = event.getMOPParametersWithoutThreadVar(); if (event.getPos().equals("around")) { isAround = true; retType = event.getRetType().toString(); } this.pos = event.getPos(); this.retVal = event.getRetVal(); this.throwVal = event.getThrowVal(); if (event.getThreadVar() != null && event.getThreadVar().length() != 0) { if (event.getParameters().getParam(event.getThreadVar()) == null) throw new MOPException("thread variable is not included in the event definition."); this.threadVars.add(event.getParameters().getParam(event.getThreadVar())); } this.statManager = combinedAspect.statManager; this.activatorsManager = combinedAspect.activatorsManager; this.globalLock = combinedAspect.lockManager.getLock(); this.isSync = mopSpec.isSync(); this.advices.put(event, new GeneralAdviceBody(mopSpec, event, combinedAspect)); this.events.add(event); if (event.getCountCond() != null && event.getCountCond().length() != 0) { this.beCounted = true; } this.pointcut = event.getPointCut(); if (mopSpec.has__SKIP() || event.getPos().equals("around")) aroundLocalDecl = new AroundAdviceLocalDecl(); if (event.getPos().equals("around")) aroundAdviceReturn = new AroundAdviceReturn(event.getRetType(), event.getParametersWithoutThreadVar()); if(event.isStartEvent()) specsForActivation.add(mopSpec); else specsForChecking.add(mopSpec); } public PointCut getPointCut() { return pointcut; } public String getPointCutName() { return pointcutName.getVarName(); } public boolean addEvent(JavaMOPSpec mopSpec, EventDefinition event, CombinedAspect combinedAspect) throws MOPException { // Parameter Conflict Check for(MOPParameter param : event.getParametersWithoutThreadVar()){ MOPParameter param2 = parameters.getParam(param.getName()); if(param2 == null) continue; if(!param.getType().equals(param2.getType())){ return false; } } parameters.addAll(event.getParametersWithoutThreadVar()); if (event.getThreadVar() != null && event.getThreadVar().length() != 0) { if (event.getParameters().getParam(event.getThreadVar()) == null) throw new MOPException("thread variable is not included in the event definition."); this.threadVars.add(event.getParameters().getParam(event.getThreadVar())); } // add an advice body. this.advices.put(event, new GeneralAdviceBody(mopSpec, event, combinedAspect)); this.events.add(event); if (event.getCountCond() != null && event.getCountCond().length() != 0) { this.beCounted = true; } if(event.isStartEvent()) specsForActivation.add(mopSpec); else specsForChecking.add(mopSpec); return true; } protected String adviceBody(){ String ret = ""; if(Main.empty_advicebody){ ret += "System.out.print(\"\");\n"; Iterator<EventDefinition> iter; if(this.pos.equals("before")) iter = this.events.descendingIterator(); else iter = this.events.iterator(); if (this.beCounted) { ret += "++" + this.pointcutName + "_count;\n"; } while(iter.hasNext()){ EventDefinition event = iter.next(); AdviceBody advice = advices.get(event); if(advices.size() > 1){ ret += "//" + advice.mopSpec.getName() + "_" + event.getUniqueId() + "\n"; } } } else { for (MOPParameter threadVar : threadVars) { ret += "Thread " + threadVar.getName() + " = Thread.currentThread();\n"; } for(JavaMOPSpec spec : specsForActivation){ ret += activatorsManager.getActivator(spec) + " = true;\n"; } if (isSync) { ret += "while (!" + globalLock.getName() + ".tryLock()) {\n"; ret += "Thread.yield();\n"; ret += "}\n"; } Iterator<EventDefinition> iter; if(this.pos.equals("before")) iter = this.events.descendingIterator(); else iter = this.events.iterator(); if (this.beCounted) { ret += "++" + this.pointcutName + "_count;\n"; } while(iter.hasNext()){ EventDefinition event = iter.next(); AdviceBody advice = advices.get(event); ret += this.statManager.incEvent(advice.mopSpec, event); if(specsForChecking.contains(advice.mopSpec)){ if(advices.size() > 1){ ret += "//" + advice.mopSpec.getName() + "_" + event.getUniqueId() + "\n"; } ret += "if (" + activatorsManager.getActivator(advice.mopSpec) + ") {\n"; } else { if(advices.size() > 1){ ret += "//" + advice.mopSpec.getName() + "_" + event.getUniqueId() + "\n"; ret += "{\n"; } } if (Main.statistics) { MOPStatistics stat = this.statManager.getStat(advice.mopSpec); ret += stat.eventInc(event.getId()); for (MOPParameter param : event.getMOPParametersOnSpec()) { ret += stat.paramInc(param); } ret += "\n"; } // add check count condition here String countCond = event.getCountCond(); if (countCond != null && countCond.length() != 0) { countCond = countCond.replaceAll("count", this.pointcutName + "_count"); ret += "if (" + countCond + ") {\n"; } ret += advice; if (countCond != null && countCond.length() != 0) { ret += "}\n"; } if(specsForChecking.contains(advice.mopSpec)){ ret += "}\n"; } else { if(advices.size() > 1){ ret += "}\n"; } } } if (isSync) { ret += globalLock.getName() + ".unlock();\n"; } } return ret; } public String toString() { String ret = ""; String pointcutStr = pointcut.toString(); if(Main.inline && !isAround){ ret += "void " + inlineFuncName + "(" + inlineParameters.parameterDeclString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "JoinPoint thisJoinPoint"; } ret += ") {\n"; ret += adviceBody(); ret += "}\n"; } ret += "pointcut " + pointcutName; ret += "("; ret += parameters.parameterDeclString(); ret += ")"; ret += " : "; if (pointcutStr != null && pointcutStr.length() != 0) { ret += "("; ret += pointcutStr; ret += ")"; ret += " && "; } ret += commonPointcut + "();\n"; if (isAround) ret += retType + " "; ret += pos + " (" + parameters.parameterDeclString() + ") "; if (retVal != null && retVal.size() > 0) { ret += "returning ("; ret += retVal.parameterDeclString(); ret += ") "; } if (throwVal != null && throwVal.size() > 0) { ret += "throwing ("; ret += throwVal.parameterDeclString(); ret += ") "; } ret += ": " + pointcutName + "(" + parameters.parameterString() + ") {\n"; if (aroundLocalDecl != null) ret += aroundLocalDecl; if(Main.inline && !isAround){ ret += inlineFuncName + "(" + inlineParameters.parameterString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "thisJoinPoint"; } ret += ");\n"; } else { ret += adviceBody(); } if (aroundAdviceReturn != null) ret += aroundAdviceReturn; ret += "}\n"; return ret; } public String toRVString() { String ret = ""; String pointcutStr = pointcut.toString(); // Do we need to handle inline? if(Main.inline && !isAround){ ret += "void " + inlineFuncName + "(" + inlineParameters.parameterDeclString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "JoinPoint thisJoinPoint"; } ret += ") {\n"; ret += adviceBody(); ret += "}\n"; } ret += "pointcut " + pointcutName; ret += "("; ret += parameters.parameterDeclString(); ret += ")"; ret += " : "; if (pointcutStr != null && pointcutStr.length() != 0) { ret += "("; ret += pointcutStr; ret += ")"; ret += " && "; } ret += commonPointcut + "();\n"; if (isAround) ret += retType + " "; ret += pos + " (" + parameters.parameterDeclString() + ") "; if (retVal != null && retVal.size() > 0) { ret += "returning ("; ret += retVal.parameterDeclString(); ret += ") "; } if (throwVal != null && throwVal.size() > 0) { ret += "throwing ("; ret += throwVal.parameterDeclString(); ret += ") "; } ret += ": " + pointcutName + "(" + parameters.parameterString() + ") {\n"; if (aroundLocalDecl != null) ret += aroundLocalDecl; if(Main.inline && !isAround){ ret += inlineFuncName + "(" + inlineParameters.parameterString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "thisJoinPoint"; } ret += ");\n"; } else { // Call method here MOPNameRuntimeMonitor.nameEvent() // If there's thread var, replace with t (currentThread), // and also generate Thread t = currentThread before it // If there's return/ throw pointcut, cat in the end for (MOPParameter threadVar : threadVars) { ret += "Thread " + threadVar.getName() + " = Thread.currentThread();\n"; } Iterator<EventDefinition> iter; if(this.pos.equals("before")) iter = this.events.descendingIterator(); else iter = this.events.iterator(); while (iter.hasNext()) { EventDefinition event = iter.next(); AdviceBody advice = advices.get(event); if (advices.size() > 1) { ret += "//" + advice.mopSpec.getName() + "_" + event.getUniqueId() + "\n"; } String countCond = event.getCountCond(); if (countCond != null && countCond.length() != 0) { ret += "++" + this.pointcutName+ "_count;\n"; countCond = countCond.replaceAll("count", this.pointcutName + "_count"); ret += "if (" + countCond + ") {\n"; } if (Main.merge && Main.aspectname != null && Main.aspectname.length() > 0) { ret += Main.aspectname + "RuntimeMonitor." + advice.mopSpec.getName() + "_" + event.getId() + "Event("; } else { ret += specName + "RuntimeMonitor." + event.getId() + "Event("; } // Parameters // Original (including threadVar) String original = event.getParameters().parameterString(); ret += original; // Parameters in returning pointcut if (event.getRetVal() != null && event.getRetVal().size() > 0) { String retParameters = event.getRetVal().parameterString(); if (retParameters.length() > 0) { if (original == null || original.length() == 0) { ret += retParameters; } else { ret += ", " + retParameters; } } } // Parameters in throwing pointcut if (event.getThrowVal() != null && event.getThrowVal().size() > 0) { String throwParameters = event.getThrowVal().parameterString(); if (throwParameters.length() > 0) { if (original == null || original.length() == 0) { ret += throwParameters; } else { ret += ", " + throwParameters; } } } // __STATICSIG should be passed as an argument because rv-monitor cannot infer if (event.has__STATICSIG()) { - String staticsig = "thisJoinPoint"; + String staticsig = "thisJoinPoint.getStaticPart().getSignature()"; if (original == null || original.length() == 0) { ret += staticsig; } else { ret += ", " + staticsig; } } ret += ");\n"; if (countCond != null && countCond.length() != 0) { ret += "}\n"; } } } if (aroundAdviceReturn != null) ret += aroundAdviceReturn; ret += "}\n"; return ret; } }
true
true
public String toRVString() { String ret = ""; String pointcutStr = pointcut.toString(); // Do we need to handle inline? if(Main.inline && !isAround){ ret += "void " + inlineFuncName + "(" + inlineParameters.parameterDeclString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "JoinPoint thisJoinPoint"; } ret += ") {\n"; ret += adviceBody(); ret += "}\n"; } ret += "pointcut " + pointcutName; ret += "("; ret += parameters.parameterDeclString(); ret += ")"; ret += " : "; if (pointcutStr != null && pointcutStr.length() != 0) { ret += "("; ret += pointcutStr; ret += ")"; ret += " && "; } ret += commonPointcut + "();\n"; if (isAround) ret += retType + " "; ret += pos + " (" + parameters.parameterDeclString() + ") "; if (retVal != null && retVal.size() > 0) { ret += "returning ("; ret += retVal.parameterDeclString(); ret += ") "; } if (throwVal != null && throwVal.size() > 0) { ret += "throwing ("; ret += throwVal.parameterDeclString(); ret += ") "; } ret += ": " + pointcutName + "(" + parameters.parameterString() + ") {\n"; if (aroundLocalDecl != null) ret += aroundLocalDecl; if(Main.inline && !isAround){ ret += inlineFuncName + "(" + inlineParameters.parameterString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "thisJoinPoint"; } ret += ");\n"; } else { // Call method here MOPNameRuntimeMonitor.nameEvent() // If there's thread var, replace with t (currentThread), // and also generate Thread t = currentThread before it // If there's return/ throw pointcut, cat in the end for (MOPParameter threadVar : threadVars) { ret += "Thread " + threadVar.getName() + " = Thread.currentThread();\n"; } Iterator<EventDefinition> iter; if(this.pos.equals("before")) iter = this.events.descendingIterator(); else iter = this.events.iterator(); while (iter.hasNext()) { EventDefinition event = iter.next(); AdviceBody advice = advices.get(event); if (advices.size() > 1) { ret += "//" + advice.mopSpec.getName() + "_" + event.getUniqueId() + "\n"; } String countCond = event.getCountCond(); if (countCond != null && countCond.length() != 0) { ret += "++" + this.pointcutName+ "_count;\n"; countCond = countCond.replaceAll("count", this.pointcutName + "_count"); ret += "if (" + countCond + ") {\n"; } if (Main.merge && Main.aspectname != null && Main.aspectname.length() > 0) { ret += Main.aspectname + "RuntimeMonitor." + advice.mopSpec.getName() + "_" + event.getId() + "Event("; } else { ret += specName + "RuntimeMonitor." + event.getId() + "Event("; } // Parameters // Original (including threadVar) String original = event.getParameters().parameterString(); ret += original; // Parameters in returning pointcut if (event.getRetVal() != null && event.getRetVal().size() > 0) { String retParameters = event.getRetVal().parameterString(); if (retParameters.length() > 0) { if (original == null || original.length() == 0) { ret += retParameters; } else { ret += ", " + retParameters; } } } // Parameters in throwing pointcut if (event.getThrowVal() != null && event.getThrowVal().size() > 0) { String throwParameters = event.getThrowVal().parameterString(); if (throwParameters.length() > 0) { if (original == null || original.length() == 0) { ret += throwParameters; } else { ret += ", " + throwParameters; } } } // __STATICSIG should be passed as an argument because rv-monitor cannot infer if (event.has__STATICSIG()) { String staticsig = "thisJoinPoint"; if (original == null || original.length() == 0) { ret += staticsig; } else { ret += ", " + staticsig; } } ret += ");\n"; if (countCond != null && countCond.length() != 0) { ret += "}\n"; } } } if (aroundAdviceReturn != null) ret += aroundAdviceReturn; ret += "}\n"; return ret; }
public String toRVString() { String ret = ""; String pointcutStr = pointcut.toString(); // Do we need to handle inline? if(Main.inline && !isAround){ ret += "void " + inlineFuncName + "(" + inlineParameters.parameterDeclString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "JoinPoint thisJoinPoint"; } ret += ") {\n"; ret += adviceBody(); ret += "}\n"; } ret += "pointcut " + pointcutName; ret += "("; ret += parameters.parameterDeclString(); ret += ")"; ret += " : "; if (pointcutStr != null && pointcutStr.length() != 0) { ret += "("; ret += pointcutStr; ret += ")"; ret += " && "; } ret += commonPointcut + "();\n"; if (isAround) ret += retType + " "; ret += pos + " (" + parameters.parameterDeclString() + ") "; if (retVal != null && retVal.size() > 0) { ret += "returning ("; ret += retVal.parameterDeclString(); ret += ") "; } if (throwVal != null && throwVal.size() > 0) { ret += "throwing ("; ret += throwVal.parameterDeclString(); ret += ") "; } ret += ": " + pointcutName + "(" + parameters.parameterString() + ") {\n"; if (aroundLocalDecl != null) ret += aroundLocalDecl; if(Main.inline && !isAround){ ret += inlineFuncName + "(" + inlineParameters.parameterString(); if(hasThisJoinPoint){ if(inlineParameters.size() > 0) ret += ", "; ret += "thisJoinPoint"; } ret += ");\n"; } else { // Call method here MOPNameRuntimeMonitor.nameEvent() // If there's thread var, replace with t (currentThread), // and also generate Thread t = currentThread before it // If there's return/ throw pointcut, cat in the end for (MOPParameter threadVar : threadVars) { ret += "Thread " + threadVar.getName() + " = Thread.currentThread();\n"; } Iterator<EventDefinition> iter; if(this.pos.equals("before")) iter = this.events.descendingIterator(); else iter = this.events.iterator(); while (iter.hasNext()) { EventDefinition event = iter.next(); AdviceBody advice = advices.get(event); if (advices.size() > 1) { ret += "//" + advice.mopSpec.getName() + "_" + event.getUniqueId() + "\n"; } String countCond = event.getCountCond(); if (countCond != null && countCond.length() != 0) { ret += "++" + this.pointcutName+ "_count;\n"; countCond = countCond.replaceAll("count", this.pointcutName + "_count"); ret += "if (" + countCond + ") {\n"; } if (Main.merge && Main.aspectname != null && Main.aspectname.length() > 0) { ret += Main.aspectname + "RuntimeMonitor." + advice.mopSpec.getName() + "_" + event.getId() + "Event("; } else { ret += specName + "RuntimeMonitor." + event.getId() + "Event("; } // Parameters // Original (including threadVar) String original = event.getParameters().parameterString(); ret += original; // Parameters in returning pointcut if (event.getRetVal() != null && event.getRetVal().size() > 0) { String retParameters = event.getRetVal().parameterString(); if (retParameters.length() > 0) { if (original == null || original.length() == 0) { ret += retParameters; } else { ret += ", " + retParameters; } } } // Parameters in throwing pointcut if (event.getThrowVal() != null && event.getThrowVal().size() > 0) { String throwParameters = event.getThrowVal().parameterString(); if (throwParameters.length() > 0) { if (original == null || original.length() == 0) { ret += throwParameters; } else { ret += ", " + throwParameters; } } } // __STATICSIG should be passed as an argument because rv-monitor cannot infer if (event.has__STATICSIG()) { String staticsig = "thisJoinPoint.getStaticPart().getSignature()"; if (original == null || original.length() == 0) { ret += staticsig; } else { ret += ", " + staticsig; } } ret += ");\n"; if (countCond != null && countCond.length() != 0) { ret += "}\n"; } } } if (aroundAdviceReturn != null) ret += aroundAdviceReturn; ret += "}\n"; return ret; }
diff --git a/src/com/android/deskclock/StopwatchFragment.java b/src/com/android/deskclock/StopwatchFragment.java index 42b9859c..1f495dd4 100644 --- a/src/com/android/deskclock/StopwatchFragment.java +++ b/src/com/android/deskclock/StopwatchFragment.java @@ -1,470 +1,471 @@ package com.android.deskclock; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.android.deskclock.timer.TimerView; import java.util.ArrayList; /** * TODO: Insert description here. (generated by isaackatz) */ public class StopwatchFragment extends DeskClockFragment { // Stopwatch states private static final int STOPWATCH_RESET = 0; private static final int STOPWATCH_RUNNING = 1; private static final int STOPWATCH_STOPPED = 2; private static final int MAX_LAPS = 99; int mState = STOPWATCH_RESET; // Stopwatch views that are accessed by the activity Button mLeftButton, mRightButton; CircleTimerView mTime; TimerView mTimeText; View mLapsTitle; ListView mLapsList; Button mShareButton; View mButtonSeperator; // Used for calculating the time from the start taking into account the pause times long mStartTime = 0; long mAccumulatedTime = 0; // Lap information class Lap { Lap () { mLapTime = 0; mTotalTime = 0; } Lap (long time, long total) { mLapTime = time; mTotalTime = total; } public long mLapTime; public long mTotalTime; } // Adapter for the ListView that shows the lap times. class LapsListAdapter extends BaseAdapter { Context mContext; ArrayList<Lap> mLaps = new ArrayList<Lap>(); private final LayoutInflater mInflater; public LapsListAdapter(Context context) { mContext = context; mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (mLaps.size() == 0 || position >= mLaps.size()) { return null; } View lapInfo; if (convertView != null) { lapInfo = convertView; } else { lapInfo = mInflater.inflate(R.layout.lap_view, parent, false); } TextView count = (TextView)lapInfo.findViewById(R.id.lap_number); TextView lapTime = (TextView)lapInfo.findViewById(R.id.lap_time); TextView toalTime = (TextView)lapInfo.findViewById(R.id.lap_total); lapTime.setText(getTimeText(mLaps.get(position).mLapTime)); toalTime.setText(getTimeText(mLaps.get(position).mTotalTime)); count.setText(getString(R.string.sw_current_lap_number, mLaps.size() - position)); return lapInfo; } @Override public int getCount() { return mLaps.size(); } @Override public Object getItem(int position) { if (mLaps.size() == 0 || position >= mLaps.size()) { return null; } return mLaps.get(position); } public void addLap(Lap l) { mLaps.add(0, l); notifyDataSetChanged(); } public void clearLaps() { mLaps.clear(); notifyDataSetChanged(); } // Helper function used to get the lap data to be stored in the activitys's bundle public long [] getLapTimes() { int size = mLaps.size(); if (size == 0) { return null; } long [] laps = new long[size]; for (int i = 0; i < size; i ++) { laps[i] = mLaps.get(i).mLapTime; } return laps; } // Helper function to restore adapter's data from the activity's bundle public void setLapTimes(long [] laps) { if (laps == null || laps.length == 0) { return; } int size = laps.length; mLaps.clear(); for (int i = 0; i < size; i ++) { mLaps.add(new Lap (laps[i], 0)); } long totalTime = 0; for (int i = size -1; i >= 0; i --) { totalTime += laps[i]; mLaps.get(i).mTotalTime = totalTime; } notifyDataSetChanged(); } } // Keys for data stored in the activity's bundle private static final String START_TIME_KEY = "start_time"; private static final String ACCUM_TIME_KEY = "accum_time"; private static final String STATE_KEY = "state"; private static final String LAPS_KEY = "laps"; LapsListAdapter mLapsAdapter; public StopwatchFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.stopwatch_fragment, container, false); mLeftButton = (Button)v.findViewById(R.id.stopwatch_left_button); mLeftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonClicked(true); switch (mState) { case STOPWATCH_RUNNING: // Save lap time addLapTime(System.currentTimeMillis()/10); showLaps(); setButtons(STOPWATCH_RUNNING); break; case STOPWATCH_STOPPED: // do reset mAccumulatedTime = 0; mLapsAdapter.clearLaps(); showLaps(); mTime.stopIntervalAnimation(); mTime.reset(); mTimeText.setTime(mAccumulatedTime); mTimeText.blinkTimeStr(false); setButtons(STOPWATCH_RESET); mState = STOPWATCH_RESET; break; default: Log.wtf("Illegal state " + mState + " while pressing the left stopwatch button"); break; } } }); mRightButton = (Button)v.findViewById(R.id.stopwatch_right_button); mRightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonClicked(true); switch (mState) { case STOPWATCH_RUNNING: // do stop stopUpdateThread(); mTime.pauseIntervalAnimation(); long curTime = System.currentTimeMillis()/10; mAccumulatedTime += (curTime - mStartTime); mTimeText.setTime(mAccumulatedTime); mTimeText.blinkTimeStr(true); updateCurrentLap(curTime, mAccumulatedTime); setButtons(STOPWATCH_STOPPED); mState = STOPWATCH_STOPPED; break; case STOPWATCH_RESET: case STOPWATCH_STOPPED: // do start mStartTime = System.currentTimeMillis()/10; startUpdateThread(); mTimeText.blinkTimeStr(false); if (mTime.isAnimating()) { mTime.startIntervalAnimation(); } setButtons(STOPWATCH_RUNNING); mState = STOPWATCH_RUNNING; break; default: Log.wtf("Illegal state " + mState + " while pressing the right stopwatch button"); break; } } }); mShareButton = (Button)v.findViewById(R.id.stopwatch_share_button); mButtonSeperator = v.findViewById(R.id.stopwatch_button_seperator); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); // Add data to the intent, the receiving app will decide what to // do with it. - intent.putExtra(Intent.EXTRA_SUBJECT, mContext.getResources().getString(R.string.sw_share_title)); + intent.putExtra(Intent.EXTRA_SUBJECT, + getActivity().getResources().getString(R.string.sw_share_title)); intent.putExtra(Intent.EXTRA_TEXT, buildShareResults()); startActivity(Intent.createChooser(intent, null)); } }); mTime = (CircleTimerView)v.findViewById(R.id.stopwatch_time); mTimeText = (TimerView)v.findViewById(R.id.stopwatch_time_text); mLapsTitle = v.findViewById(R.id.laps_title); mLapsList = (ListView)v.findViewById(R.id.laps_list); mLapsList.setDividerHeight(0); mLapsAdapter = new LapsListAdapter(getActivity()); if (mLapsList != null) { mLapsList.setAdapter(mLapsAdapter); } if (savedInstanceState != null) { mState = savedInstanceState.getInt(STATE_KEY, STOPWATCH_RESET); mStartTime = savedInstanceState.getLong(START_TIME_KEY, 0); mAccumulatedTime = savedInstanceState.getLong(ACCUM_TIME_KEY, 0); mLapsAdapter.setLapTimes(savedInstanceState.getLongArray(LAPS_KEY)); } return v; } @Override public void onResume() { setButtons(mState); mTimeText.setTime(mAccumulatedTime); if (mState == STOPWATCH_RUNNING) { startUpdateThread(); } showLaps(); super.onResume(); } @Override public void onPause() { if (mState == STOPWATCH_RUNNING) { stopUpdateThread(); } super.onPause(); } @Override public void onSaveInstanceState (Bundle outState) { outState.putInt(STATE_KEY, mState); outState.putLong(START_TIME_KEY, mStartTime); outState.putLong(ACCUM_TIME_KEY, mAccumulatedTime); if (mLapsAdapter != null) { long [] laps = mLapsAdapter.getLapTimes(); if (laps != null) { outState.putLongArray(LAPS_KEY, laps); } } super.onSaveInstanceState(outState); } private void showShareButton(boolean show) { if (mShareButton != null) { mShareButton.setVisibility(show ? View.VISIBLE : View.GONE); mButtonSeperator.setVisibility(show ? View.VISIBLE : View.GONE); mShareButton.setEnabled(show); } } /*** * Update the buttons on the stopwatch according to the watch's state */ private void setButtons(int state) { switch (state) { case STOPWATCH_RESET: setButton(mLeftButton, R.string.sw_lap_button, false, View.INVISIBLE); setButton(mRightButton, R.string.sw_start_button, true, View.VISIBLE); showShareButton(false); break; case STOPWATCH_RUNNING: setButton(mLeftButton, R.string.sw_lap_button, !reachedMaxLaps(), View.VISIBLE); setButton(mRightButton, R.string.sw_stop_button, true, View.VISIBLE); showShareButton(false); break; case STOPWATCH_STOPPED: setButton(mLeftButton, R.string.sw_reset_button, true, View.VISIBLE); setButton(mRightButton, R.string.sw_start_button, true, View.VISIBLE); showShareButton(true); break; default: break; } } private boolean reachedMaxLaps() { return mLapsAdapter.getCount() >= MAX_LAPS; } /*** * Set a single button with the string and states provided. * @param b - Button view to update * @param text - Text in button * @param enabled - enable/disables the button * @param visibility - Show/hide the button */ private void setButton (Button b, int text, boolean enabled, int visibility) { b.setText(text); b.setVisibility(visibility); b.setEnabled(enabled); } /*** * Sets the string of the time running on the stopwatch up to hundred of a second accuracy * @param time - in hundreds of a second since the stopwatch started */ private String getTimeText(long time) { if (time < 0) { time = 0; } long hundreds, seconds, minutes, hours; seconds = time / 100; hundreds = (time - seconds * 100); minutes = seconds / 60; seconds = seconds - minutes * 60; hours = minutes / 60; minutes = minutes - hours * 60; if (hours > 99) { hours = 0; } // TODO: must build to account for localization String timeStr; if (hours >= 10) { timeStr = String.format("%02dh %02dm %02ds .%02d", hours, minutes, seconds, hundreds); } else if (hours > 0) { timeStr = String.format("%01dh %02dm %02ds .%02d", hours, minutes, seconds, hundreds); } else if (minutes >= 10) { timeStr = String.format("%02dm %02ds .%02d", minutes, seconds, hundreds); } else { timeStr = String.format("%02dm %02ds .%02d", minutes, seconds, hundreds); } return timeStr; } /*** * * @param time - in hundredths of a second */ private void addLapTime(long time) { int size = mLapsAdapter.getCount(); long curTime = time - mStartTime + mAccumulatedTime; if (size == 0) { // Always show the ending lap and a new one mLapsAdapter.addLap(new Lap(curTime, curTime)); mLapsAdapter.addLap(new Lap(0, curTime)); mTime.setIntervalTime(curTime * 10); } else { long lapTime = curTime - ((Lap) mLapsAdapter.getItem(1)).mTotalTime; ((Lap)mLapsAdapter.getItem(0)).mLapTime = lapTime; ((Lap)mLapsAdapter.getItem(0)).mTotalTime = curTime; mLapsAdapter.addLap(new Lap(0, 0)); mTime.setMarkerTime(lapTime * 10); // mTime.setIntervalTime(lapTime * 10); } mLapsAdapter.notifyDataSetChanged(); // Start lap animation starting from the second lap mTime.stopIntervalAnimation(); if (!reachedMaxLaps()) { mTime.startIntervalAnimation(); } } private void updateCurrentLap(long curTime, long totalTime) { if (mLapsAdapter.getCount() > 0) { Lap curLap = (Lap)mLapsAdapter.getItem(0); curLap.mLapTime = totalTime - ((Lap)mLapsAdapter.getItem(1)).mTotalTime; curLap.mTotalTime = totalTime; mLapsAdapter.notifyDataSetChanged(); } } private void showLaps() { if (mLapsAdapter.getCount() > 0) { mLapsList.setVisibility(View.VISIBLE); mLapsTitle.setVisibility(View.VISIBLE); } else { mLapsList.setVisibility(View.INVISIBLE); mLapsTitle.setVisibility(View.INVISIBLE); } } private void startUpdateThread() { mTime.post(mTimeUpdateThread); } private void stopUpdateThread() { mTime.removeCallbacks(mTimeUpdateThread); } Runnable mTimeUpdateThread = new Runnable() { @Override public void run() { long curTime = System.currentTimeMillis()/10; long totalTime = mAccumulatedTime + (curTime - mStartTime); if (mTime != null) { mTimeText.setTime(totalTime); } if (mLapsAdapter.getCount() > 0) { updateCurrentLap(curTime, totalTime); } mTime.postDelayed(mTimeUpdateThread, 10); } }; private String buildShareResults() { return getString(R.string.sw_share_main, mTimeText.getTimeString()); } }
true
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.stopwatch_fragment, container, false); mLeftButton = (Button)v.findViewById(R.id.stopwatch_left_button); mLeftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonClicked(true); switch (mState) { case STOPWATCH_RUNNING: // Save lap time addLapTime(System.currentTimeMillis()/10); showLaps(); setButtons(STOPWATCH_RUNNING); break; case STOPWATCH_STOPPED: // do reset mAccumulatedTime = 0; mLapsAdapter.clearLaps(); showLaps(); mTime.stopIntervalAnimation(); mTime.reset(); mTimeText.setTime(mAccumulatedTime); mTimeText.blinkTimeStr(false); setButtons(STOPWATCH_RESET); mState = STOPWATCH_RESET; break; default: Log.wtf("Illegal state " + mState + " while pressing the left stopwatch button"); break; } } }); mRightButton = (Button)v.findViewById(R.id.stopwatch_right_button); mRightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonClicked(true); switch (mState) { case STOPWATCH_RUNNING: // do stop stopUpdateThread(); mTime.pauseIntervalAnimation(); long curTime = System.currentTimeMillis()/10; mAccumulatedTime += (curTime - mStartTime); mTimeText.setTime(mAccumulatedTime); mTimeText.blinkTimeStr(true); updateCurrentLap(curTime, mAccumulatedTime); setButtons(STOPWATCH_STOPPED); mState = STOPWATCH_STOPPED; break; case STOPWATCH_RESET: case STOPWATCH_STOPPED: // do start mStartTime = System.currentTimeMillis()/10; startUpdateThread(); mTimeText.blinkTimeStr(false); if (mTime.isAnimating()) { mTime.startIntervalAnimation(); } setButtons(STOPWATCH_RUNNING); mState = STOPWATCH_RUNNING; break; default: Log.wtf("Illegal state " + mState + " while pressing the right stopwatch button"); break; } } }); mShareButton = (Button)v.findViewById(R.id.stopwatch_share_button); mButtonSeperator = v.findViewById(R.id.stopwatch_button_seperator); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); // Add data to the intent, the receiving app will decide what to // do with it. intent.putExtra(Intent.EXTRA_SUBJECT, mContext.getResources().getString(R.string.sw_share_title)); intent.putExtra(Intent.EXTRA_TEXT, buildShareResults()); startActivity(Intent.createChooser(intent, null)); } }); mTime = (CircleTimerView)v.findViewById(R.id.stopwatch_time); mTimeText = (TimerView)v.findViewById(R.id.stopwatch_time_text); mLapsTitle = v.findViewById(R.id.laps_title); mLapsList = (ListView)v.findViewById(R.id.laps_list); mLapsList.setDividerHeight(0); mLapsAdapter = new LapsListAdapter(getActivity()); if (mLapsList != null) { mLapsList.setAdapter(mLapsAdapter); } if (savedInstanceState != null) { mState = savedInstanceState.getInt(STATE_KEY, STOPWATCH_RESET); mStartTime = savedInstanceState.getLong(START_TIME_KEY, 0); mAccumulatedTime = savedInstanceState.getLong(ACCUM_TIME_KEY, 0); mLapsAdapter.setLapTimes(savedInstanceState.getLongArray(LAPS_KEY)); } return v; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.stopwatch_fragment, container, false); mLeftButton = (Button)v.findViewById(R.id.stopwatch_left_button); mLeftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonClicked(true); switch (mState) { case STOPWATCH_RUNNING: // Save lap time addLapTime(System.currentTimeMillis()/10); showLaps(); setButtons(STOPWATCH_RUNNING); break; case STOPWATCH_STOPPED: // do reset mAccumulatedTime = 0; mLapsAdapter.clearLaps(); showLaps(); mTime.stopIntervalAnimation(); mTime.reset(); mTimeText.setTime(mAccumulatedTime); mTimeText.blinkTimeStr(false); setButtons(STOPWATCH_RESET); mState = STOPWATCH_RESET; break; default: Log.wtf("Illegal state " + mState + " while pressing the left stopwatch button"); break; } } }); mRightButton = (Button)v.findViewById(R.id.stopwatch_right_button); mRightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonClicked(true); switch (mState) { case STOPWATCH_RUNNING: // do stop stopUpdateThread(); mTime.pauseIntervalAnimation(); long curTime = System.currentTimeMillis()/10; mAccumulatedTime += (curTime - mStartTime); mTimeText.setTime(mAccumulatedTime); mTimeText.blinkTimeStr(true); updateCurrentLap(curTime, mAccumulatedTime); setButtons(STOPWATCH_STOPPED); mState = STOPWATCH_STOPPED; break; case STOPWATCH_RESET: case STOPWATCH_STOPPED: // do start mStartTime = System.currentTimeMillis()/10; startUpdateThread(); mTimeText.blinkTimeStr(false); if (mTime.isAnimating()) { mTime.startIntervalAnimation(); } setButtons(STOPWATCH_RUNNING); mState = STOPWATCH_RUNNING; break; default: Log.wtf("Illegal state " + mState + " while pressing the right stopwatch button"); break; } } }); mShareButton = (Button)v.findViewById(R.id.stopwatch_share_button); mButtonSeperator = v.findViewById(R.id.stopwatch_button_seperator); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/plain"); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); // Add data to the intent, the receiving app will decide what to // do with it. intent.putExtra(Intent.EXTRA_SUBJECT, getActivity().getResources().getString(R.string.sw_share_title)); intent.putExtra(Intent.EXTRA_TEXT, buildShareResults()); startActivity(Intent.createChooser(intent, null)); } }); mTime = (CircleTimerView)v.findViewById(R.id.stopwatch_time); mTimeText = (TimerView)v.findViewById(R.id.stopwatch_time_text); mLapsTitle = v.findViewById(R.id.laps_title); mLapsList = (ListView)v.findViewById(R.id.laps_list); mLapsList.setDividerHeight(0); mLapsAdapter = new LapsListAdapter(getActivity()); if (mLapsList != null) { mLapsList.setAdapter(mLapsAdapter); } if (savedInstanceState != null) { mState = savedInstanceState.getInt(STATE_KEY, STOPWATCH_RESET); mStartTime = savedInstanceState.getLong(START_TIME_KEY, 0); mAccumulatedTime = savedInstanceState.getLong(ACCUM_TIME_KEY, 0); mLapsAdapter.setLapTimes(savedInstanceState.getLongArray(LAPS_KEY)); } return v; }
diff --git a/FallPrevention/src/no/ntnu/stud/fallprevention/WidgetUpdateService.java b/FallPrevention/src/no/ntnu/stud/fallprevention/WidgetUpdateService.java index 6334b9a..bebeddd 100644 --- a/FallPrevention/src/no/ntnu/stud/fallprevention/WidgetUpdateService.java +++ b/FallPrevention/src/no/ntnu/stud/fallprevention/WidgetUpdateService.java @@ -1,105 +1,106 @@ package no.ntnu.stud.fallprevention; import java.util.Timer; import java.util.TimerTask; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.IBinder; import android.widget.RemoteViews; public class WidgetUpdateService extends Service { private final int WIDGET_UPDATE_FREQUENCY = 5000; @Override public int onStartCommand(Intent intent, int flags,int startId) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext()); Context context = this.getApplicationContext(); Timer timer = new Timer(); timer.schedule(new Updater(appWidgetManager, context), WIDGET_UPDATE_FREQUENCY, WIDGET_UPDATE_FREQUENCY); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { return null; } private class Updater extends TimerTask { AppWidgetManager appWidgetManager; Context context; public Updater(AppWidgetManager appWidgetManager, Context context) { this.appWidgetManager = appWidgetManager; this.context = context; } @Override public void run() { ComponentName thisWidget = new ComponentName(getApplicationContext(), WidgetProvider.class); int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); for (int widgetId : allWidgetIds) { RemoteViews views; // Change background if there are new messages if (new DatabaseHelper(context).dbHaveEvents()) { views = new RemoteViews(context.getPackageName(), R.layout.widget_layout_w_messages); } else { views = new RemoteViews(context.getPackageName(), R.layout.widget_layout_no_messages); } // Update face based on state RiskStatus status = new DatabaseHelper(context).dbGetStatus(); Drawable drawable; if (status == RiskStatus.BAD_JOB) { drawable = context.getResources().getDrawable(R.drawable.bad_job); } else if (status == RiskStatus.NOT_SO_OK_JOB) { drawable = context.getResources().getDrawable(R.drawable.not_so_ok_job); } else if (status == RiskStatus.OK_JOB) { drawable = context.getResources().getDrawable(R.drawable.ok_job); } else if (status == RiskStatus.GOOD_JOB) { drawable = context.getResources().getDrawable(R.drawable.good_job); } else if (status == RiskStatus.VERY_GOOD_JOB) { drawable = context.getResources().getDrawable(R.drawable.very_good_job); } else { // Problem. This should never happen throw new RuntimeException("Error thrown at WidgetUpdateService.java:71"); } Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true); views.setBitmap(R.id.smileyButton, "setImageBitmap", bitmap); - appWidgetManager.updateAppWidget(widgetId, views); + //appWidgetManager.updateAppWidget(widgetId, views); - // ADD A LISTENER: TODO: Check if this works with the chagnes + // Add onClickListener Intent clickIntent = new Intent(context, EventList.class); PendingIntent pendIntent = PendingIntent.getActivity(context, 0, clickIntent, 0); views.setOnClickPendingIntent(R.id.smileyButton, pendIntent); - ComponentName name = new ComponentName(context, this.getClass()); - appWidgetManager.updateAppWidget(name, views); + // ComponentName name = new ComponentName(context, this.getClass()); + // appWidgetManager.updateAppWidget(name, views); + appWidgetManager.updateAppWidget(widgetId, views); } } } }
false
true
public void run() { ComponentName thisWidget = new ComponentName(getApplicationContext(), WidgetProvider.class); int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); for (int widgetId : allWidgetIds) { RemoteViews views; // Change background if there are new messages if (new DatabaseHelper(context).dbHaveEvents()) { views = new RemoteViews(context.getPackageName(), R.layout.widget_layout_w_messages); } else { views = new RemoteViews(context.getPackageName(), R.layout.widget_layout_no_messages); } // Update face based on state RiskStatus status = new DatabaseHelper(context).dbGetStatus(); Drawable drawable; if (status == RiskStatus.BAD_JOB) { drawable = context.getResources().getDrawable(R.drawable.bad_job); } else if (status == RiskStatus.NOT_SO_OK_JOB) { drawable = context.getResources().getDrawable(R.drawable.not_so_ok_job); } else if (status == RiskStatus.OK_JOB) { drawable = context.getResources().getDrawable(R.drawable.ok_job); } else if (status == RiskStatus.GOOD_JOB) { drawable = context.getResources().getDrawable(R.drawable.good_job); } else if (status == RiskStatus.VERY_GOOD_JOB) { drawable = context.getResources().getDrawable(R.drawable.very_good_job); } else { // Problem. This should never happen throw new RuntimeException("Error thrown at WidgetUpdateService.java:71"); } Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true); views.setBitmap(R.id.smileyButton, "setImageBitmap", bitmap); appWidgetManager.updateAppWidget(widgetId, views); // ADD A LISTENER: TODO: Check if this works with the chagnes Intent clickIntent = new Intent(context, EventList.class); PendingIntent pendIntent = PendingIntent.getActivity(context, 0, clickIntent, 0); views.setOnClickPendingIntent(R.id.smileyButton, pendIntent); ComponentName name = new ComponentName(context, this.getClass()); appWidgetManager.updateAppWidget(name, views); } }
public void run() { ComponentName thisWidget = new ComponentName(getApplicationContext(), WidgetProvider.class); int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); for (int widgetId : allWidgetIds) { RemoteViews views; // Change background if there are new messages if (new DatabaseHelper(context).dbHaveEvents()) { views = new RemoteViews(context.getPackageName(), R.layout.widget_layout_w_messages); } else { views = new RemoteViews(context.getPackageName(), R.layout.widget_layout_no_messages); } // Update face based on state RiskStatus status = new DatabaseHelper(context).dbGetStatus(); Drawable drawable; if (status == RiskStatus.BAD_JOB) { drawable = context.getResources().getDrawable(R.drawable.bad_job); } else if (status == RiskStatus.NOT_SO_OK_JOB) { drawable = context.getResources().getDrawable(R.drawable.not_so_ok_job); } else if (status == RiskStatus.OK_JOB) { drawable = context.getResources().getDrawable(R.drawable.ok_job); } else if (status == RiskStatus.GOOD_JOB) { drawable = context.getResources().getDrawable(R.drawable.good_job); } else if (status == RiskStatus.VERY_GOOD_JOB) { drawable = context.getResources().getDrawable(R.drawable.very_good_job); } else { // Problem. This should never happen throw new RuntimeException("Error thrown at WidgetUpdateService.java:71"); } Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true); views.setBitmap(R.id.smileyButton, "setImageBitmap", bitmap); //appWidgetManager.updateAppWidget(widgetId, views); // Add onClickListener Intent clickIntent = new Intent(context, EventList.class); PendingIntent pendIntent = PendingIntent.getActivity(context, 0, clickIntent, 0); views.setOnClickPendingIntent(R.id.smileyButton, pendIntent); // ComponentName name = new ComponentName(context, this.getClass()); // appWidgetManager.updateAppWidget(name, views); appWidgetManager.updateAppWidget(widgetId, views); } }
diff --git a/src/main/java/de/cismet/verdis/search/KassenzeichenGeomSearch.java b/src/main/java/de/cismet/verdis/search/KassenzeichenGeomSearch.java index 6d6cfcd..024513c 100644 --- a/src/main/java/de/cismet/verdis/search/KassenzeichenGeomSearch.java +++ b/src/main/java/de/cismet/verdis/search/KassenzeichenGeomSearch.java @@ -1,133 +1,134 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * Copyright (C) 2010 thorsten * * 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.cismet.verdis.search; import Sirius.server.middleware.interfaces.domainserver.MetaService; import com.vividsolutions.jts.geom.Geometry; import de.cismet.verdis.CidsAppBackend; import de.cismet.verdis.constants.KassenzeichenPropertyConstants; import de.cismet.verdis.constants.VerdisMetaClassConstants; import java.util.*; /** * DOCUMENT ME! * * @author thorsten * @version $Revision$, $Date$ */ public class KassenzeichenGeomSearch extends GeomServerSearch { @Override public Collection performServerSearch() { final Geometry searchGeometry = getGeometry(); if (searchGeometry != null) { final String sqlKassenzeichenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " geom.id = kassenzeichen.geometrie AND " + - " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) AND " + + " GeometryType(geom.geo_field) = 'POINT' " + " ORDER BY kassenzeichennumer ASC;"; final String sqlFlaechenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " flaechen AS flaechen, " + " " + VerdisMetaClassConstants.MC_FLAECHE + " AS flaeche, " + " " + VerdisMetaClassConstants.MC_FLAECHENINFO + " AS flaecheninfo, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " flaechen.kassenzeichen_reference = kassenzeichen.id AND " + " flaechen.flaeche = flaeche.id AND " + " flaeche.flaecheninfo = flaecheninfo.id AND " + " geom.id = flaecheninfo.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final String sqlFrontenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " fronten AS fronten, " + " " + VerdisMetaClassConstants.MC_FRONTINFO + " AS frontinfo, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " fronten.kassenzeichen_reference = kassenzeichen.id AND " + " fronten.frontinfo = frontinfo.id AND " + " geom.id = frontinfo.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final MetaService metaService = (MetaService) getActiveLoaclServers().get(CidsAppBackend.DOMAIN); // ids der kassenzeichen sammeln final Set<Integer> idSet = new HashSet<Integer>(); getLog().debug(sqlKassenzeichenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlKassenzeichenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during kassenzeichen geom search", ex); } getLog().debug(sqlFlaechenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlFlaechenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during flaechen geom search", ex); } getLog().debug(sqlFrontenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlFrontenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during fronten geom search", ex); } // ids der Kassenzeichen sortieren final List<Integer> sortedIdList = Arrays.asList(idSet.toArray(new Integer[0])); Collections.sort(sortedIdList); // return sortedIdList; } else { getLog().info("searchGeometry is null, geom search is not possible"); } return null; } }
true
true
public Collection performServerSearch() { final Geometry searchGeometry = getGeometry(); if (searchGeometry != null) { final String sqlKassenzeichenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " geom.id = kassenzeichen.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final String sqlFlaechenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " flaechen AS flaechen, " + " " + VerdisMetaClassConstants.MC_FLAECHE + " AS flaeche, " + " " + VerdisMetaClassConstants.MC_FLAECHENINFO + " AS flaecheninfo, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " flaechen.kassenzeichen_reference = kassenzeichen.id AND " + " flaechen.flaeche = flaeche.id AND " + " flaeche.flaecheninfo = flaecheninfo.id AND " + " geom.id = flaecheninfo.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final String sqlFrontenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " fronten AS fronten, " + " " + VerdisMetaClassConstants.MC_FRONTINFO + " AS frontinfo, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " fronten.kassenzeichen_reference = kassenzeichen.id AND " + " fronten.frontinfo = frontinfo.id AND " + " geom.id = frontinfo.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final MetaService metaService = (MetaService) getActiveLoaclServers().get(CidsAppBackend.DOMAIN); // ids der kassenzeichen sammeln final Set<Integer> idSet = new HashSet<Integer>(); getLog().debug(sqlKassenzeichenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlKassenzeichenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during kassenzeichen geom search", ex); } getLog().debug(sqlFlaechenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlFlaechenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during flaechen geom search", ex); } getLog().debug(sqlFrontenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlFrontenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during fronten geom search", ex); } // ids der Kassenzeichen sortieren final List<Integer> sortedIdList = Arrays.asList(idSet.toArray(new Integer[0])); Collections.sort(sortedIdList); // return sortedIdList; } else { getLog().info("searchGeometry is null, geom search is not possible"); } return null; }
public Collection performServerSearch() { final Geometry searchGeometry = getGeometry(); if (searchGeometry != null) { final String sqlKassenzeichenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " geom.id = kassenzeichen.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) AND " + " GeometryType(geom.geo_field) = 'POINT' " + " ORDER BY kassenzeichennumer ASC;"; final String sqlFlaechenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " flaechen AS flaechen, " + " " + VerdisMetaClassConstants.MC_FLAECHE + " AS flaeche, " + " " + VerdisMetaClassConstants.MC_FLAECHENINFO + " AS flaecheninfo, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " flaechen.kassenzeichen_reference = kassenzeichen.id AND " + " flaechen.flaeche = flaeche.id AND " + " flaeche.flaecheninfo = flaecheninfo.id AND " + " geom.id = flaecheninfo.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final String sqlFrontenGeom = "SELECT " + " DISTINCT " + VerdisMetaClassConstants.MC_KASSENZEICHEN + "." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " AS kassenzeichennumer " + "FROM " + " " + VerdisMetaClassConstants.MC_KASSENZEICHEN + " AS kassenzeichen, " + " fronten AS fronten, " + " " + VerdisMetaClassConstants.MC_FRONTINFO + " AS frontinfo, " + " " + VerdisMetaClassConstants.MC_GEOM + " AS geom " + "WHERE " + " kassenzeichen." + KassenzeichenPropertyConstants.PROP__KASSENZEICHENNUMMER + " IS NOT NULL AND " + " fronten.kassenzeichen_reference = kassenzeichen.id AND " + " fronten.frontinfo = frontinfo.id AND " + " geom.id = frontinfo.geometrie AND " + " ST_Intersects(GeomFromText('" + searchGeometry.toText() + "', " + searchGeometry.getSRID() + "), geom.geo_field) " + " ORDER BY kassenzeichennumer ASC;"; final MetaService metaService = (MetaService) getActiveLoaclServers().get(CidsAppBackend.DOMAIN); // ids der kassenzeichen sammeln final Set<Integer> idSet = new HashSet<Integer>(); getLog().debug(sqlKassenzeichenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlKassenzeichenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during kassenzeichen geom search", ex); } getLog().debug(sqlFlaechenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlFlaechenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during flaechen geom search", ex); } getLog().debug(sqlFrontenGeom); try { for (final ArrayList fields : metaService.performCustomSearch(sqlFrontenGeom)) { idSet.add((Integer) fields.get(0)); } } catch (Exception ex) { getLog().error("problem during fronten geom search", ex); } // ids der Kassenzeichen sortieren final List<Integer> sortedIdList = Arrays.asList(idSet.toArray(new Integer[0])); Collections.sort(sortedIdList); // return sortedIdList; } else { getLog().info("searchGeometry is null, geom search is not possible"); } return null; }
diff --git a/src/main/java/net/slreynolds/ds/util/Pair.java b/src/main/java/net/slreynolds/ds/util/Pair.java index 27ba445..a851d07 100644 --- a/src/main/java/net/slreynolds/ds/util/Pair.java +++ b/src/main/java/net/slreynolds/ds/util/Pair.java @@ -1,65 +1,65 @@ package net.slreynolds.ds.util; public class Pair<S,T> { private final S one; private final T two; public Pair(S s, T t) { one = s; two = t; } public S first() { return one; } public T second() { return two; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((one == null) ? 0 : one.hashCode()); result = prime * result + ((two == null) ? 0 : two.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Pair)) { return false; } - Pair other = (Pair) obj; + Pair<?,?> other = (Pair<?,?>) obj; if (one == null) { if (other.one != null) { return false; } } else if (!one.equals(other.one)) { return false; } if (two == null) { if (other.two != null) { return false; } } else if (!two.equals(other.two)) { return false; } return true; } @Override public String toString() { return "Pair ["+ one + two + "]"; } }
true
true
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Pair)) { return false; } Pair other = (Pair) obj; if (one == null) { if (other.one != null) { return false; } } else if (!one.equals(other.one)) { return false; } if (two == null) { if (other.two != null) { return false; } } else if (!two.equals(other.two)) { return false; } return true; }
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Pair)) { return false; } Pair<?,?> other = (Pair<?,?>) obj; if (one == null) { if (other.one != null) { return false; } } else if (!one.equals(other.one)) { return false; } if (two == null) { if (other.two != null) { return false; } } else if (!two.equals(other.two)) { return false; } return true; }
diff --git a/src/amstin/models/grammar/parsing/Memo.java b/src/amstin/models/grammar/parsing/Memo.java index ce0e29e..0ace225 100644 --- a/src/amstin/models/grammar/parsing/Memo.java +++ b/src/amstin/models/grammar/parsing/Memo.java @@ -1,68 +1,73 @@ package amstin.models.grammar.parsing; import java.util.HashMap; import java.util.Map; public class Memo implements IParser { private IParser parser; public Memo(IParser parser) { // System.out.println("Memoizing: " + parser.getClass()); this.parser = parser; } @Override public void parse(Map<IParser, Map<Integer, Entry>> table, Cnt cnt, final String src, int pos) { if (!table.containsKey(parser)) { table.put(parser, new HashMap<Integer, Entry>()); } if (!table.get(parser).containsKey(pos)) { table.get(parser).put(pos, new Entry()); } final Entry entry = table.get(parser).get(pos); if (entry.cnts.isEmpty()) { entry.cnts.add(cnt); parser.parse(table, new MemoCnt(entry), src, pos); } else { entry.cnts.add(cnt); - int i = 0; - for (int r: entry.results) { + int l = entry.results.size(); + for (int i = 0; i < l; i++) { + // if an item is added to entry.results cflowbelow cnt.apply + // we do not reprocesses it here. I don't know if this is wrong. + // but we cannot use an iterator over results, because + // you get concurrentmodification errors (e.g. when parsing + // multiply nested left recursive expressions). + int r = entry.results.get(i); cnt.apply(r, entry.objects.get(i)); - i++; } } } private static class MemoCnt implements Cnt { private final Entry entry; public MemoCnt(Entry entry) { this.entry = entry; } @Override public void apply(int result, Object tree) { if (!entry.isSubsumed(result, tree)) { entry.results.add(result); entry.objects.add(tree); for (Cnt c: entry.cnts) { c.apply(result, tree); } } } } }
false
true
public void parse(Map<IParser, Map<Integer, Entry>> table, Cnt cnt, final String src, int pos) { if (!table.containsKey(parser)) { table.put(parser, new HashMap<Integer, Entry>()); } if (!table.get(parser).containsKey(pos)) { table.get(parser).put(pos, new Entry()); } final Entry entry = table.get(parser).get(pos); if (entry.cnts.isEmpty()) { entry.cnts.add(cnt); parser.parse(table, new MemoCnt(entry), src, pos); } else { entry.cnts.add(cnt); int i = 0; for (int r: entry.results) { cnt.apply(r, entry.objects.get(i)); i++; } } }
public void parse(Map<IParser, Map<Integer, Entry>> table, Cnt cnt, final String src, int pos) { if (!table.containsKey(parser)) { table.put(parser, new HashMap<Integer, Entry>()); } if (!table.get(parser).containsKey(pos)) { table.get(parser).put(pos, new Entry()); } final Entry entry = table.get(parser).get(pos); if (entry.cnts.isEmpty()) { entry.cnts.add(cnt); parser.parse(table, new MemoCnt(entry), src, pos); } else { entry.cnts.add(cnt); int l = entry.results.size(); for (int i = 0; i < l; i++) { // if an item is added to entry.results cflowbelow cnt.apply // we do not reprocesses it here. I don't know if this is wrong. // but we cannot use an iterator over results, because // you get concurrentmodification errors (e.g. when parsing // multiply nested left recursive expressions). int r = entry.results.get(i); cnt.apply(r, entry.objects.get(i)); } } }
diff --git a/Paco/src/com/google/android/apps/paco/FindExperimentsActivity.java b/Paco/src/com/google/android/apps/paco/FindExperimentsActivity.java index 90cf3e380..e44e6bc2d 100644 --- a/Paco/src/com/google/android/apps/paco/FindExperimentsActivity.java +++ b/Paco/src/com/google/android/apps/paco/FindExperimentsActivity.java @@ -1,390 +1,390 @@ /* * Copyright 2011 Google Inc. All Rights Reserved. * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.google.android.apps.paco; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * */ public class FindExperimentsActivity extends Activity { private static final int DATA_EXPERIMENT_OPTION = 3; private static final int STOP_EXPERIMENT_OPTION = 2; private static final int EDIT_EXPERIMENT_OPTION = 1; static final int JOIN_REQUEST_CODE = 1; static final int JOINED_EXPERIMENT = 1; private boolean showingJoinedExperiments; private Cursor cursor; private ExperimentProviderUtil experimentProviderUtil; private ListView list; private ProgressDialog p; private ViewGroup mainLayout; public UserPreferences userPrefs; private BaseAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.find_experiments, null); setContentView(mainLayout); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(ExperimentColumns.CONTENT_URI); } showingJoinedExperiments = intent.getData().equals(ExperimentColumns.JOINED_EXPERIMENTS_CONTENT_URI); userPrefs = new UserPreferences(this); ensureGoogleAccountChosen(); list = (ListView) findViewById(R.id.find_experiments_list); createListHeader(); Button listFooter = (Button) findViewById(R.id.RefreshExperimentsButton2); listFooter.setVisibility(View.VISIBLE); if (!showingJoinedExperiments) { listFooter.setOnClickListener(new OnClickListener() { public void onClick(View v) { refreshList(); } }); } else { listFooter.setVisibility(View.GONE); } experimentProviderUtil = new ExperimentProviderUtil(this); String selectionArgs = null; if (!showingJoinedExperiments) { selectionArgs = ExperimentColumns.JOIN_DATE + " IS NULL"; } cursor = managedQuery(getIntent().getData(), new String[] { ExperimentColumns._ID, ExperimentColumns.TITLE, ExperimentColumns.CREATOR, ExperimentColumns.ICON }, - selectionArgs, null, ExperimentColumns.TITLE); + selectionArgs, null, ExperimentColumns.TITLE + " COLLATE NOCASE ASC"); if (showingJoinedExperiments) { adapter = new RunningExperimentListAdapter(this, cursor); } else { adapter = new AvailableExperimentListAdapter(this, cursor); //new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, // new String[] { ExperimentColumns.TITLE }, // new int[] { android.R.id.text1 }) {}; } list.setAdapter(adapter); if (!showingJoinedExperiments) { list.setItemsCanFocus(true); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> listview, View textview, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return an experiment selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); } else { Intent experimentIntent = new Intent(FindExperimentsActivity.this, ExperimentDetailActivity.class); experimentIntent.setData(uri); startActivityForResult(experimentIntent, JOIN_REQUEST_CODE); } } }); } registerForContextMenu(list); } @Override protected void onResume() { super.onResume(); if (!showingJoinedExperiments && listIsStale()) { refreshList(); } } private void ensureGoogleAccountChosen() { if (userPrefs.getSelectedAccount(this) == null) { Intent acctChooser = new Intent(this, AccountChooser.class); this.startActivity(acctChooser); } } private boolean listIsStale() { return userPrefs.isExperimentListStale(); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case EDIT_EXPERIMENT_OPTION: editExperiment(info.id); return true; case STOP_EXPERIMENT_OPTION: deleteExperiment(info.id); return true; case DATA_EXPERIMENT_OPTION: showDataForExperiment(info.id); return true; default: return super.onContextItemSelected(item); } } private void showDataForExperiment(long id) { Intent experimentIntent = new Intent(FindExperimentsActivity.this, FeedbackActivity.class); experimentIntent.setData(Uri.withAppendedPath(getIntent().getData(), Long.toString(id))); startActivity(experimentIntent); } private void deleteExperiment(long id) { NotificationCreator nc = NotificationCreator.create(this); nc.timeoutNotificationsForExperiment(id); experimentProviderUtil.deleteFullExperiment(Uri.withAppendedPath(getIntent().getData(), Long.toString(id))); new AlarmStore(this).deleteAllSignalsForSurvey(id); cursor.requery(); startService(new Intent(FindExperimentsActivity.this, BeeperService.class)); } private void editExperiment(long id) { Intent experimentIntent = new Intent(FindExperimentsActivity.this, ExperimentScheduleActivity.class); experimentIntent.setData(Uri.withAppendedPath(getIntent().getData(), Long.toString(id))); startActivity(experimentIntent); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.equals(list) && showingJoinedExperiments) { // AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; // int position = info.position; // SignalSchedule schedule = ((Experiment)(adapter.getItem(position))).getSchedule(); // if (schedule.getUserEditable() != null && // schedule.getUserEditable()) { menu.add(0, EDIT_EXPERIMENT_OPTION, 0, "Edit Schedule"); // } menu.add(0, STOP_EXPERIMENT_OPTION, 0, "Stop Experiment"); menu.add(0, DATA_EXPERIMENT_OPTION, 0, "Explore Data"); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == JOIN_REQUEST_CODE) { if (resultCode == JOINED_EXPERIMENT) { finish(); } } } private TextView createListHeader() { TextView listHeader = (TextView)findViewById(R.id.ExperimentListTitle); String header = null; if (showingJoinedExperiments) { header = "Running Experiments"; } else { header = "Available Experiments"; } listHeader.setText(header); listHeader.setTextSize(25); return listHeader; } protected void refreshList() { DownloadExperimentsTaskListener listener = new DownloadExperimentsTaskListener() { @Override public void done() { cursor.requery(); } }; new DownloadExperimentsTask(this, listener, userPrefs, experimentProviderUtil, null).execute(); } private class RunningExperimentListAdapter extends CursorAdapter { private LayoutInflater mInflater; private int titleColumn; private int idColumn; RunningExperimentListAdapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); titleColumn = cursor.getColumnIndex( ExperimentColumns.TITLE); idColumn = cursor.getColumnIndex(ExperimentColumns._ID); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = mInflater.inflate(R.layout.experiment_list_row, parent, false); return v; } @Override public void bindView(View view, Context context, Cursor cursor) { String id = cursor.getString(idColumn); TextView tv = (TextView) view.findViewById(R.id.experimentListRowTitle); tv.setText(cursor.getString(titleColumn)); tv.setOnClickListener(myButtonListener); tv.setTag(id); ImageButton editButton = (ImageButton)view.findViewById(R.id.editExperimentButton); editButton.setOnClickListener(myButtonListener); editButton.setTag(id); ImageButton quitButton = (ImageButton)view.findViewById(R.id.quitExperimentButton); quitButton.setOnClickListener(myButtonListener); quitButton.setTag(id); ImageButton exploreButton = (ImageButton)view.findViewById(R.id.exploreDataExperimentButton); exploreButton.setOnClickListener(myButtonListener); exploreButton.setTag(id); // show icon // ImageView iv = (ImageView) view.findViewById(R.id.explore_data_icon); // iv.setImageResource(); } private OnClickListener myButtonListener = new OnClickListener() { @Override public void onClick(final View v) { final int position = list.getPositionForView(v); if (position == ListView.INVALID_POSITION) { return; } else if (v.getId() == R.id.editExperimentButton) { editExperiment(Long.parseLong((String) v.getTag())); } else if (v.getId() == R.id.exploreDataExperimentButton) { showDataForExperiment(Long.parseLong((String) v.getTag())); } else if (v.getId() == R.id.quitExperimentButton) { new AlertDialog.Builder(FindExperimentsActivity.this) .setCancelable(true) .setTitle("Stop the Experiment?") .setMessage("Are you sure you want to stop the experiment?") .setPositiveButton("Yes", new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteExperiment(Long.parseLong((String) v.getTag())); } }) .setNegativeButton("No", new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } else if (v.getId() == R.id.experimentListRowTitle) { Intent experimentIntent = new Intent(FindExperimentsActivity.this, ExperimentExecutor.class); Uri uri = ContentUris.withAppendedId(getIntent().getData(), Long.parseLong((String)v.getTag())); experimentIntent.setData(uri); startActivity(experimentIntent); finish(); } } }; } private class AvailableExperimentListAdapter extends CursorAdapter { private LayoutInflater mInflater; private int titleColumn; private int idColumn; private int creatorColumn; private int iconColumn; AvailableExperimentListAdapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); titleColumn = cursor.getColumnIndex( ExperimentColumns.TITLE); creatorColumn = cursor.getColumnIndex(ExperimentColumns.CREATOR); idColumn = cursor.getColumnIndex(ExperimentColumns._ID); //iconColumn = cursor.getColumnIndex(ExperimentColumns.ICON); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = mInflater.inflate(R.layout.experiments_available_list_row, parent, false); return v; } @Override public void bindView(View view, Context context, Cursor cursor) { String id = cursor.getString(idColumn); TextView tv = (TextView) view.findViewById(R.id.experimentListRowTitle); tv.setText(cursor.getString(titleColumn)); String creatorText = null; if (creatorColumn != -1) { creatorText = cursor.getString(creatorColumn); } else { creatorText = "unknown author"; } TextView tv2 = (TextView) view.findViewById(R.id.experimentListRowCreator); tv2.setText(creatorText); // ImageView iv = (ImageView) view.findViewById(R.id.experimentIconView); // iv.setImageBitmap(Bitmap.create(cursor.getString(iconColumn))); } } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.find_experiments, null); setContentView(mainLayout); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(ExperimentColumns.CONTENT_URI); } showingJoinedExperiments = intent.getData().equals(ExperimentColumns.JOINED_EXPERIMENTS_CONTENT_URI); userPrefs = new UserPreferences(this); ensureGoogleAccountChosen(); list = (ListView) findViewById(R.id.find_experiments_list); createListHeader(); Button listFooter = (Button) findViewById(R.id.RefreshExperimentsButton2); listFooter.setVisibility(View.VISIBLE); if (!showingJoinedExperiments) { listFooter.setOnClickListener(new OnClickListener() { public void onClick(View v) { refreshList(); } }); } else { listFooter.setVisibility(View.GONE); } experimentProviderUtil = new ExperimentProviderUtil(this); String selectionArgs = null; if (!showingJoinedExperiments) { selectionArgs = ExperimentColumns.JOIN_DATE + " IS NULL"; } cursor = managedQuery(getIntent().getData(), new String[] { ExperimentColumns._ID, ExperimentColumns.TITLE, ExperimentColumns.CREATOR, ExperimentColumns.ICON }, selectionArgs, null, ExperimentColumns.TITLE); if (showingJoinedExperiments) { adapter = new RunningExperimentListAdapter(this, cursor); } else { adapter = new AvailableExperimentListAdapter(this, cursor); //new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, // new String[] { ExperimentColumns.TITLE }, // new int[] { android.R.id.text1 }) {}; } list.setAdapter(adapter); if (!showingJoinedExperiments) { list.setItemsCanFocus(true); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> listview, View textview, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return an experiment selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); } else { Intent experimentIntent = new Intent(FindExperimentsActivity.this, ExperimentDetailActivity.class); experimentIntent.setData(uri); startActivityForResult(experimentIntent, JOIN_REQUEST_CODE); } } }); } registerForContextMenu(list); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.find_experiments, null); setContentView(mainLayout); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(ExperimentColumns.CONTENT_URI); } showingJoinedExperiments = intent.getData().equals(ExperimentColumns.JOINED_EXPERIMENTS_CONTENT_URI); userPrefs = new UserPreferences(this); ensureGoogleAccountChosen(); list = (ListView) findViewById(R.id.find_experiments_list); createListHeader(); Button listFooter = (Button) findViewById(R.id.RefreshExperimentsButton2); listFooter.setVisibility(View.VISIBLE); if (!showingJoinedExperiments) { listFooter.setOnClickListener(new OnClickListener() { public void onClick(View v) { refreshList(); } }); } else { listFooter.setVisibility(View.GONE); } experimentProviderUtil = new ExperimentProviderUtil(this); String selectionArgs = null; if (!showingJoinedExperiments) { selectionArgs = ExperimentColumns.JOIN_DATE + " IS NULL"; } cursor = managedQuery(getIntent().getData(), new String[] { ExperimentColumns._ID, ExperimentColumns.TITLE, ExperimentColumns.CREATOR, ExperimentColumns.ICON }, selectionArgs, null, ExperimentColumns.TITLE + " COLLATE NOCASE ASC"); if (showingJoinedExperiments) { adapter = new RunningExperimentListAdapter(this, cursor); } else { adapter = new AvailableExperimentListAdapter(this, cursor); //new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, // new String[] { ExperimentColumns.TITLE }, // new int[] { android.R.id.text1 }) {}; } list.setAdapter(adapter); if (!showingJoinedExperiments) { list.setItemsCanFocus(true); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> listview, View textview, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return an experiment selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); } else { Intent experimentIntent = new Intent(FindExperimentsActivity.this, ExperimentDetailActivity.class); experimentIntent.setData(uri); startActivityForResult(experimentIntent, JOIN_REQUEST_CODE); } } }); } registerForContextMenu(list); }
diff --git a/components/bio-formats/src/loci/formats/tools/ImageInfo.java b/components/bio-formats/src/loci/formats/tools/ImageInfo.java index 887136c27..135c1fa1b 100644 --- a/components/bio-formats/src/loci/formats/tools/ImageInfo.java +++ b/components/bio-formats/src/loci/formats/tools/ImageInfo.java @@ -1,675 +1,676 @@ // // ImageInfo.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.tools; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.StringTokenizer; import loci.common.*; import loci.formats.*; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; /** * ImageInfo is a utility class for reading a file * and reporting information about it. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/tools/ImageInfo.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/tools/ImageInfo.java">SVN</a></dd></dl> */ public final class ImageInfo { // -- Constructor -- private ImageInfo() { } // -- Utility methods -- /** * A utility method for reading a file from the command line, * and displaying the results in a simple display. */ public static boolean testRead(String[] args) throws FormatException, IOException { return testRead(new ImageReader(), args); } /** * A utility method for reading a file from the command line, and * displaying the results in a simple display, using the given reader. */ public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean minmax = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean expand = false; boolean omexml = false; boolean normalize = false; boolean fastBlit = false; boolean preload = false; String omexmlVersion = null; int start = 0; int end = Integer.MAX_VALUE; int series = 0; int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; String swapOrder = null, shuffleOrder = null; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatHandler.setDebug(true); else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-version")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-level")) { try { FormatHandler.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-shuffle")) { shuffleOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else LogTools.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else LogTools.println("Ignoring unknown argument: " + args[i]); } } } if (FormatHandler.debug) { LogTools.println("Debugging at level " + FormatHandler.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf file [-nopix] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap inputOrder] [-shuffle outputOrder] [-map id] [-preload]", " [-version v] [-crop x,y,w,h]", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default input dimension order", " -shuffle: override the default output dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -version: specify which OME-XML version should be generated", " -crop: crop images before displaying; argument is 'x,y,w,h'", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LogTools.println(s[i]); return false; } if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessStream f = new RandomAccessStream(id); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); RABytes file = new RABytes(b); Location.mapFile(id, file); } if (omexml) { reader.setOriginalMetadataPopulated(true); MetadataStore store = MetadataTools.createOMEXMLMetadata(null, omexmlVersion); if (store != null) reader.setMetadataStore(store); } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; LogTools.print("Checking file format "); LogTools.println("[" + ir.getFormat(id) + "]"); } else { // verify format LogTools.print("Checking " + reader.getFormat() + " format "); LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]"); } LogTools.println("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); MinMaxCalculator minMaxCalc = null; if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader); DimensionSwapper dimSwapper = null; if (swapOrder != null || shuffleOrder != null) { reader = dimSwapper = new DimensionSwapper(reader); } StatusEchoer status = new StatusEchoer(); reader.addStatusListener(status); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(true); reader.setMetadataCollected(doMeta); long s1 = System.currentTimeMillis(); reader.setId(id); long e1 = System.currentTimeMillis(); float sec1 = (e1 - s1) / 1000f; LogTools.println("Initialization took " + sec1 + "s"); if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (shuffleOrder != null) dimSwapper.setOutputOrder(shuffleOrder); if (!normalize && (reader.getPixelType() == FormatTools.FLOAT || reader.getPixelType() == FormatTools.DOUBLE)) { LogTools.println("Warning: Java does not support " + "display of unnormalized floating point data."); LogTools.println("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } if (reader.isRGB() && reader.getRGBChannelCount() > 4) { LogTools.println("Warning: Java does not support " + "merging more than 4 channels."); LogTools.println("Please use the '-separate' option " + "to avoid receiving a cryptic exception."); } // read basic metadata LogTools.println(); LogTools.println("Reading core metadata"); LogTools.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) LogTools.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LogTools.println( "************ Warning: invalid used files list ************"); } if (used == null) { LogTools.println("Used files = null"); } else if (used.length == 0) { LogTools.println("Used files = []"); } else if (used.length > 1) { LogTools.println("Used files:"); for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]); } else if (!id.equals(used[0])) { LogTools.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(); LogTools.println("Series count = " + seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series #i int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean thumbnail = reader.isThumbnailSeries(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series #i String seriesName = mr == null ? null : mr.getImageName(j); LogTools.println("Series #" + j + (seriesName == null ? "" : " -- " + seriesName) + ":"); LogTools.println("\tImage count = " + imageCount); LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) LogTools.print(" (merged)"); else if (separate) LogTools.print(" (separated)"); LogTools.println(); if (rgb != (rgbChanCount != 1)) { LogTools.println("\t************ Warning: RGB mismatch ************"); } LogTools.println("\tInterleaved = " + interleaved); LogTools.print("\tIndexed = " + indexed); if (table8 != null) { int len0 = table8.length; int len1 = table8[0].length; LogTools.print(" (8-bit LUT: " + table8.length + " x "); LogTools.print(table8[0] == null ? "null" : "" + table8[0].length); LogTools.print(")"); } if (table16 != null) { int len0 = table16.length; int len1 = table16[0].length; LogTools.print(" (16-bit LUT: " + table16.length + " x "); LogTools.print(table16[0] == null ? "null" : "" + table16[0].length); LogTools.print(")"); } LogTools.println(); if (indexed && table8 == null && table16 == null) { LogTools.println("\t************ Warning: no LUT ************"); } if (table8 != null && table16 != null) { LogTools.println( "\t************ Warning: multiple LUTs ************"); } LogTools.println("\tWidth = " + sizeX); LogTools.println("\tHeight = " + sizeY); LogTools.println("\tSizeZ = " + sizeZ); LogTools.println("\tSizeT = " + sizeT); LogTools.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { LogTools.print(" (effectively " + effSizeC + ")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { LogTools.print(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) LogTools.print(" x "); LogTools.print(cLengths[i] + " " + cTypes[i]); cProduct *= cLengths[i]; } LogTools.print(")"); } LogTools.println(); if (cLengths.length == 0 || cProduct != sizeC) { LogTools.println( "\t************ Warning: C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LogTools.println("\t************ Warning: ZCT mismatch ************"); } LogTools.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); LogTools.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); LogTools.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); LogTools.println("\tPixel type = " + FormatTools.getPixelTypeString(pixelType)); LogTools.println("\tMetadata complete = " + metadataComplete); LogTools.println("\tThumbnail series = " + thumbnail); if (doMeta) { LogTools.println("\t-----"); int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { LogTools.println(" [mismatch: " + indices2[i] + "]"); } else LogTools.println(); } } } reader.setSeries(series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(); int sizeC = reader.getSizeC(); // get a priori min/max values Double[] preGlobalMin = null, preGlobalMax = null; Double[] preKnownMin = null, preKnownMax = null; Double[] prePlaneMin = null, prePlaneMax = null; boolean preIsMinMaxPop = false; if (minmax) { preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } // read pixels if (pixels) { LogTools.println(); LogTools.print("Reading" + s + " pixel data "); status.setVerbose(false); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; if (width == 0) width = reader.getSizeX(); if (height == 0) height = reader.getSizeY(); LogTools.print("(" + start + "-" + end + ") "); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { status.setEchoNext(true); if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(i) : reader.openImage(i, xCoordinate, yCoordinate, width, height); } else { int x = reader.getSizeX(); int y = reader.getSizeY(); byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(reader.getPixelType()), reader.getPixelType() == FormatTools.FLOAT, reader.isLittleEndian()); images[i - start] = AWTImageTools.makeImage( ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = AWTImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { if (!mismatch) { LogTools.println(); mismatch = true; } LogTools.println("\tPlane #" + i + ": pixel type mismatch: " + FormatTools.getPixelTypeString(pixType) + "/" + FormatTools.getPixelTypeString(pixelType)); } else { mismatch = false; LogTools.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) LogTools.print(" "); LogTools.println("[done]"); // output timing results float sec2 = (e2 - s2) / 1000f; float avg = (float) (e2 - s2) / images.length; LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)"); if (minmax) { // get computed min/max values Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LogTools.println(); LogTools.println("Min/max values:"); for (int c=0; c<sizeC; c++) { LogTools.println("\tChannel " + c + ":"); LogTools.println("\t\tGlobal minimum = " + globalMin[c] + " (initially " + preGlobalMin[c] + ")"); LogTools.println("\t\tGlobal maximum = " + globalMax[c] + " (initially " + preGlobalMax[c] + ")"); LogTools.println("\t\tKnown minimum = " + knownMin[c] + " (initially " + preKnownMin[c] + ")"); LogTools.println("\t\tKnown maximum = " + knownMax[c] + " (initially " + preKnownMax[c] + ")"); } LogTools.print("\tFirst plane minimum(s) ="); if (planeMin == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { LogTools.print(" " + planeMin[subC]); } } LogTools.print(" (initially"); if (prePlaneMin == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { LogTools.print(" " + prePlaneMin[subC]); } } LogTools.println(")"); LogTools.print("\tFirst plane maximum(s) ="); if (planeMax == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { LogTools.print(" " + planeMax[subC]); } } LogTools.print(" (initially"); if (prePlaneMax == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { LogTools.print(" " + prePlaneMax[subC]); } } LogTools.println(")"); LogTools.println("\tMin/max populated = " + isMinMaxPop + " (initially " + preIsMinMaxPop + ")"); } // display pixels in image viewer // NB: avoid dependencies on optional loci.formats.gui package LogTools.println(); LogTools.println("Launching image viewer"); ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.gui.ImageViewer"); r.exec("viewer = new ImageViewer()"); r.setVar("reader", reader); r.setVar("images", images); r.setVar("true", true); r.exec("viewer.setImages(reader, images)"); r.exec("viewer.setVisible(true)"); } catch (ReflectException exc) { throw new FormatException(exc); } } // read format-specific metadata table if (doMeta) { LogTools.println(); LogTools.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { LogTools.print(keys[i] + ": "); LogTools.println(reader.getMetadataValue(keys[i])); } } // output and validate OME-XML if (omexml) { LogTools.println(); String version = MetadataTools.getOMEXMLVersion(ms); if (version == null) LogTools.println("Generating OME-XML"); else { LogTools.println("Generating OME-XML (schema version " + version + ")"); } if (MetadataTools.isOMEXMLMetadata(ms)) { String xml = MetadataTools.getOMEXML((MetadataRetrieve) ms); LogTools.println(XMLTools.indentXML(xml)); MetadataTools.validateOMEXML(xml); } else { LogTools.println("The metadata could not be converted to OME-XML."); if (omexmlVersion == null) { - LogTools.println("The OME-Java library is probably not available."); + LogTools.println( + "The OME-XML Java library is probably not available."); } else { LogTools.println(omexmlVersion + " is probably not a legal schema version."); } } } return true; } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { if (!testRead(args)) System.exit(1); } // -- Helper classes -- /** Used by testRead to echo status messages to the console. */ private static class StatusEchoer implements StatusListener { private boolean verbose = true; private boolean next = true; public void setVerbose(boolean value) { verbose = value; } public void setEchoNext(boolean value) { next = value; } public void statusUpdated(StatusEvent e) { if (verbose) LogTools.println("\t" + e.getStatusMessage()); else if (next) { LogTools.print(";"); next = false; } } } }
true
true
public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean minmax = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean expand = false; boolean omexml = false; boolean normalize = false; boolean fastBlit = false; boolean preload = false; String omexmlVersion = null; int start = 0; int end = Integer.MAX_VALUE; int series = 0; int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; String swapOrder = null, shuffleOrder = null; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatHandler.setDebug(true); else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-version")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-level")) { try { FormatHandler.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-shuffle")) { shuffleOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else LogTools.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else LogTools.println("Ignoring unknown argument: " + args[i]); } } } if (FormatHandler.debug) { LogTools.println("Debugging at level " + FormatHandler.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf file [-nopix] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap inputOrder] [-shuffle outputOrder] [-map id] [-preload]", " [-version v] [-crop x,y,w,h]", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default input dimension order", " -shuffle: override the default output dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -version: specify which OME-XML version should be generated", " -crop: crop images before displaying; argument is 'x,y,w,h'", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LogTools.println(s[i]); return false; } if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessStream f = new RandomAccessStream(id); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); RABytes file = new RABytes(b); Location.mapFile(id, file); } if (omexml) { reader.setOriginalMetadataPopulated(true); MetadataStore store = MetadataTools.createOMEXMLMetadata(null, omexmlVersion); if (store != null) reader.setMetadataStore(store); } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; LogTools.print("Checking file format "); LogTools.println("[" + ir.getFormat(id) + "]"); } else { // verify format LogTools.print("Checking " + reader.getFormat() + " format "); LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]"); } LogTools.println("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); MinMaxCalculator minMaxCalc = null; if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader); DimensionSwapper dimSwapper = null; if (swapOrder != null || shuffleOrder != null) { reader = dimSwapper = new DimensionSwapper(reader); } StatusEchoer status = new StatusEchoer(); reader.addStatusListener(status); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(true); reader.setMetadataCollected(doMeta); long s1 = System.currentTimeMillis(); reader.setId(id); long e1 = System.currentTimeMillis(); float sec1 = (e1 - s1) / 1000f; LogTools.println("Initialization took " + sec1 + "s"); if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (shuffleOrder != null) dimSwapper.setOutputOrder(shuffleOrder); if (!normalize && (reader.getPixelType() == FormatTools.FLOAT || reader.getPixelType() == FormatTools.DOUBLE)) { LogTools.println("Warning: Java does not support " + "display of unnormalized floating point data."); LogTools.println("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } if (reader.isRGB() && reader.getRGBChannelCount() > 4) { LogTools.println("Warning: Java does not support " + "merging more than 4 channels."); LogTools.println("Please use the '-separate' option " + "to avoid receiving a cryptic exception."); } // read basic metadata LogTools.println(); LogTools.println("Reading core metadata"); LogTools.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) LogTools.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LogTools.println( "************ Warning: invalid used files list ************"); } if (used == null) { LogTools.println("Used files = null"); } else if (used.length == 0) { LogTools.println("Used files = []"); } else if (used.length > 1) { LogTools.println("Used files:"); for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]); } else if (!id.equals(used[0])) { LogTools.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(); LogTools.println("Series count = " + seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series #i int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean thumbnail = reader.isThumbnailSeries(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series #i String seriesName = mr == null ? null : mr.getImageName(j); LogTools.println("Series #" + j + (seriesName == null ? "" : " -- " + seriesName) + ":"); LogTools.println("\tImage count = " + imageCount); LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) LogTools.print(" (merged)"); else if (separate) LogTools.print(" (separated)"); LogTools.println(); if (rgb != (rgbChanCount != 1)) { LogTools.println("\t************ Warning: RGB mismatch ************"); } LogTools.println("\tInterleaved = " + interleaved); LogTools.print("\tIndexed = " + indexed); if (table8 != null) { int len0 = table8.length; int len1 = table8[0].length; LogTools.print(" (8-bit LUT: " + table8.length + " x "); LogTools.print(table8[0] == null ? "null" : "" + table8[0].length); LogTools.print(")"); } if (table16 != null) { int len0 = table16.length; int len1 = table16[0].length; LogTools.print(" (16-bit LUT: " + table16.length + " x "); LogTools.print(table16[0] == null ? "null" : "" + table16[0].length); LogTools.print(")"); } LogTools.println(); if (indexed && table8 == null && table16 == null) { LogTools.println("\t************ Warning: no LUT ************"); } if (table8 != null && table16 != null) { LogTools.println( "\t************ Warning: multiple LUTs ************"); } LogTools.println("\tWidth = " + sizeX); LogTools.println("\tHeight = " + sizeY); LogTools.println("\tSizeZ = " + sizeZ); LogTools.println("\tSizeT = " + sizeT); LogTools.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { LogTools.print(" (effectively " + effSizeC + ")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { LogTools.print(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) LogTools.print(" x "); LogTools.print(cLengths[i] + " " + cTypes[i]); cProduct *= cLengths[i]; } LogTools.print(")"); } LogTools.println(); if (cLengths.length == 0 || cProduct != sizeC) { LogTools.println( "\t************ Warning: C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LogTools.println("\t************ Warning: ZCT mismatch ************"); } LogTools.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); LogTools.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); LogTools.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); LogTools.println("\tPixel type = " + FormatTools.getPixelTypeString(pixelType)); LogTools.println("\tMetadata complete = " + metadataComplete); LogTools.println("\tThumbnail series = " + thumbnail); if (doMeta) { LogTools.println("\t-----"); int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { LogTools.println(" [mismatch: " + indices2[i] + "]"); } else LogTools.println(); } } } reader.setSeries(series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(); int sizeC = reader.getSizeC(); // get a priori min/max values Double[] preGlobalMin = null, preGlobalMax = null; Double[] preKnownMin = null, preKnownMax = null; Double[] prePlaneMin = null, prePlaneMax = null; boolean preIsMinMaxPop = false; if (minmax) { preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } // read pixels if (pixels) { LogTools.println(); LogTools.print("Reading" + s + " pixel data "); status.setVerbose(false); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; if (width == 0) width = reader.getSizeX(); if (height == 0) height = reader.getSizeY(); LogTools.print("(" + start + "-" + end + ") "); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { status.setEchoNext(true); if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(i) : reader.openImage(i, xCoordinate, yCoordinate, width, height); } else { int x = reader.getSizeX(); int y = reader.getSizeY(); byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(reader.getPixelType()), reader.getPixelType() == FormatTools.FLOAT, reader.isLittleEndian()); images[i - start] = AWTImageTools.makeImage( ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = AWTImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { if (!mismatch) { LogTools.println(); mismatch = true; } LogTools.println("\tPlane #" + i + ": pixel type mismatch: " + FormatTools.getPixelTypeString(pixType) + "/" + FormatTools.getPixelTypeString(pixelType)); } else { mismatch = false; LogTools.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) LogTools.print(" "); LogTools.println("[done]"); // output timing results float sec2 = (e2 - s2) / 1000f; float avg = (float) (e2 - s2) / images.length; LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)"); if (minmax) { // get computed min/max values Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LogTools.println(); LogTools.println("Min/max values:"); for (int c=0; c<sizeC; c++) { LogTools.println("\tChannel " + c + ":"); LogTools.println("\t\tGlobal minimum = " + globalMin[c] + " (initially " + preGlobalMin[c] + ")"); LogTools.println("\t\tGlobal maximum = " + globalMax[c] + " (initially " + preGlobalMax[c] + ")"); LogTools.println("\t\tKnown minimum = " + knownMin[c] + " (initially " + preKnownMin[c] + ")"); LogTools.println("\t\tKnown maximum = " + knownMax[c] + " (initially " + preKnownMax[c] + ")"); } LogTools.print("\tFirst plane minimum(s) ="); if (planeMin == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { LogTools.print(" " + planeMin[subC]); } } LogTools.print(" (initially"); if (prePlaneMin == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { LogTools.print(" " + prePlaneMin[subC]); } } LogTools.println(")"); LogTools.print("\tFirst plane maximum(s) ="); if (planeMax == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { LogTools.print(" " + planeMax[subC]); } } LogTools.print(" (initially"); if (prePlaneMax == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { LogTools.print(" " + prePlaneMax[subC]); } } LogTools.println(")"); LogTools.println("\tMin/max populated = " + isMinMaxPop + " (initially " + preIsMinMaxPop + ")"); } // display pixels in image viewer // NB: avoid dependencies on optional loci.formats.gui package LogTools.println(); LogTools.println("Launching image viewer"); ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.gui.ImageViewer"); r.exec("viewer = new ImageViewer()"); r.setVar("reader", reader); r.setVar("images", images); r.setVar("true", true); r.exec("viewer.setImages(reader, images)"); r.exec("viewer.setVisible(true)"); } catch (ReflectException exc) { throw new FormatException(exc); } } // read format-specific metadata table if (doMeta) { LogTools.println(); LogTools.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { LogTools.print(keys[i] + ": "); LogTools.println(reader.getMetadataValue(keys[i])); } } // output and validate OME-XML if (omexml) { LogTools.println(); String version = MetadataTools.getOMEXMLVersion(ms); if (version == null) LogTools.println("Generating OME-XML"); else { LogTools.println("Generating OME-XML (schema version " + version + ")"); } if (MetadataTools.isOMEXMLMetadata(ms)) { String xml = MetadataTools.getOMEXML((MetadataRetrieve) ms); LogTools.println(XMLTools.indentXML(xml)); MetadataTools.validateOMEXML(xml); } else { LogTools.println("The metadata could not be converted to OME-XML."); if (omexmlVersion == null) { LogTools.println("The OME-Java library is probably not available."); } else { LogTools.println(omexmlVersion + " is probably not a legal schema version."); } } } return true; }
public static boolean testRead(IFormatReader reader, String[] args) throws FormatException, IOException { String id = null; boolean pixels = true; boolean doMeta = true; boolean thumbs = false; boolean minmax = false; boolean merge = false; boolean stitch = false; boolean separate = false; boolean expand = false; boolean omexml = false; boolean normalize = false; boolean fastBlit = false; boolean preload = false; String omexmlVersion = null; int start = 0; int end = Integer.MAX_VALUE; int series = 0; int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; String swapOrder = null, shuffleOrder = null; String map = null; if (args != null) { for (int i=0; i<args.length; i++) { if (args[i].startsWith("-") && args.length > 1) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-debug")) FormatHandler.setDebug(true); else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-version")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-level")) { try { FormatHandler.setDebugLevel(Integer.parseInt(args[++i])); } catch (NumberFormatException exc) { } } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-shuffle")) { shuffleOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else LogTools.println("Ignoring unknown command flag: " + args[i]); } else { if (id == null) id = args[i]; else LogTools.println("Ignoring unknown argument: " + args[i]); } } } if (FormatHandler.debug) { LogTools.println("Debugging at level " + FormatHandler.debugLevel); } if (id == null) { String className = reader.getClass().getName(); String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf file [-nopix] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap inputOrder] [-shuffle outputOrder] [-map id] [-preload]", " [-version v] [-crop x,y,w,h]", "", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nometa: output only core metadata", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", "-normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default input dimension order", " -shuffle: override the default output dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -version: specify which OME-XML version should be generated", " -crop: crop images before displaying; argument is 'x,y,w,h'", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LogTools.println(s[i]); return false; } if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessStream f = new RandomAccessStream(id); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); RABytes file = new RABytes(b); Location.mapFile(id, file); } if (omexml) { reader.setOriginalMetadataPopulated(true); MetadataStore store = MetadataTools.createOMEXMLMetadata(null, omexmlVersion); if (store != null) reader.setMetadataStore(store); } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; LogTools.print("Checking file format "); LogTools.println("[" + ir.getFormat(id) + "]"); } else { // verify format LogTools.print("Checking " + reader.getFormat() + " format "); LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]"); } LogTools.println("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); String pat = FilePattern.findPattern(new Location(id)); if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); MinMaxCalculator minMaxCalc = null; if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader); DimensionSwapper dimSwapper = null; if (swapOrder != null || shuffleOrder != null) { reader = dimSwapper = new DimensionSwapper(reader); } StatusEchoer status = new StatusEchoer(); reader.addStatusListener(status); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(true); reader.setMetadataCollected(doMeta); long s1 = System.currentTimeMillis(); reader.setId(id); long e1 = System.currentTimeMillis(); float sec1 = (e1 - s1) / 1000f; LogTools.println("Initialization took " + sec1 + "s"); if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (shuffleOrder != null) dimSwapper.setOutputOrder(shuffleOrder); if (!normalize && (reader.getPixelType() == FormatTools.FLOAT || reader.getPixelType() == FormatTools.DOUBLE)) { LogTools.println("Warning: Java does not support " + "display of unnormalized floating point data."); LogTools.println("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } if (reader.isRGB() && reader.getRGBChannelCount() > 4) { LogTools.println("Warning: Java does not support " + "merging more than 4 channels."); LogTools.println("Please use the '-separate' option " + "to avoid receiving a cryptic exception."); } // read basic metadata LogTools.println(); LogTools.println("Reading core metadata"); LogTools.println(stitch ? "File pattern = " + id : "Filename = " + reader.getCurrentFile()); if (map != null) LogTools.println("Mapped filename = " + map); String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LogTools.println( "************ Warning: invalid used files list ************"); } if (used == null) { LogTools.println("Used files = null"); } else if (used.length == 0) { LogTools.println("Used files = []"); } else if (used.length > 1) { LogTools.println("Used files:"); for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]); } else if (!id.equals(used[0])) { LogTools.println("Used files = [" + used[0] + "]"); } int seriesCount = reader.getSeriesCount(); LogTools.println("Series count = " + seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series #i int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean thumbnail = reader.isThumbnailSeries(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series #i String seriesName = mr == null ? null : mr.getImageName(j); LogTools.println("Series #" + j + (seriesName == null ? "" : " -- " + seriesName) + ":"); LogTools.println("\tImage count = " + imageCount); LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")"); if (merge) LogTools.print(" (merged)"); else if (separate) LogTools.print(" (separated)"); LogTools.println(); if (rgb != (rgbChanCount != 1)) { LogTools.println("\t************ Warning: RGB mismatch ************"); } LogTools.println("\tInterleaved = " + interleaved); LogTools.print("\tIndexed = " + indexed); if (table8 != null) { int len0 = table8.length; int len1 = table8[0].length; LogTools.print(" (8-bit LUT: " + table8.length + " x "); LogTools.print(table8[0] == null ? "null" : "" + table8[0].length); LogTools.print(")"); } if (table16 != null) { int len0 = table16.length; int len1 = table16[0].length; LogTools.print(" (16-bit LUT: " + table16.length + " x "); LogTools.print(table16[0] == null ? "null" : "" + table16[0].length); LogTools.print(")"); } LogTools.println(); if (indexed && table8 == null && table16 == null) { LogTools.println("\t************ Warning: no LUT ************"); } if (table8 != null && table16 != null) { LogTools.println( "\t************ Warning: multiple LUTs ************"); } LogTools.println("\tWidth = " + sizeX); LogTools.println("\tHeight = " + sizeY); LogTools.println("\tSizeZ = " + sizeZ); LogTools.println("\tSizeT = " + sizeT); LogTools.print("\tSizeC = " + sizeC); if (sizeC != effSizeC) { LogTools.print(" (effectively " + effSizeC + ")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { LogTools.print(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) LogTools.print(" x "); LogTools.print(cLengths[i] + " " + cTypes[i]); cProduct *= cLengths[i]; } LogTools.print(")"); } LogTools.println(); if (cLengths.length == 0 || cProduct != sizeC) { LogTools.println( "\t************ Warning: C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LogTools.println("\t************ Warning: ZCT mismatch ************"); } LogTools.println("\tThumbnail size = " + thumbSizeX + " x " + thumbSizeY); LogTools.println("\tEndianness = " + (little ? "intel (little)" : "motorola (big)")); LogTools.println("\tDimension order = " + dimOrder + (orderCertain ? " (certain)" : " (uncertain)")); LogTools.println("\tPixel type = " + FormatTools.getPixelTypeString(pixelType)); LogTools.println("\tMetadata complete = " + metadataComplete); LogTools.println("\tThumbnail series = " + thumbnail); if (doMeta) { LogTools.println("\t-----"); int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] + ", C " + zct[i][1] + ", T " + zct[i][2]); if (indices[i] != indices2[i]) { LogTools.println(" [mismatch: " + indices2[i] + "]"); } else LogTools.println(); } } } reader.setSeries(series); String s = seriesCount > 1 ? (" series #" + series) : ""; int pixelType = reader.getPixelType(); int sizeC = reader.getSizeC(); // get a priori min/max values Double[] preGlobalMin = null, preGlobalMax = null; Double[] preKnownMin = null, preKnownMax = null; Double[] prePlaneMin = null, prePlaneMax = null; boolean preIsMinMaxPop = false; if (minmax) { preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } // read pixels if (pixels) { LogTools.println(); LogTools.print("Reading" + s + " pixel data "); status.setVerbose(false); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; if (width == 0) width = reader.getSizeX(); if (height == 0) height = reader.getSizeY(); LogTools.print("(" + start + "-" + end + ") "); BufferedImage[] images = new BufferedImage[end - start + 1]; long s2 = System.currentTimeMillis(); boolean mismatch = false; for (int i=start; i<=end; i++) { status.setEchoNext(true); if (!fastBlit) { images[i - start] = thumbs ? reader.openThumbImage(i) : reader.openImage(i, xCoordinate, yCoordinate, width, height); } else { int x = reader.getSizeX(); int y = reader.getSizeY(); byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(reader.getPixelType()), reader.getPixelType() == FormatTools.FLOAT, reader.isLittleEndian()); images[i - start] = AWTImageTools.makeImage( ImageTools.make24Bits(pix, x, y, false, false), x, y); } // check for pixel type mismatch int pixType = AWTImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { if (!mismatch) { LogTools.println(); mismatch = true; } LogTools.println("\tPlane #" + i + ": pixel type mismatch: " + FormatTools.getPixelTypeString(pixType) + "/" + FormatTools.getPixelTypeString(pixelType)); } else { mismatch = false; LogTools.print("."); } } long e2 = System.currentTimeMillis(); if (!mismatch) LogTools.print(" "); LogTools.println("[done]"); // output timing results float sec2 = (e2 - s2) / 1000f; float avg = (float) (e2 - s2) / images.length; LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)"); if (minmax) { // get computed min/max values Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LogTools.println(); LogTools.println("Min/max values:"); for (int c=0; c<sizeC; c++) { LogTools.println("\tChannel " + c + ":"); LogTools.println("\t\tGlobal minimum = " + globalMin[c] + " (initially " + preGlobalMin[c] + ")"); LogTools.println("\t\tGlobal maximum = " + globalMax[c] + " (initially " + preGlobalMax[c] + ")"); LogTools.println("\t\tKnown minimum = " + knownMin[c] + " (initially " + preKnownMin[c] + ")"); LogTools.println("\t\tKnown maximum = " + knownMax[c] + " (initially " + preKnownMax[c] + ")"); } LogTools.print("\tFirst plane minimum(s) ="); if (planeMin == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { LogTools.print(" " + planeMin[subC]); } } LogTools.print(" (initially"); if (prePlaneMin == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { LogTools.print(" " + prePlaneMin[subC]); } } LogTools.println(")"); LogTools.print("\tFirst plane maximum(s) ="); if (planeMax == null) LogTools.print(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { LogTools.print(" " + planeMax[subC]); } } LogTools.print(" (initially"); if (prePlaneMax == null) LogTools.print(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { LogTools.print(" " + prePlaneMax[subC]); } } LogTools.println(")"); LogTools.println("\tMin/max populated = " + isMinMaxPop + " (initially " + preIsMinMaxPop + ")"); } // display pixels in image viewer // NB: avoid dependencies on optional loci.formats.gui package LogTools.println(); LogTools.println("Launching image viewer"); ReflectedUniverse r = new ReflectedUniverse(); try { r.exec("import loci.formats.gui.ImageViewer"); r.exec("viewer = new ImageViewer()"); r.setVar("reader", reader); r.setVar("images", images); r.setVar("true", true); r.exec("viewer.setImages(reader, images)"); r.exec("viewer.setVisible(true)"); } catch (ReflectException exc) { throw new FormatException(exc); } } // read format-specific metadata table if (doMeta) { LogTools.println(); LogTools.println("Reading" + s + " metadata"); Hashtable meta = reader.getMetadata(); String[] keys = (String[]) meta.keySet().toArray(new String[0]); Arrays.sort(keys); for (int i=0; i<keys.length; i++) { LogTools.print(keys[i] + ": "); LogTools.println(reader.getMetadataValue(keys[i])); } } // output and validate OME-XML if (omexml) { LogTools.println(); String version = MetadataTools.getOMEXMLVersion(ms); if (version == null) LogTools.println("Generating OME-XML"); else { LogTools.println("Generating OME-XML (schema version " + version + ")"); } if (MetadataTools.isOMEXMLMetadata(ms)) { String xml = MetadataTools.getOMEXML((MetadataRetrieve) ms); LogTools.println(XMLTools.indentXML(xml)); MetadataTools.validateOMEXML(xml); } else { LogTools.println("The metadata could not be converted to OME-XML."); if (omexmlVersion == null) { LogTools.println( "The OME-XML Java library is probably not available."); } else { LogTools.println(omexmlVersion + " is probably not a legal schema version."); } } } return true; }
diff --git a/src/uk/ac/man/cs/mig/util/graph/layout/dotlayoutengine/DotProcess.java b/src/uk/ac/man/cs/mig/util/graph/layout/dotlayoutengine/DotProcess.java index c46960a..b8aa492 100644 --- a/src/uk/ac/man/cs/mig/util/graph/layout/dotlayoutengine/DotProcess.java +++ b/src/uk/ac/man/cs/mig/util/graph/layout/dotlayoutengine/DotProcess.java @@ -1,99 +1,102 @@ package uk.ac.man.cs.mig.util.graph.layout.dotlayoutengine; import javax.swing.*; import java.io.IOException; /** * User: matthewhorridge<br> * The Univeristy Of Manchester<br> * Medical Informatics Group<br> * Date: Jan 16, 2004<br><br> * <p/> * [email protected]<br> * www.cs.man.ac.uk/~horridgm<br><br> * <p/> * A wrapper for a native dot process. */ public class DotProcess { private Process process; /** * Contructs a <code>DotProcess</code>, and starts * the native dot process. Using the default process * path for the particular platfrom being used. */ public DotProcess() { } /** * Lays out a graph using the dot application * * @param fileName A file that acts as a 'scratch pad' * The graph is read from this file, and then export * to the same file in attributed dot format. * @return <code>true</code> if the process completed without * any errors, or <code>false</code> if the process did not * complete. */ public boolean startProcess(String fileName) { if(process != null) { killProcess(); } Runtime r = Runtime.getRuntime(); DotLayoutEngineProperties properties = DotLayoutEngineProperties.getInstance(); try { process = r.exec(properties.getDotProcessPath() + " " + fileName + " -q -o " + fileName); try { process.waitFor(); return true; } catch(InterruptedException irEx) { irEx.printStackTrace(); return false; } } catch(IOException ioEx) { String errMsg = "An error related to DOT has occurred. " + "This error was probably because OWLViz could not" + " find the DOT application. Please ensure that the" + " path to the DOT application is set properly"; - String dlgErrMsg = "<html><body>An error related to DOT has occurred.<br>" + "This error was probably because OWLViz could not<br>" + " find the DOT application. Please ensure that the<br>" + " path to the DOT application is set properly</body></html>"; + String dlgErrMsg = "<html><body>A DOT error has occurred.<br>" + + "This is probably because OWLViz could not find the DOT application.<br>" + + "OWLViz requires that Graphviz (http://www.graphviz.org/) is installed<br>" + + " and the path to the DOT application is set properly (in options).</body></html>"; JOptionPane.showMessageDialog(null, dlgErrMsg, "DOT Error", JOptionPane.ERROR_MESSAGE); // Display on stderr System.out.println("DOT Process Error:"); System.out.println(ioEx.getMessage()); System.out.println(errMsg); return false; // Display a dialog //ioEx.printStackTrace(); } } /** * Kills the native dot process (if it was started * successfully). */ protected void killProcess() { if(process != null) { process.destroy(); process = null; } } }
true
true
public boolean startProcess(String fileName) { if(process != null) { killProcess(); } Runtime r = Runtime.getRuntime(); DotLayoutEngineProperties properties = DotLayoutEngineProperties.getInstance(); try { process = r.exec(properties.getDotProcessPath() + " " + fileName + " -q -o " + fileName); try { process.waitFor(); return true; } catch(InterruptedException irEx) { irEx.printStackTrace(); return false; } } catch(IOException ioEx) { String errMsg = "An error related to DOT has occurred. " + "This error was probably because OWLViz could not" + " find the DOT application. Please ensure that the" + " path to the DOT application is set properly"; String dlgErrMsg = "<html><body>An error related to DOT has occurred.<br>" + "This error was probably because OWLViz could not<br>" + " find the DOT application. Please ensure that the<br>" + " path to the DOT application is set properly</body></html>"; JOptionPane.showMessageDialog(null, dlgErrMsg, "DOT Error", JOptionPane.ERROR_MESSAGE); // Display on stderr System.out.println("DOT Process Error:"); System.out.println(ioEx.getMessage()); System.out.println(errMsg); return false; // Display a dialog //ioEx.printStackTrace(); } }
public boolean startProcess(String fileName) { if(process != null) { killProcess(); } Runtime r = Runtime.getRuntime(); DotLayoutEngineProperties properties = DotLayoutEngineProperties.getInstance(); try { process = r.exec(properties.getDotProcessPath() + " " + fileName + " -q -o " + fileName); try { process.waitFor(); return true; } catch(InterruptedException irEx) { irEx.printStackTrace(); return false; } } catch(IOException ioEx) { String errMsg = "An error related to DOT has occurred. " + "This error was probably because OWLViz could not" + " find the DOT application. Please ensure that the" + " path to the DOT application is set properly"; String dlgErrMsg = "<html><body>A DOT error has occurred.<br>" + "This is probably because OWLViz could not find the DOT application.<br>" + "OWLViz requires that Graphviz (http://www.graphviz.org/) is installed<br>" + " and the path to the DOT application is set properly (in options).</body></html>"; JOptionPane.showMessageDialog(null, dlgErrMsg, "DOT Error", JOptionPane.ERROR_MESSAGE); // Display on stderr System.out.println("DOT Process Error:"); System.out.println(ioEx.getMessage()); System.out.println(errMsg); return false; // Display a dialog //ioEx.printStackTrace(); } }