answer
stringlengths
17
10.2M
package org.hisp.dhis.android.dashboard.ui.fragments.dashboard; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import org.hisp.dhis.android.dashboard.DhisService; import org.hisp.dhis.android.dashboard.R; import org.hisp.dhis.android.dashboard.ui.activities.DashboardElementDetailActivity; import org.hisp.dhis.android.dashboard.ui.adapters.DashboardItemAdapter; import org.hisp.dhis.android.dashboard.ui.events.UiEvent; import org.hisp.dhis.android.dashboard.ui.fragments.BaseFragment; import org.hisp.dhis.android.dashboard.ui.fragments.interpretation.InterpretationCreateFragment; import org.hisp.dhis.android.dashboard.ui.views.GridDividerDecoration; import org.hisp.dhis.android.dashboard.utils.EventBusProvider; import org.hisp.dhis.android.sdk.core.api.Dhis2; import org.hisp.dhis.android.sdk.core.persistence.loaders.DbLoader; import org.hisp.dhis.android.sdk.core.persistence.loaders.Query; import org.hisp.dhis.android.sdk.core.persistence.loaders.TrackedTable; import org.hisp.dhis.android.sdk.models.common.Access; import org.hisp.dhis.android.sdk.models.dashboard.Dashboard; import org.hisp.dhis.android.sdk.models.dashboard.DashboardElement; import org.hisp.dhis.android.sdk.models.dashboard.DashboardItem; import org.hisp.dhis.android.sdk.models.dashboard.DashboardItemContent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DashboardFragment extends BaseFragment implements LoaderManager.LoaderCallbacks<List<DashboardItem>>, DashboardItemAdapter.OnItemClickListener { private static final int LOADER_ID = 74734523; private static final String DASHBOARD_ID = "arg:dashboardId"; private static final String DELETE = "arg:delete"; private static final String UPDATE = "arg:update"; private static final String READ = "arg:read"; private static final String WRITE = "arg:write"; private static final String MANAGE = "arg:manage"; private static final String EXTERNALIZE = "arg:externalize"; RecyclerView mRecyclerView; DashboardItemAdapter mAdapter; public static DashboardFragment newInstance(Dashboard dashboard) { DashboardFragment fragment = new DashboardFragment(); Access access = dashboard.getAccess(); Bundle args = new Bundle(); args.putLong(DASHBOARD_ID, dashboard.getId()); args.putBoolean(DELETE, access.isDelete()); args.putBoolean(UPDATE, access.isUpdate()); args.putBoolean(READ, access.isRead()); args.putBoolean(WRITE, access.isWrite()); args.putBoolean(MANAGE, access.isManage()); args.putBoolean(EXTERNALIZE, access.isExternalize()); fragment.setArguments(args); return fragment; } private static Access getAccessFromBundle(Bundle args) { Access access = new Access(); access.setDelete(args.getBoolean(DELETE)); access.setUpdate(args.getBoolean(UPDATE)); access.setRead(args.getBoolean(READ)); access.setWrite(args.getBoolean(WRITE)); access.setManage(args.getBoolean(MANAGE)); access.setExternalize(args.getBoolean(EXTERNALIZE)); return access; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle bundle) { return inflater.inflate(R.layout.recycler_view, group, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { mRecyclerView = (RecyclerView) view; final int spanCount = getResources().getInteger(R.integer.column_nums); mAdapter = new DashboardItemAdapter(getActivity(), getAccessFromBundle(getArguments()), spanCount, this); GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), spanCount); gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL); gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return mAdapter.getSpanSize(position); } }); mRecyclerView.setLayoutManager(gridLayoutManager); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.addItemDecoration(new GridDividerDecoration(getActivity() .getApplicationContext())); mRecyclerView.setAdapter(mAdapter); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getLoaderManager().initLoader(LOADER_ID, getArguments(), this); } @Override public Loader<List<DashboardItem>> onCreateLoader(int id, Bundle args) { if (id == LOADER_ID && isAdded()) { /* When two tables are joined sometimes we can get empty rows. For example dashboard does not contain any dashboard items. In order to avoid strange bugs during table JOINs, we explicitly state that we want only not null values */ List<TrackedTable> trackedTables = Arrays.asList( new TrackedTable(DashboardItem.class), new TrackedTable(DashboardElement.class)); return new DbLoader<>(getActivity().getApplicationContext(), trackedTables, new ItemsQuery(args.getLong(DASHBOARD_ID))); } return null; } @Override public void onLoadFinished(Loader<List<DashboardItem>> loader, List<DashboardItem> dashboardItems) { if (loader.getId() == LOADER_ID) { mAdapter.swapData(dashboardItems); } } @Override public void onLoaderReset(Loader<List<DashboardItem>> loader) { if (loader.getId() == LOADER_ID) { mAdapter.swapData(null); } } @Override public void onContentClick(DashboardElement element) { switch (element.getDashboardItem().getType()) { case DashboardItemContent.TYPE_CHART: case DashboardItemContent.TYPE_EVENT_CHART: case DashboardItemContent.TYPE_MAP: case DashboardItemContent.TYPE_REPORT_TABLE: { Intent intent = DashboardElementDetailActivity .newIntentForDashboardElement(getActivity(), element.getId()); startActivity(intent); break; } default: { String message = getString(R.string.unsupported_dashboard_item_type); Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); } } } @Override public void onContentDeleteClick(DashboardElement element) { if (element != null) { Dhis2.dashboardElements().remove(element); DhisService.getInstance().syncDashboards(); EventBusProvider.post(new UiEvent(UiEvent.UiEventType.SYNC_DASHBOARDS)); } } @Override public void onItemDeleteClick(DashboardItem item) { if (item != null) { Dhis2.dashboardItems().remove(item); DhisService.getInstance().syncDashboards(); EventBusProvider.post(new UiEvent(UiEvent.UiEventType.SYNC_DASHBOARDS)); } } @Override public void onItemShareClick(DashboardItem item) { InterpretationCreateFragment .newInstance(item.getId()) .show(getChildFragmentManager()); } private static class ItemsQuery implements Query<List<DashboardItem>> { private final long mDashboardId; public ItemsQuery(long dashboardId) { mDashboardId = dashboardId; } @Override public List<DashboardItem> query(Context context) { Dashboard dashboard = new Dashboard(); dashboard.setId(mDashboardId); List<DashboardItem> dashboardItems = Dhis2.dashboardItems().list(dashboard); List<DashboardItem> filteredDashboardItems = new ArrayList<>(); if (dashboardItems != null && !dashboardItems.isEmpty()) { for (DashboardItem dashboardItem : dashboardItems) { if (!DashboardItemContent.TYPE_MESSAGES.equals(dashboardItem.getType()) && !DashboardItemContent.TYPE_EVENT_REPORT.equals(dashboardItem.getType())) { List<DashboardElement> dashboardElements = Dhis2 .dashboardElements().list(dashboardItem); dashboardItem.setDashboardElements(dashboardElements); filteredDashboardItems.add(dashboardItem); } } } return filteredDashboardItems; } } }
// 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, / // sell copies of the Software, and to permit persons to whom the / // Software is furnished to do so, subject to the following / // conditions: / // included in all copies or substantial portions of the Software. / // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES / // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND / // 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.asn1s.core.type.x680.collection; import org.asn1s.api.Scope; import org.asn1s.api.State; import org.asn1s.api.encoding.EncodingInstructions; import org.asn1s.api.encoding.tag.TagEncoding; import org.asn1s.api.encoding.tag.TagMethod; import org.asn1s.api.exception.ResolutionException; import org.asn1s.api.exception.ValidationException; import org.asn1s.api.type.CollectionTypeExtensionGroup; import org.asn1s.api.type.ComponentType; import org.asn1s.api.type.Type; import org.asn1s.api.type.Type.Family; import org.asn1s.core.type.TaggedTypeImpl; import org.jetbrains.annotations.NotNull; import java.util.*; abstract class AbstractComponentInterpolator { private final Scope scope; private final AbstractCollectionType type; private final boolean applyAutomaticTags; private final Map<String, Family> componentFamilyMap = new HashMap<>(); AbstractComponentInterpolator( Scope scope, AbstractCollectionType type ) { this.scope = scope; this.type = type; applyAutomaticTags = type.isAutomaticTags() && mayUseAutomaticTags( type ); } private static boolean mayUseAutomaticTags( @NotNull AbstractCollectionType collectionType ) { for( Type type : collectionType.getComponents() ) { if( type instanceof ComponentType && ( (ComponentType)type ).isExplicitlyTagged() ) return false; } for( Type type : collectionType.getComponentsLast() ) { if( type instanceof ComponentType && ( (ComponentType)type ).isExplicitlyTagged() ) return false; } return true; } protected abstract void assertTagAmbiguity( Collection<ComponentType> components ) throws ValidationException; private Scope getScope() { return scope; } AbstractCollectionType getType() { return type; } List<ComponentType> interpolate() throws ValidationException, ResolutionException { new CollectionValidator( getType() ).validate(); List<ComponentType> components = interpolateComponents(); assertTagAmbiguity( components ); return components; } @NotNull private List<ComponentType> interpolateComponents() throws ValidationException, ResolutionException { List<ComponentType> components = new ComponentsBuilder( getType(), componentFamilyMap ).build(); for( ComponentType component : components ) component.validate( getScope() ); return isApplyAutomaticTags() ? applyAutomaticTags( components ) : components; } @NotNull private List<ComponentType> applyAutomaticTags( @NotNull Collection<ComponentType> components ) throws ResolutionException, ValidationException { int tagNumber = 0; List<ComponentType> result = new ArrayList<>( components.size() ); for( ComponentType component : components ) { if( component.getVersion() == 1 ) { result.add( applyTagNumber( tagNumber, component ) ); tagNumber++; } } for( ComponentType component : components ) { if( component.getVersion() > 1 ) { result.add( applyTagNumber( tagNumber, component ) ); tagNumber++; } } result.sort( Comparator.comparingInt( ComponentType:: getIndex ) ); return result; } private ComponentType applyTagNumber( int tagNumber, ComponentType component ) throws ResolutionException, ValidationException { TagMethod method = componentFamilyMap.get( component.getComponentName() ) == Family.Choice && component.getEncoding( EncodingInstructions.Tag ) == null ? TagMethod.Explicit : TagMethod.Implicit; TaggedTypeImpl subType = new TaggedTypeImpl( TagEncoding.context( tagNumber, method ), component.getComponentTypeRef() ); subType.setNamespace( component.getNamespace() ); ComponentType taggedComponent = new ComponentTypeImpl( component.getIndex(), component.getVersion(), component.getComponentName(), subType, component.isOptional(), component.getDefaultValueRef() ); taggedComponent.setNamespace( component.getNamespace() ); taggedComponent.validate( getScope() ); return taggedComponent; } private boolean isApplyAutomaticTags() { return applyAutomaticTags; } private static final class ComponentsBuilder { private final AbstractCollectionType type; private final Map<String, Family> componentFamilyMap; @SuppressWarnings( "unchecked" ) // 0 - components, 1 - componentsLast, 2 - extensions private final Collection<ComponentType>[] _comps = new Collection[]{new ArrayList<ComponentType>(), new ArrayList<ComponentType>(), new ArrayList<ComponentType>()}; private final List<ComponentType> result = new ArrayList<>(); private int index; private ComponentsBuilder( AbstractCollectionType type, Map<String, Family> componentFamilyMap ) { this.type = type; this.componentFamilyMap = componentFamilyMap; } private List<ComponentType> build() throws ValidationException { resolveComponentsImpl( _comps[0], type.getComponents(), -1 ); resolveComponentsImpl( _comps[1], type.getComponentsLast(), -1 ); resolveComponentsImpl( _comps[2], type.getExtensions(), 2 ); registerComponents( _comps[0] ); registerComponents( _comps[2] ); registerComponents( _comps[1] ); return result; } private void registerComponents( Iterable<ComponentType> source ) { for( ComponentType component : source ) //noinspection ValueOfIncrementOrDecrementUsed addComponentType( result, component, component.getVersion(), index++ ); } private void resolveComponentsImpl( Collection<ComponentType> list, Iterable<Type> sources, int version ) throws ValidationException { if( version == -1 ) for( Type source : sources ) resolveComponentTypeSource( list, source, 1 ); else for( Type source : sources ) //noinspection ValueOfIncrementOrDecrementUsed resolveComponentTypeSource( list, source, version++ ); } private void resolveComponentTypeSource( Collection<ComponentType> list, Type source, int version ) throws ValidationException { if( source instanceof ComponentType ) addComponentType( list, (ComponentType)source, version, -1 ); else if( source instanceof ComponentsFromType ) resolveComponentTypeSourceForCompsFromType( list, (ComponentsFromType)source, version ); else if( source instanceof CollectionTypeExtensionGroup ) resolveComponentTypeSourceForExtGroup( list, (CollectionTypeExtensionGroup)source, version ); else throw new IllegalStateException( "Unable to use type: " + source ); } private void resolveComponentTypeSourceForExtGroup( Collection<ComponentType> list, CollectionTypeExtensionGroup source, int version ) throws ValidationException { int groupVersion = source.getVersion(); if( groupVersion != -1 ) { if( groupVersion < version ) throw new ValidationException( "Version must be greater than previous group" ); version = groupVersion; } for( ComponentType componentType : source.getComponents() ) addComponentType( list, componentType, version, -1 ); } private void resolveComponentTypeSourceForCompsFromType( Collection<ComponentType> list, ComponentsFromType source, int version ) { for( ComponentType componentType : source.getComponents() ) addComponentType( list, componentType, version, -1 ); } private void addComponentType( Collection<ComponentType> list, ComponentType source, int version, int index ) { if( source.getState() == State.Done ) componentFamilyMap.put( source.getComponentName(), source.getFamily() ); list.add( isShouldKeep( source, version, index ) ? source : createComponentType( source, version, index ) ); } private static boolean isShouldKeep( ComponentType source, int version, int index ) { return source.getVersion() == version && index != -1 && source.getIndex() == index; } @NotNull private ComponentType createComponentType( ComponentType source, int version, int index ) { ComponentType componentType = new ComponentTypeImpl( index == -1 ? source.getIndex() : index, version, source.getComponentName(), source.getComponentTypeRef(), source.isOptional(), source.getDefaultValueRef() ); componentType.setNamespace( type.getNamespace() ); return componentType; } } private static final class CollectionValidator { private final AbstractCollectionType type; private final Collection<String> names; private CollectionValidator( AbstractCollectionType type ) { this.type = type; names = new HashSet<>(); } public void validate() throws ValidationException { assertNames( type.getComponents(), names ); assertNames( type.getExtensions(), names ); assertNames( type.getComponentsLast(), names ); if( isExtensionVersionProhibited() ) assertExtensionGroupHasNoVersion(); else assertExtensionVersions(); } private static void assertNames( Iterable<Type> items, Collection<String> names ) throws ValidationException { for( Type item : items ) assertName( item, names ); } private static void assertName( Type item, Collection<String> names ) throws ValidationException { if( item instanceof ComponentType ) assertNameForComponentType( (ComponentType)item, names ); else if( item instanceof CollectionTypeExtensionGroup ) assertNameForExtensionGroup( (CollectionTypeExtensionGroup)item, names ); else if( item instanceof ComponentsFromType ) assertNameForComponentsFromType( (ComponentsFromType)item, names ); } private static void assertNameForComponentsFromType( ComponentsFromType item, Collection<String> names ) throws ValidationException { for( ComponentType componentType : item.getComponents() ) assertName( componentType, names ); } private static void assertNameForExtensionGroup( CollectionTypeExtensionGroup item, Collection<String> names ) throws ValidationException { for( ComponentType componentType : item.getComponents() ) assertName( componentType, names ); } private static void assertNameForComponentType( ComponentType item, Collection<String> names ) throws ValidationException { String componentName = item.getComponentName(); if( names.contains( componentName ) ) throw new ValidationException( "ComponentType with name '" + componentName + "' already exist" ); names.add( componentName ); } private void assertExtensionVersions() throws ValidationException { int prevVersion = 1; for( Type extension : type.getExtensions() ) { CollectionTypeExtensionGroup group = (CollectionTypeExtensionGroup)extension; if( prevVersion >= group.getVersion() ) throw new ValidationException( "Extension group version is greater than previous" ); prevVersion = group.getVersion(); } } private void assertExtensionGroupHasNoVersion() throws ValidationException { for( Type extension : type.getExtensions() ) if( extension instanceof CollectionTypeExtensionGroup && ( (CollectionTypeExtensionGroup)extension ).getVersion() != -1 ) throw new ValidationException( "Extension group version is prohibited: " + type ); } private boolean isExtensionVersionProhibited() { for( Type extension : type.getExtensions() ) if( isVersionProhibitedFor( extension ) ) return true; return false; } private static boolean isVersionProhibitedFor( Type extension ) { return extension instanceof ComponentType || extension instanceof ComponentsFromType || extension instanceof CollectionTypeExtensionGroup && ( (CollectionTypeExtensionGroup)extension ).getVersion() == -1; } } }
package net.meisen.general.genmisc; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; import net.meisen.general.genmisc.types.Streams; import org.junit.Test; /** * The test specified for the <code>Streams</code> * * @author pmeisen * */ public class TestStreams { /** * Tests the implementation of the * {@link Streams#writeStringToStream(String, java.io.OutputStream)} method */ @Test public void testWriteStringToStream() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final String content = "This is a Test"; // write it Streams.writeStringToStream(content, baos); // test it assertEquals(baos.toString(), content); } /** * Tests the implementation of the encoding guesses for some files. * * @throws IOException * if the file cannot be accessed */ @Test public void testGuessEncoding() throws IOException { InputStream is; String enc; // EMPTY is = getClass().getResourceAsStream("encodedFiles/Empty.txt"); enc = Streams.guessEncoding(is, null); assertEquals(System.getProperty("file.encoding"), enc); // ASCII is = getClass().getResourceAsStream("encodedFiles/ASCII.txt"); enc = Streams.guessEncoding(is, null); assertEquals("US-ASCII", enc); // Cp1252 is = getClass().getResourceAsStream("encodedFiles/Cp1252.txt"); enc = Streams.guessEncoding(is, null); assertEquals("Cp1252", enc); // UTF8 with BOM is = getClass().getResourceAsStream("encodedFiles/UTF8_BOM.txt"); enc = Streams.guessEncoding(is, null); assertEquals("UTF-8", enc); // UTF8 without BOM is = getClass().getResourceAsStream("encodedFiles/UTF8_noBOM.txt"); enc = Streams.guessEncoding(is, null); assertEquals("UTF-8", enc); // UTF16 BigEndian is = getClass().getResourceAsStream("encodedFiles/UCS-2_BigEndian.txt"); enc = Streams.guessEncoding(is, null); assertEquals("UTF-16BE", enc); // UTF16 LittleEndian is = getClass().getResourceAsStream( "encodedFiles/UCS-2_LittleEndian.txt"); enc = Streams.guessEncoding(is, null); assertEquals("UTF-16LE", enc); } /** * Tests the implementation of the short mappers, i.e. * {@link Streams#shortToByte(short)} and * {@link Streams#byteToShort(byte[])}. */ @Test public void testShortByte() { byte[] byteArray; short value; for (short i = Short.MIN_VALUE;; i++) { byteArray = Streams.shortToByte((short) i); value = Streams.byteToShort(byteArray); assertEquals((short) i, value); if (i == Short.MAX_VALUE) { break; } } } /** * Tests the implementation of the int mappers, i.e. * {@link Streams#intToByte(int)} and {@link Streams#byteToInt(byte[])}. */ @Test public void testIntByte() { byte[] byteArray; int value; for (int i = Integer.MIN_VALUE;; i++) { byteArray = Streams.intToByte(i); value = Streams.byteToInt(byteArray); assertEquals(i, value); if (i == Integer.MAX_VALUE) { break; } } } /** * Tests the implementation of the long mappers, i.e. * {@link Streams#longToByte(long)} and {@link Streams#byteToLong(byte[])}. */ @Test public void testLongByte() { byte[] byteArray; long value; // test the boundaries byteArray = Streams.longToByte(Long.MIN_VALUE); value = Streams.byteToLong(byteArray); assertEquals(Long.MIN_VALUE, value); byteArray = Streams.longToByte(Long.MAX_VALUE); value = Streams.byteToLong(byteArray); assertEquals(Long.MAX_VALUE, value); byteArray = Streams.longToByte(0); value = Streams.byteToLong(byteArray); assertEquals(0, value); // pick some random numbers final Random rnd = new Random(); for (int i = 0; i < Integer.MAX_VALUE; i++) { final long rndValue = rnd.nextLong(); byteArray = Streams.longToByte(rndValue); value = Streams.byteToLong(byteArray); assertEquals(rndValue, value); } } }
package io.branch.referral; import java.util.ArrayList; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PrefHelper { public static final boolean LOG = false; public static final String NO_STRING_VALUE = "bnc_no_value"; private static final String SHARED_PREF_FILE = "branch_referral_shared_pref"; private static final String KEY_APP_KEY = "bnc_app_key"; private static final String KEY_DEVICE_FINGERPRINT_ID = "bnc_device_fingerprint_id"; private static final String KEY_SESSION_ID = "bnc_session_id"; private static final String KEY_IDENTITY_ID = "bnc_identity_id"; private static final String KEY_LINK_CLICK_ID = "bnc_link_click_id"; private static final String KEY_SESSION_PARAMS = "bnc_session_params"; private static final String KEY_INSTALL_PARAMS = "bnc_install_params"; private static final String KEY_USER_URL = "bnc_user_url"; private static final String KEY_IS_REFERRABLE = "bnc_is_referrable"; private static final String KEY_BUCKETS = "bnc_buckets"; private static final String KEY_CREDIT_BASE = "bnc_credit_base_"; private static final String KEY_ACTIONS = "bnc_actions"; private static final String KEY_TOTAL_BASE = "bnc_total_base_"; private static final String KEY_UNIQUE_BASE = "bnc_balance_base_"; private static PrefHelper prefHelper_; private SharedPreferences appSharedPrefs_; private Editor prefsEditor_; public PrefHelper() {} private PrefHelper(Context context) { this.appSharedPrefs_ = context.getSharedPreferences(SHARED_PREF_FILE, Context.MODE_PRIVATE); this.prefsEditor_ = this.appSharedPrefs_.edit(); } public static PrefHelper getInstance(Context context) { if (prefHelper_ == null) { prefHelper_ = new PrefHelper(context); } return prefHelper_; } public String getAPIBaseUrl() { return "http://api.branchmetrics.io/"; } public void setAppKey(String key) { setString(KEY_APP_KEY, key); } public String getAppKey() { return getString(KEY_APP_KEY); } public void setDeviceFingerPrintID(String device_fingerprint_id) { setString(KEY_DEVICE_FINGERPRINT_ID, device_fingerprint_id); } public String getDeviceFingerPrintID() { return getString(KEY_DEVICE_FINGERPRINT_ID); } public void setSessionID(String session_id) { setString(KEY_SESSION_ID, session_id); } public String getSessionID() { return getString(KEY_SESSION_ID); } public void setIdentityID(String identity_id) { setString(KEY_IDENTITY_ID, identity_id); } public String getIdentityID() { return getString(KEY_IDENTITY_ID); } public void setLinkClickID(String link_click_id) { setString(KEY_LINK_CLICK_ID, link_click_id); } public String getLinkClickID() { return getString(KEY_LINK_CLICK_ID); } public String getSessionParams() { return getString(KEY_SESSION_PARAMS); } public void setSessionParams(String params) { setString(KEY_SESSION_PARAMS, params); } public String getInstallParams() { return getString(KEY_INSTALL_PARAMS); } public void setInstallParams(String params) { setString(KEY_INSTALL_PARAMS, params); } public void setUserURL(String user_url) { setString(KEY_USER_URL, user_url); } public String getUserURL() { return getString(KEY_USER_URL); } public int getIsReferrable() { return getInteger(KEY_IS_REFERRABLE); } public void setIsReferrable() { setInteger(KEY_IS_REFERRABLE, 1); } public void clearIsReferrable() { setInteger(KEY_IS_REFERRABLE, 0); } public void clearUserValues() { ArrayList<String> buckets = getBuckets(); for (String bucket : buckets) { setCreditCount(bucket, 0); } setBuckets(new ArrayList<String>()); ArrayList<String> actions = getActions(); for (String action : actions) { setActionTotalCount(action, 0); setActionUniqueCount(action, 0); } setActions(new ArrayList<String>()); } // REWARD TRACKING CALLS private ArrayList<String> getBuckets() { String bucketList = getString(KEY_BUCKETS); if (bucketList.equals(NO_STRING_VALUE)) { return new ArrayList<String>(); } else { return deserializeString(bucketList); } } private void setBuckets(ArrayList<String> buckets) { if (buckets.size() == 0) { setString(KEY_BUCKETS, NO_STRING_VALUE); } else { setString(KEY_BUCKETS, serializeArrayList(buckets)); } } public void setCreditCount(int count) { setCreditCount("default", count); } public void setCreditCount(String bucket, int count) { ArrayList<String> buckets = getBuckets(); if (!buckets.contains(bucket)) { buckets.add(bucket); setBuckets(buckets); } setInteger(KEY_CREDIT_BASE + bucket, count); } public int getCreditCount() { return getCreditCount("default"); } public int getCreditCount(String bucket) { return getInteger(KEY_CREDIT_BASE + bucket); } // EVENT REFERRAL INSTALL CALLS private ArrayList<String> getActions() { String actionList = getString(KEY_ACTIONS); if (actionList.equals(NO_STRING_VALUE)) { return new ArrayList<String>(); } else { return deserializeString(actionList); } } private void setActions(ArrayList<String> actions) { if (actions.size() == 0) { setString(KEY_ACTIONS, NO_STRING_VALUE); } else { setString(KEY_ACTIONS, serializeArrayList(actions)); } } public void setActionTotalCount(String action, int count) { ArrayList<String> actions = getActions(); if (!actions.contains(action)) { actions.add(action); setActions(actions); } setInteger(KEY_TOTAL_BASE + action, count); } public void setActionUniqueCount(String action, int count) { setInteger(KEY_UNIQUE_BASE + action, count); } public int getActionTotalCount(String action) { return getInteger(KEY_TOTAL_BASE + action); } public int getActionUniqueCount(String action) { return getInteger(KEY_UNIQUE_BASE + action); } // ALL GENERIC CALLS private String serializeArrayList(ArrayList<String> strings) { String retString = ""; for (String value : strings) { retString = retString + value + ","; } retString = retString.substring(0, retString.length()-1); return retString; } private ArrayList<String> deserializeString(String list) { ArrayList<String> strings = new ArrayList<String>(); String[] stringArr = list.split(","); for (int i = 0; i < stringArr.length; i++) { strings.add(stringArr[i]); } return strings; } public int getInteger(String key) { return prefHelper_.appSharedPrefs_.getInt(key, 0); } public long getLong(String key) { return prefHelper_.appSharedPrefs_.getLong(key, 0); } public float getFloat(String key) { return prefHelper_.appSharedPrefs_.getFloat(key, 0); } public String getString(String key) { return prefHelper_.appSharedPrefs_.getString(key, NO_STRING_VALUE); } public boolean getBool(String key) { return prefHelper_.appSharedPrefs_.getBoolean(key, false); } public void setInteger(String key, int value) { prefHelper_.prefsEditor_.putInt(key, value); prefHelper_.prefsEditor_.commit(); } public void setLong(String key, long value) { prefHelper_.prefsEditor_.putLong(key, value); prefHelper_.prefsEditor_.commit(); } public void setFloat(String key, float value) { prefHelper_.prefsEditor_.putFloat(key, value); prefHelper_.prefsEditor_.commit(); } public void setString(String key, String value) { prefHelper_.prefsEditor_.putString(key, value); prefHelper_.prefsEditor_.commit(); } public void setBool(String key, Boolean value) { prefHelper_.prefsEditor_.putBoolean(key, value); prefHelper_.prefsEditor_.commit(); } }
package services; import network.packets.soe.DataChannelA; import network.packets.swg.SWGPacket; import network.packets.swg.zone.baselines.Baseline; import intents.InboundPacketIntent; import intents.OutboundPacketIntent; import resources.control.Intent; import resources.control.Manager; import services.galaxy.GalacticManager; public class CoreManager extends Manager { private EngineManager engineManager; private GalacticManager galacticManager; private long startTime; public CoreManager() { engineManager = new EngineManager(); galacticManager = new GalacticManager(); addChildService(engineManager); addChildService(galacticManager); } /** * Determines whether or not the core is operational * @return TRUE if the core is operational, FALSE otherwise */ public boolean isOperational() { return true; } @Override public boolean initialize() { startTime = System.nanoTime(); registerForIntent(InboundPacketIntent.TYPE); registerForIntent(OutboundPacketIntent.TYPE); return super.initialize(); } @Override public void onIntentReceived(Intent i) { if (i instanceof InboundPacketIntent) { InboundPacketIntent in = (InboundPacketIntent) i; System.out.println("IN " + in.getNetworkId() + ":" + in.getServerType() + "\t" + in.getPacket().getClass().getSimpleName()); if (in.getPacket() instanceof DataChannelA) { for (SWGPacket p : ((DataChannelA) in.getPacket()).getPackets()) { System.out.println(" " + p.getClass().getSimpleName()); } } } else if (i instanceof OutboundPacketIntent) { OutboundPacketIntent out = (OutboundPacketIntent) i; System.out.println("OUT " + out.getNetworkId() + " \t" + out.getPacket().getClass().getSimpleName()); if (out.getPacket() instanceof DataChannelA) { for (SWGPacket p : ((DataChannelA) out.getPacket()).getPackets()) { if (p instanceof Baseline) System.out.println(" Baseline " + ((Baseline)p).getType() + " " + ((Baseline)p).getNum()); else System.out.println(" " + p.getClass().getSimpleName()); } } } } /** * Returns the time in milliseconds since the server started initialization * @return the core time represented as a double */ public double getCoreTime() { return (System.nanoTime()-startTime)/1E6; } }
package io.spine.client; import com.google.common.flogger.FluentLogger; import com.google.protobuf.Message; /** * Logs the fact of the error using the {@linkplain FluentLogger#atSevere() severe} level * of the passed logger. * * @param <M> * the type of the messages delivered to the consumer */ final class LoggingErrorHandler<M extends Message> extends LoggingHandler implements ErrorHandler { LoggingErrorHandler(FluentLogger logger, String messageFormat, Class<? extends Message> type) { super(logger, messageFormat, type); } @Override public void accept(Throwable throwable) { logger().atSevere() .withCause(throwable) .log(messageFormat(), type()); } }
package lombok.ast.grammar; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import org.junit.Test.None; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; public class DirectoryRunner extends Runner { private static final Comparator<Method> methodComparator = new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { String sig1 = o1.getName() + Arrays.toString(o1.getParameterTypes()); String sig2 = o2.getName() + Arrays.toString(o2.getParameterTypes()); return sig1.compareTo(sig2); } }; private static final Comparator<String> stringComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1 == null ? o2 == null : o1.equals(o2)) return 0; if (o1 == null) return -1; if (o2 == null) return +1; return o1.compareTo(o2); } }; private final Description description; private final Map<String, Map<Method, Description>> tests = new TreeMap<String, Map<Method, Description>>(stringComparator); private final Throwable failure; private final Class<?> testClass; private File directory, mirrorDirectory; public DirectoryRunner(Class<?> testClass) { this.testClass = testClass; description = Description.createSuiteDescription(testClass); Throwable error = null; try { addTests(testClass); } catch (Throwable t) { error = t; } this.failure = error; } private void addTests(Class<?> testClass) throws Exception { Method directoryMethod = testClass.getDeclaredMethod("getDirectory"); directory = (File) directoryMethod.invoke(null); try { Method mirrorMethod = testClass.getDeclaredMethod("getMirrorDirectory"); mirrorDirectory = (File)mirrorMethod.invoke(null); } catch (NoSuchMethodException e) { //then we'll go on without one! } File[] files = mirrorDirectory == null ? directory.listFiles() : mirrorDirectory.listFiles(); Map<Method, Description> noFileNeededMap = new TreeMap<Method, Description>(methodComparator); for (File file : files) { if (!file.getName().endsWith(".java")) continue; Map<Method, Description> methodToDescMap = new TreeMap<Method, Description>(methodComparator); tests.put(file.getName(), methodToDescMap); for (Method m : testClass.getMethods()) { if (m.getAnnotation(Test.class) != null) { if (m.getParameterTypes().length == 0) { if (!noFileNeededMap.containsKey(m)) { Description testDescription = Description.createTestDescription(testClass, m.getName()); description.addChild(testDescription); noFileNeededMap.put(m, testDescription); } } else { Description testDescription = Description.createTestDescription(testClass, m.getName() + ": " + file.getName()); description.addChild(testDescription); methodToDescMap.put(m, testDescription); } } } } } @Override public Description getDescription() { return description; } @Override public void run(RunNotifier notifier) { if (failure != null) { notifier.fireTestStarted(description); notifier.fireTestFailure(new Failure(description, failure)); notifier.fireTestFinished(description); return; } for (Entry<String, Map<Method, Description>> entry : tests.entrySet()) { Map<Method, Description> methodList = entry.getValue(); String content; Throwable error; try { content = entry.getKey() == null ? null : FileUtils.readFileToString(new File( mirrorDirectory == null ? directory : mirrorDirectory, entry.getKey()), "UTF-8"); error = null; } catch (IOException e) { content = null; error = e; } for (Entry<Method, Description> test : methodList.entrySet()) { Description testDescription = test.getValue(); notifier.fireTestStarted(testDescription); if (error != null) { notifier.fireTestFailure(new Failure(testDescription, error)); } else { try { if (!runTest(content, entry.getKey(), test.getKey())) { notifier.fireTestIgnored(testDescription); } } catch (Throwable t) { notifier.fireTestFailure(new Failure(testDescription, t)); } } notifier.fireTestFinished(testDescription); } } } private boolean runTest(String rawSource, String fileName, Method method) throws Throwable { Class<?>[] paramTypes = method.getParameterTypes(); Object[] params; Test t = method.getAnnotation(Test.class); switch (paramTypes.length) { case 0: assert rawSource == null; params = new Object[0]; break; case 1: if (mirrorDirectory != null) return false; if (paramTypes[0] == String.class) params = new Object[] {rawSource}; else if (paramTypes[0] == Source.class) params = new Object[] {new Source(rawSource, fileName)}; else return false; break; case 2: if (mirrorDirectory == null) return false; params = new Object[2]; String mainFileName = fileName.replaceAll("\\.\\d+\\.java$", ".java"); String expectedContent = FileUtils.readFileToString(new File(directory, mainFileName), "UTF-8"); if (paramTypes[0] == String.class) params[0] = expectedContent; else if (paramTypes[0] == Source.class) params[0] = new Source(expectedContent, mainFileName); else return false; if (paramTypes[1] == String.class) params[1] = rawSource; else if (paramTypes[1] == Source.class) params[1] = new Source(rawSource, fileName); else return false; break; default: return false; } Object instance = testClass.newInstance(); if (t != null && t.expected() != None.class) { try { Object executed = method.invoke(instance, params); if (executed instanceof Boolean && !(Boolean)executed) return false; Assert.fail("Expected exception: " + t.expected().getName()); } catch (InvocationTargetException e) { if (t.expected().isInstance(e.getCause())) return true; throw e.getCause(); } } else { try { Object executed = method.invoke(instance, params); if (executed instanceof Boolean && !(Boolean)executed) return false; } catch (InvocationTargetException e) { throw e.getCause(); } } return true; } }
package imcode.server.parser; import imcode.server.DocumentRequest; import imcode.server.ImcmsServices; import imcode.server.document.DocumentDomainObject; import imcode.server.document.textdocument.MenuDomainObject; import imcode.server.document.textdocument.MenuItemDomainObject; import imcode.server.document.textdocument.TextDocumentDomainObject; import imcode.server.user.UserDomainObject; import imcode.util.Html; import imcode.util.IdNamePair; import imcode.util.Utility; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.iterators.FilterIterator; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.oro.text.regex.PatternMatcher; import org.apache.oro.text.regex.StringSubstitution; import org.apache.oro.text.regex.Substitution; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; class MenuParser { private Substitution NULLSUBSTITUTION = new StringSubstitution( "" ); private Map menus; private int[] implicitMenus = {1}; private ParserParameters parserParameters; private static final int EXISTING_DOCTYPE_ID = 0; MenuParser( ParserParameters parserParameters ) { this.parserParameters = parserParameters; TextDocumentDomainObject textDocument = (TextDocumentDomainObject)parserParameters.getDocumentRequest().getDocument(); this.menus = textDocument.getMenus(); } private MenuDomainObject getMenuByIndex( int id ) { return (MenuDomainObject)menus.get( new Integer( id ) ); } private String getMenuModePrefix( int menuIndex, Properties menuattributes ) { Integer editingMenuIndex = parserParameters.getEditingMenuIndex(); ImcmsServices serverObject = parserParameters.getDocumentRequest().getServerObject(); UserDomainObject user = parserParameters.getDocumentRequest().getUser(); MenuDomainObject menu = getMenuByIndex( menuIndex ); List parseTags = Arrays.asList( new String[]{ "#menuindex#", "" + menuIndex, "#label#", menuattributes.getProperty( "label" ), "#flags#", "" + parserParameters.getFlags(), "#sortOrder" + ( null != menu ? menu.getSortOrder() : MenuDomainObject.MENU_SORT_ORDER__DEFAULT ) + "#", "checked", "#doc_types#", createDocumentTypesOptionList(), "#meta_id#", "" + parserParameters.getDocumentRequest().getDocument().getId(), "#defaulttemplate#", URLEncoder.encode( StringUtils.defaultString( menuattributes.getProperty( "defaulttemplate" ) ) ) } ); String result = serverObject.getAdminTemplate( "textdoc/menulabel.frag", user, parseTags ); if ( null != editingMenuIndex && editingMenuIndex.intValue() == menuIndex ) { result += serverObject.getAdminTemplate( "textdoc/add_doc.html", user, parseTags ) + serverObject.getAdminTemplate( "textdoc/sort_order.html", user, parseTags ); } return result; } private String getMenuModeSuffix( int menuIndex ) { Integer editingMenuIndex = parserParameters.getEditingMenuIndex(); if ( null != editingMenuIndex && editingMenuIndex.intValue() == menuIndex ) { return parserParameters.getDocumentRequest().getServerObject().getAdminTemplate( "textdoc/archive_del_button.html", parserParameters.getDocumentRequest().getUser(), null ); } else { List parseTags = Arrays.asList( new String[]{ "#menuindex#", "" + menuIndex, "#flags#", "" + parserParameters.getFlags(), "#meta_id#", "" + parserParameters.getDocumentRequest().getDocument().getId() } ); return parserParameters.getDocumentRequest().getServerObject().getAdminTemplate( "textdoc/admin_menu.frag", parserParameters.getDocumentRequest().getUser(), parseTags ); } } private String createDocumentTypesOptionList() { DocumentDomainObject document = parserParameters.getDocumentRequest().getDocument(); UserDomainObject user = parserParameters.getDocumentRequest().getUser(); IdNamePair[] docTypes = parserParameters.getDocumentRequest().getServerObject().getDocumentMapper().getCreatableDocumentTypeIdsAndNamesInUsersLanguage( document, user ); Map docTypesMap = new HashMap(); for ( int i = 0; i < docTypes.length; i++ ) { IdNamePair docType = docTypes[i]; docTypesMap.put( new Integer( docType.getId() ), docType ); } String existing_doc_name = parserParameters.getDocumentRequest().getServerObject().getAdminTemplate( "textdoc/existing_doc_name.html", parserParameters.getDocumentRequest().getUser(), null ); docTypesMap.put( new Integer( EXISTING_DOCTYPE_ID ), new IdNamePair( EXISTING_DOCTYPE_ID, existing_doc_name ) ); final int[] docTypeIdsOrder = { DocumentDomainObject.DOCTYPE_ID_TEXT, EXISTING_DOCTYPE_ID, DocumentDomainObject.DOCTYPE_ID_URL, DocumentDomainObject.DOCTYPE_ID_FILE, DocumentDomainObject.DOCTYPE_ID_BROWSER, DocumentDomainObject.DOCTYPE_ID_HTML, DocumentDomainObject.DOCTYPE_ID_CHAT, DocumentDomainObject.DOCTYPE_ID_BILLBOARD, DocumentDomainObject.DOCTYPE_ID_CONFERENCE, }; StringBuffer documentTypesHtmlOptionList = new StringBuffer(); for ( int i = 0; i < docTypeIdsOrder.length; i++ ) { int docTypeId = docTypeIdsOrder[i]; IdNamePair temp = (IdNamePair)docTypesMap.get( new Integer( docTypeId ) ); if ( null != temp ) { int documentTypeId = temp.getId(); String documentTypeName = temp.getName(); documentTypesHtmlOptionList.append( "<option value=\"" + documentTypeId + "\">" + documentTypeName + "</option>" ); } } return documentTypesHtmlOptionList.toString(); } private String parseMenuNode( int menuIndex, String menutemplate, Properties menuattributes, PatternMatcher patMat ) { String modeAttribute = menuattributes.getProperty( "mode" ); boolean modeIsRead = "read".equalsIgnoreCase( modeAttribute ); boolean modeIsWrite = "write".equalsIgnoreCase( modeAttribute ); boolean menuMode = parserParameters.isMenuMode(); if ( menuMode && modeIsRead || !menuMode && modeIsWrite ) { return ""; } MenuDomainObject currentMenu = getMenuByIndex( menuIndex ); // Get the menu StringBuffer result = new StringBuffer(); // Allocate a buffer for building our return-value in. NodeList menuNodes = new NodeList( menutemplate ); // Build a tree-structure of nodes in memory, which "only" needs to be traversed. (Vood)oo-magic. nodeMenu( new SimpleElement( "menu", menuattributes, menuNodes ), result, currentMenu, patMat, menuIndex ); // Create an artificial root-node of this tree. An "imcms:menu"-element. if ( menuMode ) { // If in menuMode, make sure to include all the stuff from the proper admintemplates. result.append( getMenuModeSuffix( menuIndex ) ); result.insert( 0, getMenuModePrefix( menuIndex, menuattributes ) ); } return result.toString(); } /** * Handle an imcms:menu element. */ private void nodeMenu( Element menuNode, StringBuffer result, MenuDomainObject currentMenu, PatternMatcher patMat, int menuIndex ) { if ( currentMenu == null || 0 == currentMenu.getMenuItems().length ) { return; // Don't output anything } Properties menuAttributes = menuNode.getAttributes(); // Get the attributes from the imcms:menu-element. This will be passed down, to allow attributes of the imcms:menu-element to affect the menuitems. if ( menuNode.getChildElement( "menuloop" ) == null ) { nodeMenuLoop( new SimpleElement( "menuloop", null, menuNode.getChildren() ), result, currentMenu, menuAttributes, patMat, menuIndex ); // The imcms:menu contained no imcms:menuloop, so let's create one, passing the children from the imcms:menu } else { // The imcms:menu contained at least one imcms:menuloop. Iterator menuNodeChildrenIterator = menuNode.getChildren().iterator(); while ( menuNodeChildrenIterator.hasNext() ) { Node menuNodeChild = (Node)menuNodeChildrenIterator.next(); switch ( menuNodeChild.getNodeType() ) { // Check the type of the child-node. case Node.TEXT_NODE: // A text-node result.append( ( (Text)menuNodeChild ).getContent() ); // Append the contents to our result. break; case Node.ELEMENT_NODE: // An element-node if ( "menuloop".equals( ( (Element)menuNodeChild ).getName() ) ) { // Is it an imcms:menuloop? nodeMenuLoop( (Element)menuNodeChild, result, currentMenu, menuAttributes, patMat, menuIndex ); } else { result.append( menuNodeChild.toString() ); // No? Just append it (almost)verbatim. } break; } } } } /** * Handle an imcms:menuloop element. * * @param menuLoopNode The imcms:menuloop-element * @param result The StringBuffer to which to append the result * @param menu The current menu * @param menuAttributes The attributes passed down from the imcms:menu-element. * @param patMat The patternmatcher used for pattern matching. */ private void nodeMenuLoop( Element menuLoopNode, StringBuffer result, MenuDomainObject menu, Properties menuAttributes, PatternMatcher patMat, int menuIndex ) { if ( null == menu ) { return; } List menuLoopNodeChildren = menuLoopNode.getChildren(); if ( null == menuLoopNode.getChildElement( "menuitem" ) ) { Element menuItemNode = new SimpleElement( "menuitem", null, menuLoopNodeChildren ); // The imcms:menuloop contained no imcms:menuitem, so let's create one. menuLoopNodeChildren = new ArrayList( 1 ); menuLoopNodeChildren.add( menuItemNode ); } // The imcms:menuloop contained at least one imcms:menuitem. loopOverMenuItemsAndMenuItemTemplateElementsAndAddToResult( menu, menuLoopNodeChildren, result, menuAttributes, patMat, menuIndex ); } private boolean editingMenu( int menuIndex ) { Integer editingMenuIndex = parserParameters.getEditingMenuIndex(); boolean editingThisMenu = null != editingMenuIndex && editingMenuIndex.intValue() == menuIndex && parserParameters.isMenuMode(); return editingThisMenu; } private void loopOverMenuItemsAndMenuItemTemplateElementsAndAddToResult( MenuDomainObject menu, final List menuLoopNodeChildren, StringBuffer result, Properties menuAttributes, PatternMatcher patMat, final int menuIndex ) { Iterator menuItemsIterator = new FilterIterator( Arrays.asList( menu.getMenuItems() ).iterator(), new Predicate() { public boolean evaluate( Object o ) { DocumentDomainObject document = ( (MenuItemDomainObject)o ).getDocument(); UserDomainObject user = parserParameters.getDocumentRequest().getUser(); if ( document.isVisibleInMenusForUnauthorizedUsers() || user.canAccess( document ) ) { if ( editingMenu( menuIndex ) || document.isPublishedAndNotArchived() ) { return true; } } return false; } } ); int menuItemIndexStart = 0; try { menuItemIndexStart = Integer.parseInt( menuAttributes.getProperty( "indexstart" ) ); } catch ( NumberFormatException nfe ) { // already set } int menuItemIndexStep = 1; try { menuItemIndexStep = Integer.parseInt( menuAttributes.getProperty( "indexstep" ) ); } catch ( NumberFormatException nfe ) { // already set } int menuItemIndex = menuItemIndexStart; while ( menuItemsIterator.hasNext() ) { // While there still are more menuitems from the db. Iterator menuLoopChildrenIterator = menuLoopNodeChildren.iterator(); while ( menuLoopChildrenIterator.hasNext() ) { // While there still are more imcms:menuloop-children Node menuLoopChild = (Node)menuLoopChildrenIterator.next(); switch ( menuLoopChild.getNodeType() ) { // Check the type of the child-node. case Node.TEXT_NODE: // A text-node result.append( ( (Text)menuLoopChild ).getContent() ); // Append the contents to our result. break; case Node.ELEMENT_NODE: // An element-node if ( "menuitem".equals( ( (Element)menuLoopChild ).getName() ) ) { // Is it an imcms:menuitem? MenuItemDomainObject menuItem = menuItemsIterator.hasNext() ? (MenuItemDomainObject)menuItemsIterator.next() : null; // If there are more menuitems from the db, put the next in 'menuItem', otherwise put null. nodeMenuItem( (Element)menuLoopChild, result, menuItem, menuAttributes, patMat, menuItemIndex, menu, menuIndex ); // Parse one menuitem. menuItemIndex += menuItemIndexStep; } else { result.append( menuLoopChild.toString() ); // No? Just append the elements verbatim into the result. } break; } } } } /** * Handle one imcms:menuitem * * @param menuItemNode The imcms:menuitem-element * @param result The StringBuffer to which to append the result * @param menuItem The current menuitem * @param menuAttributes The attributes passed down from the imcms:menu-element. Any attributes in the imcms:menuitem-element will override these. * @param patMat The patternmatcher used for pattern matching. */ private void nodeMenuItem( Element menuItemNode, StringBuffer result, MenuItemDomainObject menuItem, Properties menuAttributes, PatternMatcher patMat, int menuItemIndex, MenuDomainObject menu, int menuIndex ) { Substitution menuItemSubstitution; if ( menuItem != null ) { Properties menuItemAttributes = new Properties( menuAttributes ); // Make a copy of the menuAttributes, so we don't override them permanently. menuItemAttributes.putAll( menuItemNode.getAttributes() ); // Let all attributes of the menuItemNode override the attributes of the menu. menuItemSubstitution = getMenuItemSubstitution( menu, menuItem, menuItemAttributes, menuItemIndex, menuIndex ); } else { menuItemSubstitution = NULLSUBSTITUTION; } Iterator menuItemChildrenIterator = menuItemNode.getChildren().iterator(); while ( menuItemChildrenIterator.hasNext() ) { // For each node that is a child of this imcms:menuitem-element Node menuItemChild = (Node)menuItemChildrenIterator.next(); switch ( menuItemChild.getNodeType() ) { // Check the type of the child-node. case Node.ELEMENT_NODE: // An element-node Element menuItemChildElement = (Element)menuItemChild; if ( !"menuitemhide".equals( menuItemChildElement.getName() ) || menuItem != null ) { // if the child-element isn't a imcms:menuitemhide-element or there is a child... parseMenuItem( result, menuItemChildElement.getTextContent(), menuItemSubstitution, patMat ); // parse it } break; case Node.TEXT_NODE: // A text-node parseMenuItem( result, ( (Text)menuItemChild ).getContent(), menuItemSubstitution, patMat ); // parse it break; } } } private void parseMenuItem( StringBuffer result, String template, Substitution substitution, PatternMatcher patMat ) { result.append( org.apache.oro.text.regex.Util.substitute( patMat, TextDocumentParser.HASHTAG_PATTERN, substitution, template, org.apache.oro.text.regex.Util.SUBSTITUTE_ALL ) ); } public String tag( Properties menuattributes, String menutemplate, PatternMatcher patMat ) { int menuIndex; try { menuIndex = Integer.parseInt( menuattributes.getProperty( "no" ) ); } catch ( NumberFormatException ex ) { menuIndex = implicitMenus[0]++; } return parseMenuNode( menuIndex, menutemplate, menuattributes, patMat ); } /** * Create a substitution for parsing this menuitem into a template with the correct tags. */ private Substitution getMenuItemSubstitution( MenuDomainObject menu, MenuItemDomainObject menuItem, Properties parameters, int menuItemIndex, int menuIndex ) { DocumentDomainObject document = menuItem.getDocument(); String imageUrl = document.getMenuImage(); String imageTag = imageUrl != null && imageUrl.length() > 0 ? "<img src=\"" + StringEscapeUtils.escapeHtml( imageUrl ) + "\" border=\"0\">" : ""; String headline = StringEscapeUtils.escapeHtml( document.getHeadline() ); if ( headline.length() == 0 ) { headline = "&nbsp;"; } else { if ( !document.isPublished() ) { headline = "<em><i>" + headline; headline += "</i></em>"; } if ( document.isArchived() ) { headline = "<strike>" + headline; headline += "</strike>"; } } SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" ); String createdDate = dateFormat.format( document.getCreatedDatetime() ); String modifiedDate = dateFormat.format( document.getModifiedDatetime() ); Properties tags = new Properties(); tags.setProperty( "#childMetaId#", "" + document.getId() ); tags.setProperty( "#childMetaHeadline#", headline ); tags.setProperty( "#childMetaText#", document.getMenuText() ); tags.setProperty( "#childMetaImage#", imageTag ); tags.setProperty( "#childCreatedDate#", createdDate ); tags.setProperty( "#childModifiedDate#", modifiedDate ); tags.setProperty( "#menuitemindex#", "" + menuItemIndex ); tags.setProperty( "#menuitemtreesortkey#", menuItem.getTreeSortKey().toString() ); tags.setProperty( "#menuitemmetaid#", "" + document.getId() ); tags.setProperty( "#menuitemheadline#", headline ); tags.setProperty( "#menuitemtext#", document.getMenuText() ); tags.setProperty( "#menuitemimage#", imageTag ); tags.setProperty( "#menuitemimageurl#", StringEscapeUtils.escapeHtml( imageUrl ) ); tags.setProperty( "#menuitemtarget#", document.getTarget() ); tags.setProperty( "#menuitemdatecreated#", createdDate ); tags.setProperty( "#menuitemdatemodified#", modifiedDate ); DocumentRequest documentRequest = parserParameters.getDocumentRequest(); String template = parameters.getProperty( "template" ); String href = Utility.getAbsolutePathToDocument( documentRequest.getHttpServletRequest(), document ); if (null != template) { href += -1 != href.indexOf( '?' ) ? '&' : '?' ; href += "template=" + URLEncoder.encode( template ) ; } List menuItemAHref = new ArrayList( 4 ); menuItemAHref.add( "#href#" ); menuItemAHref.add( href ); menuItemAHref.add( "#target#" ); menuItemAHref.add( document.getTarget() ); UserDomainObject user = documentRequest.getUser(); ImcmsServices serverObject = documentRequest.getServerObject(); String a_href = serverObject.getAdminTemplate( "textdoc/menuitem_a_href.frag", user, menuItemAHref ); tags.setProperty( "#menuitemlinkonly#", a_href ); tags.setProperty( "#/menuitemlinkonly#", "</a>" ); boolean editingThisMenu = editingMenu( menuIndex ); if ( editingThisMenu ) { final int sortOrder = menu.getSortOrder(); if ( MenuDomainObject.MENU_SORT_ORDER__BY_MANUAL_ORDER_REVERSED == sortOrder || MenuDomainObject.MENU_SORT_ORDER__BY_MANUAL_TREE_ORDER == sortOrder ) { String sortKey ; String sortKeyTemplate ; if ( MenuDomainObject.MENU_SORT_ORDER__BY_MANUAL_ORDER_REVERSED == sortOrder ) { sortKey = "" + menuItem.getSortKey(); sortKeyTemplate = "textdoc/admin_menuitem_manual_sortkey.frag"; } else { String key = menuItem.getTreeSortKey().toString(); sortKey = key == null ? "" : key; sortKeyTemplate = "textdoc/admin_menuitem_treesortkey.frag"; } List menuItemSortKeyTags = new ArrayList( 4 ); menuItemSortKeyTags.add( "#meta_id#" ); menuItemSortKeyTags.add( "" + document.getId() ); menuItemSortKeyTags.add( "#sortkey#" ); menuItemSortKeyTags.add( sortKey ); a_href = serverObject.getAdminTemplate( sortKeyTemplate, user, menuItemSortKeyTags ) + a_href; } List menuItemCheckboxTags = new ArrayList( 2 ); menuItemCheckboxTags.add( "#meta_id#" ); menuItemCheckboxTags.add( "" + document.getId() ); a_href = serverObject.getAdminTemplate( "textdoc/admin_menuitem_checkbox.frag", user, menuItemCheckboxTags ) + a_href; a_href = Html.getLinkedStatusIconTemplate( menuItem.getDocument(), user, documentRequest.getHttpServletRequest() ) + a_href; } tags.setProperty( "#menuitemlink#", a_href ); tags.setProperty( "#/menuitemlink#", editingThisMenu && user.canEdit( menuItem.getDocument() ) ? "</a>" + serverObject.getAdminTemplate( "textdoc/admin_menuitem.frag", user, Arrays.asList( new String[]{ "#meta_id#", "" + document.getId() } ) ) : "</a>" ); return new MapSubstitution( tags, true ); } }
package com.adafruit.bleuart; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.content.Context; import android.util.Log; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.UUID; import java.util.WeakHashMap; import java.lang.String; import java.util.concurrent.ConcurrentLinkedQueue; public class BluetoothLeUart extends BluetoothGattCallback implements BluetoothAdapter.LeScanCallback { // UUIDs for UART service and associated characteristics. public static UUID UART_UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); public static UUID TX_UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"); public static UUID RX_UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"); // UUID for the UART BTLE client characteristic which is necessary for notifications. public static UUID CLIENT_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // UUIDs for the Device Information service and associated characeristics. public static UUID DIS_UUID = UUID.fromString("0000180a-0000-1000-8000-00805f9b34fb"); public static UUID DIS_MANUF_UUID = UUID.fromString("00002a29-0000-1000-8000-00805f9b34fb"); public static UUID DIS_MODEL_UUID = UUID.fromString("00002a24-0000-1000-8000-00805f9b34fb"); public static UUID DIS_HWREV_UUID = UUID.fromString("00002a26-0000-1000-8000-00805f9b34fb"); public static UUID DIS_SWREV_UUID = UUID.fromString("00002a28-0000-1000-8000-00805f9b34fb"); // Internal UART state. private Context context; private WeakHashMap<Callback, Object> callbacks; private BluetoothAdapter adapter; private BluetoothGatt gatt; private BluetoothGattCharacteristic tx; private BluetoothGattCharacteristic rx; private boolean connectFirst; // Device Information state. private BluetoothGattCharacteristic disManuf; private BluetoothGattCharacteristic disModel; private BluetoothGattCharacteristic disHWRev; private BluetoothGattCharacteristic disSWRev; private boolean disAvailable; // Queues for characteristic read (synchronous) private Queue<BluetoothGattCharacteristic> readQueue; // Interface for a BluetoothLeUart client to be notified of UART actions. public interface Callback { public void onConnected(BluetoothLeUart uart); public void onConnectFailed(BluetoothLeUart uart); public void onDisconnected(BluetoothLeUart uart); public void onReceive(BluetoothLeUart uart, BluetoothGattCharacteristic rx); public void onDeviceFound(BluetoothDevice device); public void onDeviceInfoAvailable(); } public BluetoothLeUart(Context context) { super(); this.context = context; this.callbacks = new WeakHashMap<Callback, Object>(); this.adapter = BluetoothAdapter.getDefaultAdapter(); this.gatt = null; this.tx = null; this.rx = null; this.disManuf = null; this.disModel = null; this.disHWRev = null; this.disSWRev = null; this.disAvailable = false; this.connectFirst = false; this.readQueue = new ConcurrentLinkedQueue<BluetoothGattCharacteristic>(); } // Return instance of BluetoothGatt. public BluetoothGatt getGatt() { return gatt; } // Return true if connected to UART device, false otherwise. public boolean isConnected() { return (tx != null && rx != null); } public String getDeviceInfo() { if (tx == null || !disAvailable ) { // Do nothing if there is no connection. return ""; } StringBuilder sb = new StringBuilder(); sb.append(disManuf.getStringValue(0)); sb.append(" "); sb.append(disModel.getStringValue(0)); sb.append(" (Firmware v"); sb.append(disSWRev.getStringValue(0)); sb.append(")"); return sb.toString(); }; public boolean deviceInfoAvailable() { return disAvailable; } // Send data to connected UART device. public void send(byte[] data) { if (tx == null || data == null || data.length == 0) { // Do nothing if there is no connection or message to send. return; } // Update TX characteristic value. Note the setValue overload that takes a byte array must be used. tx.setValue(data); gatt.writeCharacteristic(tx); } // Send data to connected UART device. public void send(String data) { if (data != null && !data.isEmpty()) { send(data.getBytes(Charset.forName("UTF-8"))); } // ToDo: Update to a non UI thread delay and sync with each 'connection interval' via a // semaphore or some other mechanism (is the connection event exposed in the Android // BLE API???). It seems we can only send one packet (20 bytes max) per connection event. try { Thread.sleep(110); } catch (InterruptedException e) { e.printStackTrace(); } } // Register the specified callback to receive UART callbacks. public void registerCallback(Callback callback) { callbacks.put(callback, null); } // Unregister the specified callback. public void unregisterCallback(Callback callback) { callbacks.remove(callback); } // Disconnect to a device if currently connected. public void disconnect() { if (gatt != null) { gatt.disconnect(); } gatt = null; tx = null; rx = null; } // Stop any in progress UART device scan. public void stopScan() { if (adapter != null) { adapter.stopLeScan(this); } } // Start scanning for BLE UART devices. Registered callback's onDeviceFound method will be called // when devices are found during scanning. public void startScan() { if (adapter != null) { adapter.startLeScan(this); } } // Connect to the first available UART device. public void connectFirstAvailable() { // Disconnect to any connected device. disconnect(); // Stop any in progress device scan. stopScan(); // Start scan and connect to first available device. connectFirst = true; startScan(); } // Handlers for BluetoothGatt and LeScan events. @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); if (newState == BluetoothGatt.STATE_CONNECTED) { if (status == BluetoothGatt.GATT_SUCCESS) { // Connected to device, start discovering services. if (!gatt.discoverServices()) { // Error starting service discovery. connectFailure(); } } else { // Error connecting to device. connectFailure(); } } else if (newState == BluetoothGatt.STATE_DISCONNECTED) { // Disconnected, notify callbacks of disconnection. rx = null; tx = null; notifyOnDisconnected(this); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); // Notify connection failure if service discovery failed. if (status == BluetoothGatt.GATT_FAILURE) { connectFailure(); return; } // Save reference to each UART characteristic. tx = gatt.getService(UART_UUID).getCharacteristic(TX_UUID); rx = gatt.getService(UART_UUID).getCharacteristic(RX_UUID); // Save reference to each DIS characteristic. disManuf = gatt.getService(DIS_UUID).getCharacteristic(DIS_MANUF_UUID); disModel = gatt.getService(DIS_UUID).getCharacteristic(DIS_MODEL_UUID); disHWRev = gatt.getService(DIS_UUID).getCharacteristic(DIS_HWREV_UUID); disSWRev = gatt.getService(DIS_UUID).getCharacteristic(DIS_SWREV_UUID); // Add device information characteristics to the read queue // These need to be queued because we have to wait for the response to the first // read request before a second one can be processed (which makes you wonder why they // implemented this with async logic to begin with???) readQueue.offer(disManuf); readQueue.offer(disModel); readQueue.offer(disHWRev); readQueue.offer(disSWRev); // Request a dummy read to get the device information queue going gatt.readCharacteristic(disManuf); // Setup notifications on RX characteristic changes (i.e. data received). // First call setCharacteristicNotification to enable notification. if (!gatt.setCharacteristicNotification(rx, true)) { // Stop if the characteristic notification setup failed. connectFailure(); return; } // Next update the RX characteristic's client descriptor to enable notifications. BluetoothGattDescriptor desc = rx.getDescriptor(CLIENT_UUID); if (desc == null) { // Stop if the RX characteristic has no client descriptor. connectFailure(); return; } desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); if (!gatt.writeDescriptor(desc)) { // Stop if the client descriptor could not be written. connectFailure(); return; } // Notify of connection completion. notifyOnConnected(this); } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { super.onCharacteristicChanged(gatt, characteristic); notifyOnReceive(this, characteristic); } @Override public void onCharacteristicRead (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicRead(gatt, characteristic, status); if (status == BluetoothGatt.GATT_SUCCESS) { //Log.w("DIS", characteristic.getStringValue(0)); // Check if there is anything left in the queue if(readQueue.size() > 0){ // Send a read request for the next item in the queue gatt.readCharacteristic(readQueue.poll()); } else { // We've reached the end of the queue disAvailable = true; notifyOnDeviceInfoAvailable(); } } else { //Log.w("DIS", "Failed reading characteristic " + characteristic.getUuid().toString()); } } @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { // Stop if the device doesn't have the UART service. if (!parseUUIDs(scanRecord).contains(UART_UUID)) { return; } // Notify registered callbacks of found device. notifyOnDeviceFound(device); // Connect to first found device if required. if (connectFirst) { // Stop scanning for devices. stopScan(); // Prevent connections to future found devices. connectFirst = false; // Connect to device. gatt = device.connectGatt(context, true, this); } } // Private functions to simplify the notification of all callbacks of a certain event. private void notifyOnConnected(BluetoothLeUart uart) { for (Callback cb : callbacks.keySet()) { if (cb != null) { cb.onConnected(uart); } } } private void notifyOnConnectFailed(BluetoothLeUart uart) { for (Callback cb : callbacks.keySet()) { if (cb != null) { cb.onConnectFailed(uart); } } } private void notifyOnDisconnected(BluetoothLeUart uart) { for (Callback cb : callbacks.keySet()) { if (cb != null) { cb.onDisconnected(uart); } } } private void notifyOnReceive(BluetoothLeUart uart, BluetoothGattCharacteristic rx) { for (Callback cb : callbacks.keySet()) { if (cb != null ) { cb.onReceive(uart, rx); } } } private void notifyOnDeviceFound(BluetoothDevice device) { for (Callback cb : callbacks.keySet()) { if (cb != null) { cb.onDeviceFound(device); } } } private void notifyOnDeviceInfoAvailable() { for (Callback cb : callbacks.keySet()) { if (cb != null) { cb.onDeviceInfoAvailable(); } } } // Notify callbacks of connection failure, and reset connection state. private void connectFailure() { rx = null; tx = null; notifyOnConnectFailed(this); } // Filtering by custom UUID is broken in Android 4.3 and 4.4, see: // http://stackoverflow.com/questions/18019161/startlescan-with-128-bit-uuids-doesnt-work-on-native-android-ble-implementation?noredirect=1#comment27879874_18019161 // This is a workaround function from the SO thread to manually parse advertisement data. private List<UUID> parseUUIDs(final byte[] advertisedData) { List<UUID> uuids = new ArrayList<UUID>(); int offset = 0; while (offset < (advertisedData.length - 2)) { int len = advertisedData[offset++]; if (len == 0) break; int type = advertisedData[offset++]; switch (type) { case 0x02: // Partial list of 16-bit UUIDs case 0x03: // Complete list of 16-bit UUIDs while (len > 1) { int uuid16 = advertisedData[offset++]; uuid16 += (advertisedData[offset++] << 8); len -= 2; uuids.add(UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", uuid16))); } break; case 0x06:// Partial list of 128-bit UUIDs case 0x07:// Complete list of 128-bit UUIDs // Loop through the advertised 128-bit UUID's. while (len >= 16) { try { // Wrap the advertised bits and order them. ByteBuffer buffer = ByteBuffer.wrap(advertisedData, offset++, 16).order(ByteOrder.LITTLE_ENDIAN); long mostSignificantBit = buffer.getLong(); long leastSignificantBit = buffer.getLong(); uuids.add(new UUID(leastSignificantBit, mostSignificantBit)); } catch (IndexOutOfBoundsException e) { // Defensive programming. //Log.e(LOG_TAG, e.toString()); continue; } finally { // Move the offset to read the next uuid. offset += 15; len -= 16; } } break; default: offset += (len - 1); break; } } return uuids; } }
package som.vmobjects; import java.util.Arrays; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.profiles.ValueProfile; import som.vm.NotYetImplementedException; import som.vm.constants.Nil; /** * SArrays are implemented using a Strategy-like approach. * The SArray objects are 'tagged' with a type, and the strategy behavior * is implemented directly in the AST nodes. */ public abstract class SArray extends SAbstractObject { public static final int FIRST_IDX = 0; public static final ValueProfile OBJECT_ARRAY_PROFILE = ValueProfile.createClassProfile(); protected Object storage; protected final SClass clazz; protected SArray(final long length, final SClass clazz) { storage = (int) length; this.clazz = clazz; } protected SArray(final Object storage, final SClass clazz) { assert !(storage instanceof Long); assert storage != null; this.storage = storage; this.clazz = clazz; } @Override public final SClass getSOMClass() { return clazz; } public Object getStoragePlain() { CompilerAsserts.neverPartOfCompilation(); return storage; } public int getEmptyStorage() { assert isEmptyType(); return (int) storage; } public PartiallyEmptyArray getPartiallyEmptyStorage() { assert isPartiallyEmptyType(); return (PartiallyEmptyArray) storage; } public Object[] getObjectStorage() { assert isObjectType(); // TODO: `CompilerDirectives.castExact(storage, Object[].class);` can be // used here instead of a ValueProfile (see issue #256). return (Object[]) OBJECT_ARRAY_PROFILE.profile(storage); } public long[] getLongStorage() { assert isLongType(); return (long[]) storage; } public double[] getDoubleStorage() { assert isDoubleType(); return (double[]) storage; } public boolean[] getBooleanStorage() { assert isBooleanType(); return (boolean[]) storage; } public boolean isEmptyType() { return storage instanceof Integer; } public boolean isPartiallyEmptyType() { return storage instanceof PartiallyEmptyArray; } public boolean isObjectType() { return storage.getClass() == Object[].class; } public boolean isLongType() { return storage.getClass() == long[].class; } public boolean isDoubleType() { return storage.getClass() == double[].class; } public boolean isBooleanType() { return storage.getClass() == boolean[].class; } public boolean isSomePrimitiveType() { return isLongType() || isDoubleType() || isBooleanType(); } private static long[] createLong(final Object[] arr) { long[] storage = new long[arr.length]; for (int i = 0; i < arr.length; i++) { storage[i] = (long) arr[i]; } return storage; } private static double[] createDouble(final Object[] arr) { double[] storage = new double[arr.length]; for (int i = 0; i < arr.length; i++) { storage[i] = (double) arr[i]; } return storage; } private static boolean[] createBoolean(final Object[] arr) { boolean[] storage = new boolean[arr.length]; for (int i = 0; i < arr.length; i++) { storage[i] = (boolean) arr[i]; } return storage; } public static final class PartiallyEmptyArray { private final Object[] arr; private int emptyElements; private Type type; public enum Type { EMPTY, PARTIAL_EMPTY, LONG, DOUBLE, BOOLEAN, OBJECT; } public PartiallyEmptyArray(final Type type, final int length, final long idx, final Object val) { // can't specialize this here already, // because keeping track for nils would be to expensive arr = new Object[length]; Arrays.fill(arr, Nil.nilObject); emptyElements = length - 1; arr[(int) idx] = val; this.type = type; } private PartiallyEmptyArray(final PartiallyEmptyArray old) { arr = old.arr.clone(); emptyElements = old.emptyElements; type = old.type; } public Type getType() { return type; } public Object[] getStorage() { return arr; } public void setType(final Type type) { this.type = type; } public int getLength() { return arr.length; } public Object get(final long idx) { return arr[(int) idx]; } public void set(final long idx, final Object val) { arr[(int) idx] = val; } public void incEmptyElements() { emptyElements++; } public void decEmptyElements() { emptyElements } public boolean isFull() { return emptyElements == 0; } public PartiallyEmptyArray copy() { return new PartiallyEmptyArray(this); } } public static class SMutableArray extends SArray { /** * Creates and empty array, using the EMPTY strategy. * * @param length */ public SMutableArray(final long length, final SClass clazz) { super(length, clazz); } public SMutableArray(final Object storage, final SClass clazz) { super(storage, clazz); } public SMutableArray shallowCopy() { Object storageClone; if (isEmptyType()) { storageClone = storage; } else if (isPartiallyEmptyType()) { storageClone = ((PartiallyEmptyArray) storage).copy(); } else if (isBooleanType()) { storageClone = ((boolean[]) storage).clone(); } else if (isDoubleType()) { storageClone = ((double[]) storage).clone(); } else if (isLongType()) { storageClone = ((long[]) storage).clone(); } else { assert isObjectType(); storageClone = ((Object[]) storage).clone(); } return new SMutableArray(storageClone, clazz); } public boolean txEquals(final SMutableArray a) { if (storage.getClass() != a.storage.getClass()) { // TODO: strictly speaking this isn't correct, // there could be long[].equals(Object[]) that is true // but, we are prone to ABA problems, so, I don't think this matters either return false; } if (isEmptyType()) { return true; } else if (isPartiallyEmptyType()) { return Arrays.equals(((PartiallyEmptyArray) storage).arr, ((PartiallyEmptyArray) a.storage).arr); } else if (isBooleanType()) { return Arrays.equals((boolean[]) storage, (boolean[]) a.storage); } else if (isDoubleType()) { return Arrays.equals((double[]) storage, (double[]) a.storage); } else if (isLongType()) { return Arrays.equals((long[]) storage, (long[]) a.storage); } else { assert isObjectType(); return Arrays.equals((Object[]) storage, (Object[]) a.storage); } } public void txSet(final SMutableArray a) { storage = a.storage; } /** * For internal use only, specifically, for SClass. * There we now, it is either empty, or of OBJECT type. * * @param value * @return new mutable array extended by value */ public SArray copyAndExtendWith(final Object value) { Object[] newArr; if (isEmptyType()) { newArr = new Object[] {value}; } else { // if this is not true, this method is used in a wrong context assert isObjectType(); Object[] s = getObjectStorage(); newArr = Arrays.copyOf(s, s.length + 1); newArr[s.length] = value; } return new SMutableArray(newArr, clazz); } @Override public final boolean isValue() { return false; } private void fromEmptyToParticalWithType(final PartiallyEmptyArray.Type type, final long idx, final Object val) { assert type != PartiallyEmptyArray.Type.OBJECT; assert isEmptyType(); this.storage = new PartiallyEmptyArray(type, (int) storage, idx, val); } /** * Transition from the Empty, to the PartiallyEmpty state/strategy. * We don't transition to Partial with Object, because, there is no more * specialization that could be applied. */ public final void transitionFromEmptyToPartiallyEmptyWith(final long idx, final long val) { fromEmptyToParticalWithType(PartiallyEmptyArray.Type.LONG, idx, val); } public final void transitionFromEmptyToPartiallyEmptyWith(final long idx, final double val) { fromEmptyToParticalWithType(PartiallyEmptyArray.Type.DOUBLE, idx, val); } public final void transitionFromEmptyToPartiallyEmptyWith(final long idx, final boolean val) { fromEmptyToParticalWithType(PartiallyEmptyArray.Type.BOOLEAN, idx, val); } public final void transitionToEmpty(final long length) { this.storage = (int) length; } public final void transitionTo(final Object newStorage) { this.storage = newStorage; } public final void transitionToObjectWithAll(final long length, final Object val) { Object[] arr = new Object[(int) length]; Arrays.fill(arr, val); final Object storage = arr; this.storage = storage; } public final void transitionToLongWithAll(final long length, final long val) { long[] arr = new long[(int) length]; Arrays.fill(arr, val); final Object storage = arr; this.storage = storage; } public final void transitionToDoubleWithAll(final long length, final double val) { double[] arr = new double[(int) length]; Arrays.fill(arr, val); final Object storage = arr; this.storage = storage; } public final void transitionToBooleanWithAll(final long length, final boolean val) { boolean[] arr = new boolean[(int) length]; if (val) { Arrays.fill(arr, true); } final Object storage = arr; this.storage = storage; } public final void ifFullOrObjectTransitionPartiallyEmpty() { PartiallyEmptyArray arr = getPartiallyEmptyStorage(); if (arr.isFull()) { if (arr.getType() == PartiallyEmptyArray.Type.LONG) { this.storage = createLong(arr.getStorage()); return; } else if (arr.getType() == PartiallyEmptyArray.Type.DOUBLE) { this.storage = createDouble(arr.getStorage()); return; } else if (arr.getType() == PartiallyEmptyArray.Type.BOOLEAN) { this.storage = createBoolean(arr.getStorage()); return; } } if (arr.getType() == PartiallyEmptyArray.Type.OBJECT) { this.storage = arr.getStorage(); } } } public static final class SImmutableArray extends SArray { public SImmutableArray(final long length, final SClass clazz) { super(length, clazz); } public SImmutableArray(final Object storage, final SClass clazz) { super(storage, clazz); } @Override public boolean isValue() { return true; } } public static final class STransferArray extends SMutableArray { public STransferArray(final long length, final SClass clazz) { super(length, clazz); } public STransferArray(final Object storage, final SClass clazz) { super(storage, clazz); } public STransferArray(final STransferArray old, final SClass clazz) { super(cloneStorage(old), clazz); } private static Object cloneStorage(final STransferArray old) { if (old.isEmptyType()) { return old.storage; } else if (old.isBooleanType()) { return ((boolean[]) old.storage).clone(); } else if (old.isDoubleType()) { return ((double[]) old.storage).clone(); } else if (old.isLongType()) { return ((long[]) old.storage).clone(); } else if (old.isObjectType()) { return ((Object[]) old.storage).clone(); } else if (old.isPartiallyEmptyType()) { return ((PartiallyEmptyArray) old.storage).copy(); } else { CompilerDirectives.transferToInterpreter(); assert false : "Support for some storage type missing?"; throw new NotYetImplementedException(); } } public STransferArray cloneBasics() { return new STransferArray(this, clazz); } } }
package com.emsilabs.emsitether; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Menu; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "USB Tether Notification. ", Snackbar.LENGTH_LONG) .setAction("GO", new View.OnClickListener() { @Override public void onClick(View v) { Intent ngintent = new Intent(); ngintent.setAction(Intent.ACTION_MAIN); ComponentName com = new ComponentName("com.android.settings", "com.android.settings.TetherSettings"); ngintent.setComponent(com); startActivity(ngintent); } }) .show(); } }); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
package org.ovirt.engine.core.bll.quota; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.ovirt.engine.core.common.businessentities.QuotaStorage; import org.ovirt.engine.core.common.businessentities.QuotaVdsGroup; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.common.businessentities.QuotaEnforcementTypeEnum; import org.ovirt.engine.core.common.businessentities.Quota; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.QuotaDAO; import org.ovirt.engine.core.utils.Pair; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class QuotaManagerTest { private static final Guid STORAGE_QUOTA_GLOBAL_NOT_EXCEEDED = new Guid("00000000-0000-0000-0000-000000000011"); private static final Guid STORAGE_QUOTA_GLOBAL_OVER_THRESHOLD = new Guid("00000000-0000-0000-0000-000000000012"); private static final Guid STORAGE_QUOTA_GLOBAL_IN_GRACE = new Guid("00000000-0000-0000-0000-000000000013"); private static final Guid STORAGE_QUOTA_GLOBAL_OVER_GRACE = new Guid("00000000-0000-0000-0000-000000000014"); private static final Guid STORAGE_QUOTA_SPECIFIC_NOT_EXCEEDED = new Guid("00000000-0000-0000-0000-000000000015"); private static final Guid STORAGE_QUOTA_SPECIFIC_OVER_THRESHOLD = new Guid("00000000-0000-0000-0000-000000000016"); private static final Guid STORAGE_QUOTA_SPECIFIC_IN_GRACE = new Guid("00000000-0000-0000-0000-000000000017"); private static final Guid STORAGE_QUOTA_SPECIFIC_OVER_GRACE = new Guid("00000000-0000-0000-0000-000000000018"); private static final Guid VCPU_QUOTA_GLOBAL_NOT_EXCEEDED = new Guid("00000000-0000-0000-0000-000000000021"); private static final Guid VCPU_QUOTA_GLOBAL_OVER_THRESHOLD = new Guid("00000000-0000-0000-0000-000000000022"); private static final Guid VCPU_QUOTA_GLOBAL_IN_GRACE = new Guid("00000000-0000-0000-0000-000000000023"); private static final Guid VCPU_QUOTA_GLOBAL_OVER_GRACE = new Guid("00000000-0000-0000-0000-000000000024"); private static final Guid VCPU_QUOTA_SPECIFIC_NOT_EXCEEDED = new Guid("00000000-0000-0000-0000-000000000025"); private static final Guid VCPU_QUOTA_SPECIFIC_OVER_THRESHOLD = new Guid("00000000-0000-0000-0000-000000000026"); private static final Guid VCPU_QUOTA_SPECIFIC_IN_GRACE = new Guid("00000000-0000-0000-0000-000000000027"); private static final Guid VCPU_QUOTA_SPECIFIC_OVER_GRACE = new Guid("00000000-0000-0000-0000-000000000028"); private static final Guid MEM_QUOTA_GLOBAL_NOT_EXCEEDED = new Guid("00000000-0000-0000-0000-000000000031"); private static final Guid MEM_QUOTA_GLOBAL_OVER_THRESHOLD = new Guid("00000000-0000-0000-0000-000000000032"); private static final Guid MEM_QUOTA_GLOBAL_IN_GRACE = new Guid("00000000-0000-0000-0000-000000000033"); private static final Guid MEM_QUOTA_GLOBAL_OVER_GRACE = new Guid("00000000-0000-0000-0000-000000000034"); private static final Guid MEM_QUOTA_SPECIFIC_NOT_EXCEEDED = new Guid("00000000-0000-0000-0000-000000000035"); private static final Guid MEM_QUOTA_SPECIFIC_OVER_THRESHOLD = new Guid("00000000-0000-0000-0000-000000000036"); private static final Guid MEM_QUOTA_SPECIFIC_IN_GRACE = new Guid("00000000-0000-0000-0000-000000000037"); private static final Guid DESTINATION_GUID = new Guid("00000000-0000-0000-0000-000000002222"); private static final Guid MEM_QUOTA_SPECIFIC_OVER_GRACE = new Guid("00000000-0000-0000-0000-000000000038"); private static final long UNLIMITED_STORAGE = QuotaStorage.UNLIMITED; private static final int UNLIMITED_VCPU = QuotaVdsGroup.UNLIMITED_VCPU; private static final long UNLIMITED_MEM = QuotaVdsGroup.UNLIMITED_MEM; private static final String EXPECTED_EMPTY_CAN_DO_MESSAGE = "Can-Do-Action message was expected to be empty"; private static final String EXPECTED_CAN_DO_MESSAGE = "Can-Do-Action message was expected (result: empty)"; private static final String EXPECTED_NO_AUDIT_LOG_MESSAGE = "No AuditLog massage was expected"; private static final String EXPECTED_AUDIT_LOG_MESSAGE = "AuditLog massage was expected"; @Mock private QuotaDAO quotaDAO; private QuotaManager quotaManager = Mockito.spy(QuotaManager.getInstance()); private storage_pool storage_pool = new storage_pool(); private ArrayList<String> canDoActionMessages = new ArrayList<String>(); private boolean hardEnforcement = true; private boolean auditLogWritten = false; private boolean dbWasCalled = false; @Before public void testSetup() { mockQuotaDAO(); doReturn(quotaDAO).when(quotaManager).getQuotaDAO(); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { if (((Pair)invocation.getArguments()[0]).getFirst() != null) { auditLogWritten = true; } return null; } }).when(quotaManager).auditLog(any(Pair.class)); setStoragePool(); } private void mockQuotaDAO() { when(quotaDAO.getById(STORAGE_QUOTA_GLOBAL_NOT_EXCEEDED)).thenReturn(mockStorageQuotaGlobalNotExceeded()); when(quotaDAO.getById(STORAGE_QUOTA_GLOBAL_OVER_THRESHOLD)).thenReturn(mockStorageQuotaGlobalOverThreshold()); when(quotaDAO.getById(STORAGE_QUOTA_GLOBAL_IN_GRACE)).thenReturn(mockStorageQuotaGlobalInGrace()); when(quotaDAO.getById(STORAGE_QUOTA_GLOBAL_OVER_GRACE)).thenReturn(mockStorageQuotaGlobalOverGrace()); when(quotaDAO.getById(STORAGE_QUOTA_SPECIFIC_NOT_EXCEEDED)).thenReturn(mockStorageQuotaSpecificNotExceeded()); when(quotaDAO.getById(STORAGE_QUOTA_SPECIFIC_OVER_THRESHOLD)).thenReturn(mockStorageQuotaSpecificOverThreshold()); when(quotaDAO.getById(STORAGE_QUOTA_SPECIFIC_IN_GRACE)).thenReturn(mockStorageQuotaSpecificInGrace()); when(quotaDAO.getById(STORAGE_QUOTA_SPECIFIC_OVER_GRACE)).thenReturn(mockStorageQuotaSpecificOverGrace()); when(quotaDAO.getById(VCPU_QUOTA_GLOBAL_NOT_EXCEEDED)).thenReturn(mockVCPUQuotaGlobalNotExceeded()); when(quotaDAO.getById(VCPU_QUOTA_GLOBAL_OVER_THRESHOLD)).thenReturn(mockVCPUQuotaGlobalOverThreshold()); when(quotaDAO.getById(VCPU_QUOTA_GLOBAL_IN_GRACE)).thenReturn(mockVCPUQuotaGlobalInGrace()); when(quotaDAO.getById(VCPU_QUOTA_GLOBAL_OVER_GRACE)).thenReturn(mockVCPUQuotaGlobalOverGrace()); when(quotaDAO.getById(VCPU_QUOTA_SPECIFIC_NOT_EXCEEDED)).thenReturn(mockVCPUQuotaSpecificNotExceeded()); when(quotaDAO.getById(VCPU_QUOTA_SPECIFIC_OVER_THRESHOLD)).thenReturn(mockVCPUQuotaSpecificOverThreshold()); when(quotaDAO.getById(VCPU_QUOTA_SPECIFIC_IN_GRACE)).thenReturn(mockVCPUQuotaSpecificInGrace()); when(quotaDAO.getById(VCPU_QUOTA_SPECIFIC_OVER_GRACE)).thenReturn(mockVCPUQuotaSpecificOverGrace()); when(quotaDAO.getById(MEM_QUOTA_GLOBAL_NOT_EXCEEDED)).thenReturn(mockMemQuotaGlobalNotExceeded()); when(quotaDAO.getById(MEM_QUOTA_GLOBAL_OVER_THRESHOLD)).thenReturn(mockMemQuotaGlobalOverThreshold()); when(quotaDAO.getById(MEM_QUOTA_GLOBAL_IN_GRACE)).thenReturn(mockMemQuotaGlobalInGrace()); when(quotaDAO.getById(MEM_QUOTA_GLOBAL_OVER_GRACE)).thenReturn(mockMemQuotaGlobalOverGrace()); when(quotaDAO.getById(MEM_QUOTA_SPECIFIC_NOT_EXCEEDED)).thenReturn(mockMemQuotaSpecificNotExceeded()); when(quotaDAO.getById(MEM_QUOTA_SPECIFIC_OVER_THRESHOLD)).thenReturn(mockMemQuotaSpecificOverThreshold()); when(quotaDAO.getById(MEM_QUOTA_SPECIFIC_IN_GRACE)).thenReturn(mockMemQuotaSpecificInGrace()); when(quotaDAO.getById(MEM_QUOTA_SPECIFIC_OVER_GRACE)).thenReturn(mockMemQuotaSpecificOverGrace()); } private void setStoragePool() { storage_pool.setQuotaEnforcementType(hardEnforcement ? QuotaEnforcementTypeEnum.HARD_ENFORCEMENT : QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT); storage_pool.setId(new Guid("00000000-0000-0000-0000-000000001111")); } private void assertNotEmptyCanDoActionMessage() { assertTrue(EXPECTED_CAN_DO_MESSAGE, !canDoActionMessages.isEmpty()); canDoActionMessages.clear(); } private void assertEmptyCanDoActionMessage() { assertTrue(EXPECTED_EMPTY_CAN_DO_MESSAGE, canDoActionMessages.isEmpty()); } private void assertAuditLogWritten() { assertTrue(EXPECTED_AUDIT_LOG_MESSAGE, auditLogWritten); auditLogWritten = false; } private void assertAuditLogNotWritten() { assertFalse(EXPECTED_NO_AUDIT_LOG_MESSAGE, auditLogWritten); } @Test public void testValidateAndSetStorageQuotaGlobalNotExceeded() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_GLOBAL_NOT_EXCEEDED, DESTINATION_GUID, 1)); assertTrue(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertEmptyCanDoActionMessage(); assertAuditLogNotWritten(); } @Test public void testValidateAndSetStorageQuotaGlobalOverThreshold() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_GLOBAL_OVER_THRESHOLD, DESTINATION_GUID, 1)); assertTrue(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertEmptyCanDoActionMessage(); assertAuditLogWritten(); } @Test public void testValidateAndSetStorageQuotaGlobalInGrace() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_GLOBAL_IN_GRACE, DESTINATION_GUID, 1)); assertTrue(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertEmptyCanDoActionMessage(); assertAuditLogWritten(); } @Test public void testValidateAndSetStorageQuotaGlobalOverGrace() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_GLOBAL_OVER_GRACE, DESTINATION_GUID, 1)); assertFalse(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertNotEmptyCanDoActionMessage(); assertAuditLogWritten(); } @Test public void testValidateAndSetStorageQuotaSpecificNotExceeded() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_SPECIFIC_NOT_EXCEEDED, DESTINATION_GUID, 1)); assertTrue(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertEmptyCanDoActionMessage(); assertAuditLogNotWritten(); } @Test public void testValidateAndSetStorageQuotaSpecificOverThreshold() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_SPECIFIC_OVER_THRESHOLD, DESTINATION_GUID, 1)); assertTrue(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertEmptyCanDoActionMessage(); assertAuditLogWritten(); } @Test public void testValidateAndSetStorageQuotaSpecificInGrace() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_SPECIFIC_IN_GRACE, DESTINATION_GUID, 1)); assertTrue(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertEmptyCanDoActionMessage(); assertAuditLogWritten(); } @Test public void testValidateAndSetStorageQuotaSpecificOverGrace() throws Exception { List<StorageQuotaValidationParameter> parameters = new ArrayList<StorageQuotaValidationParameter>(); parameters.add(new StorageQuotaValidationParameter(STORAGE_QUOTA_SPECIFIC_OVER_GRACE, DESTINATION_GUID, 1)); assertFalse(quotaManager.validateAndSetStorageQuota(storage_pool, parameters, canDoActionMessages)); assertNotEmptyCanDoActionMessage(); assertAuditLogWritten(); } @Test public void testDecreaseStorageQuota() throws Exception { // TODO } @Test public void testValidateQuotaForStoragePool() throws Exception { // TODO } @Test public void testValidateAndSetClusterQuota() throws Exception { // TODO } @Test public void testGetQuotaListFromParameters() throws Exception { // TODO } @Test public void testRollbackQuota() throws Exception { // TODO } @Test public void testRemoveQuotaFromCache() throws Exception { // TODO } /** * Mock a basic quota. Only the basic data (Id, name, threshold, grace...) is set. * * @return - basic quota with no limitations */ private Quota mockBasicQuota() { dbWasCalled = true; // basic data Quota quota = new Quota(); quota.setId(Guid.NewGuid()); quota.setStoragePoolId(Guid.NewGuid()); quota.setDescription("My Quota description"); quota.setQuotaName("My Quota Name"); quota.setGraceStoragePercentage(20); quota.setGraceVdsGroupPercentage(20); quota.setThresholdStoragePercentage(80); quota.setThresholdVdsGroupPercentage(80); // Enforcement type would be taken from the storage_pool and not from this field. // But in case the storage_pool in null this enforcement will be considered. quota.setQuotaEnforcementType(QuotaEnforcementTypeEnum.HARD_ENFORCEMENT); return quota; } private QuotaStorage getQuotaStorage(long storageSize, double storageSizeUsed) { QuotaStorage storageQuota = new QuotaStorage(); storageQuota.setStorageSizeGB(storageSize); storageQuota.setStorageSizeGBUsage(storageSizeUsed); storageQuota.setStorageId(DESTINATION_GUID); return storageQuota; } private List<QuotaStorage> getQuotaStorages(long storageSize, double storageSizeUsed) { ArrayList<QuotaStorage> quotaStorages = new ArrayList<QuotaStorage>(); quotaStorages.add(getQuotaStorage(UNLIMITED_STORAGE, 0)); quotaStorages.add(getQuotaStorage(50, 5)); quotaStorages.get(0).setStorageId(Guid.NewGuid()); quotaStorages.get(1).setStorageId(Guid.NewGuid()); quotaStorages.add(getQuotaStorage(storageSize, storageSizeUsed)); return quotaStorages; } private QuotaVdsGroup getQuotaVdsGroup(int vCpu, int vCpuUsed, long mem, long memUsed) { QuotaVdsGroup vdsGroupQuota = new QuotaVdsGroup(); vdsGroupQuota.setVirtualCpu(vCpu); vdsGroupQuota.setVirtualCpuUsage(vCpuUsed); vdsGroupQuota.setMemSizeMB(mem); vdsGroupQuota.setMemSizeMBUsage(memUsed); vdsGroupQuota.setVdsGroupId(DESTINATION_GUID); return vdsGroupQuota; } private List<QuotaVdsGroup> getQuotaVdsGroups(int vCpu, int vCpuUsed, long mem, long memUsed) { ArrayList<QuotaVdsGroup> quotaVdsGroups = new ArrayList<QuotaVdsGroup>(); quotaVdsGroups.add(getQuotaVdsGroup(UNLIMITED_VCPU, 0, UNLIMITED_MEM, 0)); quotaVdsGroups.add(getQuotaVdsGroup(10, 2, 1000, 100)); quotaVdsGroups.get(0).setVdsGroupId(Guid.NewGuid()); quotaVdsGroups.get(1).setVdsGroupId(Guid.NewGuid()); quotaVdsGroups.add(getQuotaVdsGroup(vCpu, vCpuUsed, mem, memUsed)); return quotaVdsGroups; } // ///////////////////// Storage global //////////////////////////// /** * Call by Guid: {@literal STORAGE_QUOTA_GLOBAL_NOT_EXCEEDED} */ private Quota mockStorageQuotaGlobalNotExceeded() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_GLOBAL_NOT_EXCEEDED); quota.setGlobalQuotaStorage(getQuotaStorage(100, 9)); return quota; } /** * Call by Guid: {@literal STORAGE_QUOTA_GLOBAL_OVER_THRESHOLD} */ private Quota mockStorageQuotaGlobalOverThreshold() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_GLOBAL_OVER_THRESHOLD); quota.setGlobalQuotaStorage(getQuotaStorage(100, 83)); return quota; } /** * Call by Guid: {@literal STORAGE_QUOTA_GLOBAL_IN_GRACE} */ private Quota mockStorageQuotaGlobalInGrace() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_GLOBAL_IN_GRACE); quota.setGlobalQuotaStorage(getQuotaStorage(100, 104)); return quota; } /** * Call by Guid: {@literal STORAGE_QUOTA_GLOBAL_OVER_GRACE} */ private Quota mockStorageQuotaGlobalOverGrace() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_GLOBAL_OVER_GRACE); quota.setGlobalQuotaStorage(getQuotaStorage(100, 140)); return quota; } // ///////////////////// Storage specific //////////////////////////// /** * Call by Guid: {@literal STORAGE_QUOTA_SPECIFIC_NOT_EXCEEDED} */ private Quota mockStorageQuotaSpecificNotExceeded() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_SPECIFIC_NOT_EXCEEDED); quota.setQuotaStorages(getQuotaStorages(100, 73)); return quota; } /** * Call by Guid: {@literal STORAGE_QUOTA_SPECIFIC_OVER_THRESHOLD} */ private Quota mockStorageQuotaSpecificOverThreshold() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_SPECIFIC_OVER_THRESHOLD); quota.setQuotaStorages(getQuotaStorages(100, 92)); return quota; } /** * Call by Guid: {@literal STORAGE_QUOTA_SPECIFIC_IN_GRACE} */ private Quota mockStorageQuotaSpecificInGrace() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_SPECIFIC_IN_GRACE); quota.setQuotaStorages(getQuotaStorages(100, 103)); return quota; } /** * Call by Guid: {@literal STORAGE_QUOTA_SPECIFIC_OVER_GRACE} */ private Quota mockStorageQuotaSpecificOverGrace() { Quota quota = mockBasicQuota(); quota.setId(STORAGE_QUOTA_SPECIFIC_OVER_GRACE); quota.setQuotaStorages(getQuotaStorages(100, 126)); return quota; } // ///////////////////// VCPU global //////////////////////////// /** * Call by Guid: {@literal VCPU_QUOTA_GLOBAL_NOT_EXCEEDED} */ private Quota mockVCPUQuotaGlobalNotExceeded() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_GLOBAL_NOT_EXCEEDED); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(100, 18, UNLIMITED_MEM, 0)); return quota; } /** * Call by Guid: {@literal VCPU_QUOTA_GLOBAL_OVER_THRESHOLD} */ private Quota mockVCPUQuotaGlobalOverThreshold() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_GLOBAL_OVER_THRESHOLD); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(100, 92, UNLIMITED_MEM, 0)); return quota; } /** * Call by Guid: {@literal VCPU_QUOTA_GLOBAL_IN_GRACE} */ private Quota mockVCPUQuotaGlobalInGrace() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_GLOBAL_IN_GRACE); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(100, 113, UNLIMITED_MEM, 0)); return quota; } /** * Call by Guid: {@literal VCPU_QUOTA_GLOBAL_OVER_GRACE} */ private Quota mockVCPUQuotaGlobalOverGrace() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_GLOBAL_OVER_GRACE); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(100, 132, UNLIMITED_MEM, 0)); return quota; } // ///////////////////// VCPU specific //////////////////////////// /** * Call by Guid: {@literal VCPU_QUOTA_SPECIFIC_NOT_EXCEEDED} */ private Quota mockVCPUQuotaSpecificNotExceeded() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_SPECIFIC_NOT_EXCEEDED); quota.setQuotaVdsGroups(getQuotaVdsGroups(100, 23, UNLIMITED_MEM, 0)); return quota; } /** * Call by Guid: {@literal VCPU_QUOTA_SPECIFIC_OVER_THRESHOLD} */ private Quota mockVCPUQuotaSpecificOverThreshold() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_SPECIFIC_OVER_THRESHOLD); quota.setQuotaVdsGroups(getQuotaVdsGroups(100, 96, UNLIMITED_MEM, 0)); return quota; } /** * Call by Guid: {@literal VCPU_QUOTA_SPECIFIC_IN_GRACE} */ private Quota mockVCPUQuotaSpecificInGrace() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_SPECIFIC_IN_GRACE); quota.setQuotaVdsGroups(getQuotaVdsGroups(100, 105, UNLIMITED_MEM, 0)); return quota; } /** * Call by Guid: {@literal VCPU_QUOTA_SPECIFIC_OVER_GRACE} */ private Quota mockVCPUQuotaSpecificOverGrace() { Quota quota = mockBasicQuota(); quota.setId(VCPU_QUOTA_SPECIFIC_OVER_GRACE); quota.setQuotaVdsGroups(getQuotaVdsGroups(100, 134, UNLIMITED_MEM, 0)); return quota; } // ///////////////////// Mem global //////////////////////////// /** * Call by Guid: {@literal MEM_QUOTA_GLOBAL_NOT_EXCEEDED} */ private Quota mockMemQuotaGlobalNotExceeded() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_GLOBAL_NOT_EXCEEDED); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(UNLIMITED_VCPU, 0, 2048, 512)); return quota; } /** * Call by Guid: {@literal MEM_QUOTA_GLOBAL_OVER_THRESHOLD} */ private Quota mockMemQuotaGlobalOverThreshold() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_GLOBAL_OVER_THRESHOLD); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(UNLIMITED_VCPU, 0, 2048, 1900)); return quota; } /** * Call by Guid: {@literal MEM_QUOTA_GLOBAL_IN_GRACE} */ private Quota mockMemQuotaGlobalInGrace() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_GLOBAL_IN_GRACE); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(UNLIMITED_VCPU, 0, 2048, 2300)); return quota; } /** * Call by Guid: {@literal MEM_QUOTA_GLOBAL_OVER_GRACE} */ private Quota mockMemQuotaGlobalOverGrace() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_GLOBAL_OVER_GRACE); quota.setGlobalQuotaVdsGroup(getQuotaVdsGroup(UNLIMITED_VCPU, 0, 2048, 3000)); return quota; } // ///////////////////// Mem specific //////////////////////////// /** * Call by Guid: {@literal MEM_QUOTA_SPECIFIC_NOT_EXCEEDED} */ private Quota mockMemQuotaSpecificNotExceeded() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_SPECIFIC_NOT_EXCEEDED); quota.setQuotaVdsGroups(getQuotaVdsGroups(UNLIMITED_VCPU, 0, 2048, 512)); return quota; } /** * Call by Guid: {@literal MEM_QUOTA_SPECIFIC_OVER_THRESHOLD} */ private Quota mockMemQuotaSpecificOverThreshold() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_SPECIFIC_OVER_THRESHOLD); quota.setQuotaVdsGroups(getQuotaVdsGroups(UNLIMITED_VCPU, 0, 2048, 2000)); return quota; } /** * Call by Guid: {@literal MEM_QUOTA_SPECIFIC_IN_GRACE} */ private Quota mockMemQuotaSpecificInGrace() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_SPECIFIC_IN_GRACE); quota.setQuotaVdsGroups(getQuotaVdsGroups(UNLIMITED_VCPU, 0, 2048, 2100)); return quota; } /** * Call by Guid: {@literal MEM_QUOTA_SPECIFIC_OVER_GRACE} */ private Quota mockMemQuotaSpecificOverGrace() { Quota quota = mockBasicQuota(); quota.setId(MEM_QUOTA_SPECIFIC_OVER_GRACE); quota.setQuotaVdsGroups(getQuotaVdsGroups(UNLIMITED_VCPU, 0, 2048, 5000)); return quota; } }
package org.cinchapi.concourse; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.cinchapi.concourse.annotate.CompoundOperation; import org.cinchapi.concourse.config.ConcourseConfiguration; import org.cinchapi.concourse.lang.BuildableState; import org.cinchapi.concourse.lang.Criteria; import org.cinchapi.concourse.lang.Translate; import org.cinchapi.concourse.security.ClientSecurity; import org.cinchapi.concourse.thrift.AccessToken; import org.cinchapi.concourse.thrift.ConcourseService; import org.cinchapi.concourse.thrift.Operator; import org.cinchapi.concourse.thrift.TObject; import org.cinchapi.concourse.thrift.TTransactionException; import org.cinchapi.concourse.thrift.TransactionToken; import org.cinchapi.concourse.time.Time; import org.cinchapi.concourse.util.Convert; import org.cinchapi.concourse.util.TLinkedTableMap; import org.cinchapi.concourse.util.Timestamps; import org.cinchapi.concourse.util.Transformers; import org.cinchapi.concourse.util.TLinkedHashMap; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * <p> * Concourse is a schemaless and distributed version control database with * automatic indexing, acid transactions and full-text search. Concourse * provides a more intuitive approach to data management that is easy to deploy, * access and scale with minimal tuning while also maintaining the referential * integrity and ACID characteristics of traditional database systems. * </p> * <h2>Data Model</h2> * <p> * The Concourse data model is lightweight and flexible. Unlike other databases, * Concourse is completely schemaless and does not hold data in tables or * collections. Instead, Concourse is simply a distributed graph of records. * Each record has multiple keys. And each key has one or more distinct values. * Like any graph, you can link records to one another. And the structure of one * record does not affect the structure of another. * </p> * <p> * <ul> * <li><strong>Record</strong> &mdash; A logical grouping of data about a single * person, place, or thing (i.e. an object). Each {@code record} is a collection * of key/value pairs that are together identified by a unique primary key. * <li><strong>Key</strong> &mdash; An attribute that maps to a set of * <em>one or more</em> distinct {@code values}. A {@code record} can have many * different {@code keys}, and the {@code keys} in one {@code record} do not * affect those in another {@code record}. * <li><strong>Value</strong> &mdash; A dynamically typed quantity that is * associated with a {@code key} in a {@code record}. * </ul> * </p> * <h4>Data Types</h4> * <p> * Concourse natively stores most of the Java primitives: boolean, double, * float, integer, long, and string (UTF-8). Otherwise, the value of the * {@link #toString()} method for the Object is stored. * </p> * <h4>Links</h4> * <p> * Concourse supports linking a {@code key} in one {@code record} to another * {@code record}. Links are one-directional, but it is possible to add two * links that are the inverse of each other to simulate bi-directionality (i.e. * link "friend" in Record 1 to Record 2 and link "friend" in Record 2 to Record * 1). * </p> * <h2>Transactions</h2> * <p> * By default, Concourse conducts every operation in {@code autocommit} mode * where every change is immediately written. Concourse also supports the * ability to stage a group of operations in transactions that are atomic, * consistent, isolated, and durable using the {@link #stage()}, * {@link #commit()} and {@link #abort()} methods. * * </p> * <h2>Thread Safety</h2> * <p> * You should <strong>not</strong> use the same client connection in multiple * threads. If you need to interact with Concourse using multiple threads, you * should create a separate connection for each thread or use a * {@link ConnectionPool}. * </p> * * @author jnelson */ public abstract class Concourse implements AutoCloseable { /** * Create a new Client connection to the environment of the Concourse Server * described in {@code concourse_client.prefs} (or the default environment * and server if the prefs file does not exist) and return a handler to * facilitate database interaction. * * @return the database handler */ public static Concourse connect() { return new Client(); } * /** Create a new Client connection to the specified {@code environment} * of the Concourse Server described in {@code concourse_client.prefs} (or * the default server if the prefs file does not exist) and return a handler * to facilitate database interaction. * * @param environment * @return */ public static Concourse connect(String environment) { return new Client(environment); } /** * Create a new Client connection to the default environment of the * specified Concourse Server and return a handler to facilitate database * interaction. * * @param host * @param port * @param username * @param password * @return the database handler */ public static Concourse connect(String host, int port, String username, String password) { return new Client(host, port, username, password); } /** * Create a new Client connection to the specified {@code environment} of * the specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @param environment * @return the database handler */ public static Concourse connect(String host, int port, String username, String password, String environment) { return new Client(host, port, username, password, environment); } /** * Discard any changes that are currently staged for commit. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be committed immediately. * </p> */ public abstract void abort(); /** * Add {@code key} as {@code value} in each of the {@code records} if it is * not already contained. * * @param key * @param value * @param records * @return a mapping from each record to a boolean indicating if * {@code value} is added */ @CompoundOperation public abstract Map<Long, Boolean> add(String key, Object value, Collection<Long> records); /** * Add {@code key} as {@code value} in a new record and return the primary * key. * * @param key * @param value * @return the primary key of the record in which the data was added */ public abstract <T> long add(String key, T value); /** * Add {@code key} as {@code value} to {@code record} if it is not already * contained. * * @param key * @param value * @param record * @return {@code true} if {@code value} is added */ public abstract <T> boolean add(String key, T value, long record); /** * Audit {@code record} and return a log of revisions. * * @param record * @return a mapping from timestamp to a description of a revision */ public abstract Map<Timestamp, String> audit(long record); /** * Audit {@code key} in {@code record} and return a log of revisions. * * @param key * @param record * @return a mapping from timestamp to a description of a revision */ public abstract Map<Timestamp, String> audit(String key, long record); /** * Browse the {@code records} and return a mapping from each record to all * the data that is contained as a mapping from key name to value set. * * @param records * @return a mapping of all the contained keys and their mapped values in * each record */ public abstract Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records); /** * Browse the {@code records} at {@code timestamp} and return a mapping from * each record to all the data that was contained as a mapping from key name * to value set. * * @param records * @param timestamp * @return a mapping of all the contained keys and their mapped values in * each record */ public abstract Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records, Timestamp timestamp); /** * Browse {@code record} and return all the data that is presently contained * as a mapping from key name to value set. * <p> * <em>This method is the atomic equivalent of calling * {@code fetch(describe(record), record)}</em> * </p> * * @param record * @return a mapping of all the presently contained keys and their mapped * values */ public abstract Map<String, Set<Object>> browse(long record); /** * Browse {@code record} at {@code timestamp} and return all the data that * was contained as a mapping from key name to value set. * <p> * <em>This method is the atomic equivalent of calling * {@code fetch(describe(record, timestamp), record, timestamp)}</em> * </p> * * @param record * @param timestamp * @return a mapping of all the contained keys and their mapped values */ public abstract Map<String, Set<Object>> browse(long record, Timestamp timestamp); /** * Browse {@code key} and return all the data that is indexed as a mapping * from value to the set of records containing the value for {@code key}. * * @param key * @return a mapping of all the indexed values and their associated records. */ public abstract Map<Object, Set<Long>> browse(String key); /** * Browse {@code key} at {@code timestamp} and return all the data that was * indexed as a mapping from value to the set of records that contained the * value for {@code key} . * * @param key * @param timestamp * @return a mapping of all the indexed values and their associated records. */ public abstract Map<Object, Set<Long>> browse(String key, Timestamp timestamp); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * and return a mapping from each timestamp to the non-empty set of values. * * @param key * @param record * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record */ public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * from {@code start} timestamp inclusively to present and return a mapping * from each timestamp to the non-emtpy set of values. * * @param key * @param record * @param start * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record from specified start * timestamp to present */ @CompoundOperation public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * from {@code start} timestamp inclusively to {@code end} timestamp * exclusively and return a mapping from each timestamp to the non-empty set * of values. * * @param key * @param record * @param start * @param end * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record from specified start * timestamp to specified end timestamp */ @CompoundOperation public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start, Timestamp end); /** * Clear every {@code key} and contained value in each of the * {@code records} by removing every value for each {@code key} in each * record. * * @param records */ @CompoundOperation public abstract void clear(Collection<Long> records); /** * Clear each of the {@code keys} in each of the {@code records} by removing * every value for each key in each record. * * @param keys * @param records */ @CompoundOperation public abstract void clear(Collection<String> keys, Collection<Long> records); /** * Clear each of the {@code keys} in {@code record} by removing every value * for each key. * * @param keys * @param record */ @CompoundOperation public abstract void clear(Collection<String> keys, long record); /** * Atomically clear {@code record} by removing each contained key and their * values. * * @param record */ public abstract void clear(long record); /** * Clear {@code key} in each of the {@code records} by removing every value * for {@code key} in each record. * * @param key * @param records */ @CompoundOperation public abstract void clear(String key, Collection<Long> records); /** * Atomically clear {@code key} in {@code record} by removing each contained * value. * * @param record */ public abstract void clear(String key, long record); @Override public final void close() throws Exception { exit(); } /** * Attempt to permanently commit all the currently staged changes. This * function returns {@code true} if and only if all the changes can be * successfully applied. Otherwise, this function returns {@code false} and * all the changes are aborted. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be written immediately. * </p> * * @return {@code true} if all staged changes are successfully committed */ public abstract boolean commit(); /** * Create a new Record and return its Primary Key. * * @return the Primary Key of the new Record */ public abstract long create(); /** * Describe each of the {@code records} and return a mapping from each * record to the keys that currently have at least one value. * * @param records * @return the populated keys in each record */ @CompoundOperation public abstract Map<Long, Set<String>> describe(Collection<Long> records); /** * Describe each of the {@code records} at {@code timestamp} and return a * mapping from each record to the keys that had at least one value. * * @param records * @param timestamp * @return the populated keys in each record at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp); /** * Describe {@code record} and return the keys that currently have at least * one value. * * @param record * @return the populated keys in {@code record} */ public abstract Set<String> describe(long record); /** * Describe {@code record} at {@code timestamp} and return the keys that had * at least one value. * * @param record * @param timestamp * @return the populated keys in {@code record} at {@code timestamp} */ public abstract Set<String> describe(long record, Timestamp timestamp); /** * Close the Client connection. */ public abstract void exit(); /** * Fetch each of the {@code keys} from each of the {@code records} and * return a mapping from each record to a mapping from each key to the * contained values. * * @param keys * @param records * @return the contained values for each of the {@code keys} in each of the * {@code records} */ @CompoundOperation public abstract Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records); /** * Fetch each of the {@code keys} from each of the {@code records} at * {@code timestamp} and return a mapping from each record to a mapping from * each key to the contained values. * * @param keys * @param records * @param timestamp * @return the contained values for each of the {@code keys} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Fetch each of the {@code keys} from {@code record} and return a mapping * from each key to the contained values. * * @param keys * @param record * @return the contained values for each of the {@code keys} in * {@code record} */ @CompoundOperation public abstract Map<String, Set<Object>> fetch(Collection<String> keys, long record); /** * Fetch each of the {@code keys} from {@code record} at {@code timestamp} * and return a mapping from each key to the contained values. * * @param keys * @param record * @param timestamp * @return the contained values for each of the {@code keys} in * {@code record} at {@code timestamp} */ @CompoundOperation public abstract Map<String, Set<Object>> fetch(Collection<String> keys, long record, Timestamp timestamp); /** * Fetch {@code key} from each of the {@code records} and return a mapping * from each record to contained values. * * @param key * @param records * @return the contained values for {@code key} in each {@code record} */ @CompoundOperation public abstract Map<Long, Set<Object>> fetch(String key, Collection<Long> records); /** * Fetch {@code key} from} each of the {@code records} at {@code timestamp} * and return a mapping from each record to the contained values. * * @param key * @param records * @param timestamp * @return the contained values for {@code key} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Set<Object>> fetch(String key, Collection<Long> records, Timestamp timestamp); /** * Fetch {@code key} from {@code record} and return all the contained * values. * * @param key * @param record * @return the contained values */ public abstract Set<Object> fetch(String key, long record); /** * Fetch {@code key} from {@code record} at {@code timestamp} and return the * set of values that were mapped. * * @param key * @param record * @param timestamp * @return the contained values */ public abstract Set<Object> fetch(String key, long record, Timestamp timestamp); /** * Find and return the set of records that satisfy the {@code criteria}. * This is analogous to the SELECT action in SQL. * * @param criteria * @return the records that match the {@code criteria} */ public abstract Set<Long> find(Criteria criteria); /** * Find and return the set of records that satisfy the {@code criteria}. * This is analogous to the SELECT action in SQL. * * @param criteria * @return the records that match the {@code criteria} */ public abstract Set<Long> find(Object criteria); // this method exists in // case the caller // forgets // to called #build() on // the CriteriaBuilder /** * Find {@code key} {@code operator} {@code value} and return the set of * records that satisfy the criteria. This is analogous to the SELECT action * in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value); /** * Find {@code key} {@code operator} {@code value} and {@code value2} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Object value2); /** * Find {@code key} {@code operator} {@code value} and {@code value2} at * {@code timestamp} and return the set of records that satisfy the * criteria. This is analogous to the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @param timestamp * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Object value2, Timestamp timestamp); /** * Find {@code key} {@code operator} {@code value} at {@code timestamp} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Timestamp timestamp); /** * Get each of the {@code keys} from each of the {@code records} and return * a mapping from each record to a mapping of each key to the first * contained value. * * @param keys * @param records * @return the first contained value for each of the {@code keys} in each of * the {@code records} */ @CompoundOperation public abstract Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records); /** * Get each of the {@code keys} from each of the {@code records} at * {@code timestamp} and return a mapping from each record to a mapping of * each key to the first contained value. * * @param keys * @param records * @param timestamp * @return the first contained value for each of the {@code keys} in each of * the {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Get each of the {@code keys} from {@code record} and return a mapping * from each key to the first contained value. * * @param keys * @param record * @return the first contained value for each of the {@code keys} in * {@code record} */ @CompoundOperation public abstract Map<String, Object> get(Collection<String> keys, long record); /** * Get each of the {@code keys} from {@code record} at {@code timestamp} and * return a mapping from each key to the first contained value. * * @param keys * @param record * @param timestamp * @return the first contained value for each of the {@code keys} in * {@code record} at {@code timestamp} */ @CompoundOperation public abstract Map<String, Object> get(Collection<String> keys, long record, Timestamp timestamp); /** * Get {@code key} from each of the {@code records} and return a mapping * from each record to the first contained value. * * @param key * @param records * @return the first contained value for {@code key} in each of the * {@code records} */ @CompoundOperation public abstract Map<Long, Object> get(String key, Collection<Long> records); /** * Get {@code key} from each of the {@code records} at {@code timestamp} and * return a mapping from each record to the first contained value. * * @param key * @param records * @param timestamp * @return the first contained value for {@code key} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Object> get(String key, Collection<Long> records, Timestamp timestamp); /** * Get {@code key} from {@code record} and return the first contained value * or {@code null} if there is none. Compared to * {@link #fetch(String, long)}, this method is suited for cases when the * caller is certain that {@code key} in {@code record} maps to a single * value of type {@code T}. * * @param key * @param record * @return the first contained value */ public abstract <T> T get(String key, long record); /** * Get {@code key} from {@code record} at {@code timestamp} and return the * first contained value or {@code null} if there was none. Compared to * {@link #fetch(String, long, Timestamp)}, this method is suited for cases * when the caller is certain that {@code key} in {@code record} mapped to a * single value of type {@code T} at {@code timestamp}. * * @param key * @param record * @param timestamp * @return the first contained value */ public abstract <T> T get(String key, long record, Timestamp timestamp); /** * Return the environment of the server that is currently in use by this * client. * * @return the server environment */ public abstract String getServerEnvironment(); /** * Return the version of the server to which this client is currently * connected. * * @return the server version */ public abstract String getServerVersion(); /** * Atomically insert the key/value mappings described in the {@code json} * formatted string into a new record. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @return the primary key of the new record or {@code null} if the insert * is unsuccessful */ public abstract long insert(String json); /** * Insert the key/value mappings described in the {@code json} formated * string into each of the {@code records}. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @param records * @return a mapping from each primary key to a boolean describing if the * data was successfully inserted into that record */ @CompoundOperation public abstract Map<Long, Boolean> insert(String json, Collection<Long> records); /** * Atomically insert the key/value mappings described in the {@code json} * formatted string into {@code record}. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @param record * @return {@code true} if the data is inserted into {@code record} */ public abstract boolean insert(String json, long record); /** * Link {@code key} in {@code source} to each of the {@code destinations}. * * @param key * @param source * @param destinations * @return a mapping from each destination to a boolean indicating if the * link was added */ public abstract Map<Long, Boolean> link(String key, long source, Collection<Long> destinations); /** * Link {@code key} in {@code source} to {@code destination}. * * @param key * @param source * @param destination * @return {@code true} if the link is added */ public abstract boolean link(String key, long source, long destination); /** * Ping each of the {@code records}. * * @param records * @return a mapping from each record to a boolean indicating if the record * currently has at least one populated key */ @CompoundOperation public abstract Map<Long, Boolean> ping(Collection<Long> records); /** * Ping {@code record}. * * @param record * @return {@code true} if {@code record} currently has at least one * populated key */ public abstract boolean ping(long record); /** * Remove {@code key} as {@code value} in each of the {@code records} if it * is contained. * * @param key * @param value * @param records * @return a mapping from each record to a boolean indicating if * {@code value} is removed */ @CompoundOperation public abstract Map<Long, Boolean> remove(String key, Object value, Collection<Long> records); /** * Remove {@code key} as {@code value} to {@code record} if it is contained. * * @param key * @param value * @param record * @return {@code true} if {@code value} is removed */ public abstract <T> boolean remove(String key, T value, long record); /** * Revert each of the {@code keys} in each of the {@code records} to * {@code timestamp} by creating new revisions that the relevant changes * that have occurred since {@code timestamp}. * * @param keys * @param records * @param timestamp */ @CompoundOperation public abstract void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Revert each of the {@code keys} in {@code record} to {@code timestamp} by * creating new revisions that the relevant changes that have occurred since * {@code timestamp}. * * @param keys * @param record * @param timestamp */ @CompoundOperation public abstract void revert(Collection<String> keys, long record, Timestamp timestamp); /** * Revert {@code key} in each of the {@code records} to {@code timestamp} by * creating new revisions that the relevant changes that have occurred since * {@code timestamp}. * * @param key * @param records * @param timestamp */ @CompoundOperation public abstract void revert(String key, Collection<Long> records, Timestamp timestamp); /** * Atomically revert {@code key} in {@code record} to {@code timestamp} by * creating new revisions that undo the relevant changes that have occurred * since {@code timestamp}. * * @param key * @param record * @param timestamp */ public abstract void revert(String key, long record, Timestamp timestamp); /** * Search {@code key} for {@code query} and return the set of records that * match. * * @param key * @param query * @return the records that match the query */ public abstract Set<Long> search(String key, String query); /** * Set {@code key} as {@code value} in each of the {@code records}. * * @param key * @param value * @param records */ @CompoundOperation public abstract void set(String key, Object value, Collection<Long> records); /** * Atomically set {@code key} as {@code value} in {@code record}. This is a * convenience method that clears the values for {@code key} and adds * {@code value}. * * @param key * @param value * @param record */ public abstract <T> void set(String key, T value, long record); /** * Turn on {@code staging} mode so that all subsequent changes are collected * in a staging area before possibly being committed. Staged operations are * guaranteed to be reliable, all or nothing units of work that allow * correct recovery from failures and provide isolation between clients so * that Concourse is always in a consistent state (e.g. a transaction). * <p> * After this method returns, all subsequent operations will be done in * {@code staging} mode until either {@link #abort()} or {@link #commit()} * is invoked. * </p> * <p> * All operations that occur within a transaction should be wrapped in a * try-catch block so that transaction exceptions can be caught and the * transaction can be properly aborted. * * <pre> * try { * concourse.stage(); * concourse.get(&quot;foo&quot;, 1); * concourse.add(&quot;foo&quot;, &quot;bar&quot;, 1); * concourse.commit(); * } * catch (TransactionException e) { * concourse.abort(); * } * </pre> * * </p> */ public abstract void stage() throws TransactionException; /** * Remove link from {@code key} in {@code source} to {@code destination}. * * @param key * @param source * @param destination * @return {@code true} if the link is removed */ public abstract boolean unlink(String key, long source, long destination); /** * Verify {@code key} equals {@code value} in {@code record} and return * {@code true} if {@code value} is currently mapped from {@code key} in * {@code record}. * * @param key * @param value * @param record * @return {@code true} if {@code key} equals {@code value} in * {@code record} */ public abstract boolean verify(String key, Object value, long record); /** * Verify {@code key} equaled {@code value} in {@code record} at * {@code timestamp} and return {@code true} if {@code value} was mapped * from {@code key} in {@code record}. * * @param key * @param value * @param record * @param timestamp * @return {@code true} if {@code key} equaled {@code value} in * {@code record} at {@code timestamp} */ public abstract boolean verify(String key, Object value, long record, Timestamp timestamp); /** * Atomically verify {@code key} equals {@code expected} in {@code record} * and swap with {@code replacement}. * * @param key * @param expected * @param record * @param replacement * @return {@code true} if the swap is successful */ public abstract boolean verifyAndSwap(String key, Object expected, long record, Object replacement); /** * Atomically verify that {@code key} equals {@code expected} in * {@code record} or set it as such. * <p> * Please note that after returning, this method guarantees that {@code key} * in {@code record} will only contain {@code value}, even if {@code value} * already existed alongside other values [e.g. calling verifyOrSet("foo", * "bar", 1) will mean that "foo" in 1 only has "bar" as a value after * returning, even if "foo" in 1 already had "bar", "baz", and "apple" as * values]. * </p> * <p> * <em>So, basically, this function has the same guarantee as the * {@link #set(String, Object, long)} method, except it will not create any * new revisions unless it is necessary to do so.</em> The {@code set} * method, on the other hand, would indiscriminately clears all the values * for {@code key} in {@code record} before adding {@code value}, even in * {@code value} already existed. * </p> * <p> * If you want to add a new value if it does not exist while also preserving * other values, you should use the {@link #add(String, Object, long)} * method instead. * </p> * * @param key * @param value * @param record * @return {@code true} if verify and/or set is successful */ public abstract void verifyOrSet(String key, Object value, long record); /** * The implementation of the {@link Concourse} interface that establishes a * connection with the remote server and handles communication. This class * is a more user friendly wrapper around a Thrift * {@link ConcourseService.Client}. * * @author jnelson */ private final static class Client extends Concourse { // NOTE: The configuration variables are static because we want to // guarantee that they are set before the client connection is // constructed. Even though these variables are static, it is still the // case that any changes to the configuration will be picked up // immediately for new client connections. private static String SERVER_HOST; private static int SERVER_PORT; private static String USERNAME; private static String PASSWORD; private static String ENVIRONMENT; static { ConcourseConfiguration config; try { config = ConcourseConfiguration .loadConfig("concourse_client.prefs"); } catch (Exception e) { config = null; } SERVER_HOST = "localhost"; SERVER_PORT = 1717; USERNAME = "admin"; PASSWORD = "admin"; ENVIRONMENT = ""; if(config != null) { SERVER_HOST = config.getString("host", SERVER_HOST); SERVER_PORT = config.getInt("port", SERVER_PORT); USERNAME = config.getString("username", USERNAME); PASSWORD = config.getString("password", PASSWORD); ENVIRONMENT = config.getString("environment", ENVIRONMENT); } } /** * Represents a request to respond to a query using the current state as * opposed to the history. */ private static Timestamp now = Timestamp.fromMicros(0); /** * An encrypted copy of the username passed to the constructor. */ private final ByteBuffer username; /** * An encrypted copy of the password passed to the constructor. */ private final ByteBuffer password; /** * The host of the connection. */ private final String host; /** * The port of the connection. */ private final int port; /** * The environment to which the client is connected. */ private final String environment; /** * The Thrift client that actually handles all RPC communication. */ private final ConcourseService.Client client; /** * The client keeps a copy of its {@link AccessToken} and passes it to * the server for each remote procedure call. The client will * re-authenticate when necessary using the username/password read from * the prefs file. */ private AccessToken creds = null; /** * Whenever the client starts a Transaction, it keeps a * {@link TransactionToken} so that the server can stage the changes in * the appropriate place. */ private TransactionToken transaction = null; /** * Create a new Client connection to the environment of the Concourse * Server described in {@code concourse_client.prefs} (or the default * environment and server if the prefs file does not exist) and return a * handler to facilitate database interaction. */ public Client() { this(ENVIRONMENT); } /** * Create a new Client connection to the specified {@code environment} * of the Concourse Server described in {@code concourse_client.prefs} * (or the default server if the prefs file does not exist) and return a * handler to facilitate database interaction. * * @param environment */ public Client(String environment) { this(SERVER_HOST, SERVER_PORT, USERNAME, PASSWORD, environment); } /** * Create a new Client connection to the default environment of the * specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password */ public Client(String host, int port, String username, String password) { this(host, port, username, password, ""); } /** * Create a new Client connection to the specified {@code environment} * of the specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @param environment */ public Client(String host, int port, String username, String password, String environment) { this.host = host; this.port = port; this.username = ClientSecurity.encrypt(username); this.password = ClientSecurity.encrypt(password); this.environment = environment; final TTransport transport = new TSocket(host, port); try { transport.open(); TProtocol protocol = new TBinaryProtocol(transport); client = new ConcourseService.Client(protocol); authenticate(); Runtime.getRuntime().addShutdownHook(new Thread("shutdown") { @Override public void run() { if(transaction != null && transport.isOpen()) { abort(); } } }); } catch (TTransportException e) { throw new RuntimeException( "Could not connect to the Concourse Server at " + host + ":" + port); } } @Override public void abort() { execute(new Callable<Void>() { @Override public Void call() throws Exception { if(transaction != null) { final TransactionToken token = transaction; transaction = null; client.abort(creds, token, environment); } return null; } }); } @Override public Map<Long, Boolean> add(String key, Object value, Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, add(key, value, record)); } return result; } public <T> long add(final String key, final T value) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Long>() { @Override public Long call() throws Exception { return client.add1(key, Convert.javaToThrift(value), creds, transaction, environment); } }); } else { throw new IllegalArgumentException( "Either your key is blank or value"); } } @Override public <T> boolean add(final String key, final T value, final long record) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.add(key, Convert.javaToThrift(value), record, creds, transaction, environment); } }); } return false; } @Override public Map<Timestamp, String> audit(final long record) { return execute(new Callable<Map<Timestamp, String>>() { @Override public Map<Timestamp, String> call() throws Exception { Map<Long, String> audit = client.audit(record, null, creds, transaction, environment); return ((TLinkedHashMap<Timestamp, String>) Transformers .transformMap(audit, new Function<Long, Timestamp>() { @Override public Timestamp apply(Long input) { return Timestamp.fromMicros(input); } })).setKeyName("DateTime").setValueName( "Revision"); } }); } @Override public Map<Timestamp, String> audit(final String key, final long record) { return execute(new Callable<Map<Timestamp, String>>() { @Override public Map<Timestamp, String> call() throws Exception { Map<Long, String> audit = client.audit(record, key, creds, transaction, environment); return ((TLinkedHashMap<Timestamp, String>) Transformers .transformMap(audit, new Function<Long, Timestamp>() { @Override public Timestamp apply(Long input) { return Timestamp.fromMicros(input); } })).setKeyName("DateTime").setValueName( "Revision"); } }); } @CompoundOperation @Override public Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records) { Map<Long, Map<String, Set<Object>>> data = TLinkedTableMap .newTLinkedTableMap("Record"); for (long record : records) { data.put(record, browse(record, now)); } return data; } @CompoundOperation @Override public Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records, Timestamp timestamp) { Map<Long, Map<String, Set<Object>>> data = TLinkedTableMap .newTLinkedTableMap("Record"); for (long record : records) { data.put(record, browse(record, timestamp)); } return data; } @Override public Map<String, Set<Object>> browse(long record) { return browse(record, now); } @Override public Map<String, Set<Object>> browse(final long record, final Timestamp timestamp) { return execute(new Callable<Map<String, Set<Object>>>() { @Override public Map<String, Set<Object>> call() throws Exception { Map<String, Set<Object>> data = TLinkedHashMap .newTLinkedHashMap("Key", "Values"); for (Entry<String, Set<TObject>> entry : client.browse0( record, timestamp.getMicros(), creds, transaction, environment).entrySet()) { data.put(entry.getKey(), Transformers.transformSet( entry.getValue(), new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } })); } return data; } }); } @Override public Map<Object, Set<Long>> browse(String key) { return browse(key, now); } @Override public Map<Object, Set<Long>> browse(final String key, final Timestamp timestamp) { return execute(new Callable<Map<Object, Set<Long>>>() { @Override public Map<Object, Set<Long>> call() throws Exception { Map<Object, Set<Long>> data = TLinkedHashMap .newTLinkedHashMap(key, "Records"); for (Entry<TObject, Set<Long>> entry : client.browse1(key, timestamp.getMicros(), creds, transaction, environment).entrySet()) { data.put(Convert.thriftToJava(entry.getKey()), entry.getValue()); } return data; } }); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record) { return execute(new Callable<Map<Timestamp, Set<Object>>>() { @Override public Map<Timestamp, Set<Object>> call() throws Exception { Map<Long, Set<TObject>> chronologize = client.chronologize( record, key, creds, transaction, environment); Map<Timestamp, Set<Object>> result = TLinkedHashMap .newTLinkedHashMap("DateTime", "Values"); for (Entry<Long, Set<TObject>> entry : chronologize .entrySet()) { result.put(Timestamp.fromMicros(entry.getKey()), Transformers.transformSet(entry.getValue(), new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert .thriftToJava(input); } })); } return result; } }); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record, final Timestamp start) { return chronologize(key, record, start, Timestamp.now()); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record, final Timestamp start, final Timestamp end) { Preconditions.checkArgument(start.getMicros() <= end.getMicros(), "Start of range cannot be greater than the end"); Map<Timestamp, Set<Object>> result = TLinkedHashMap .newTLinkedHashMap("DateTime", "Values"); Map<Timestamp, Set<Object>> chronology = chronologize(key, record); int index = Timestamps.findNearestSuccessorForTimestamp( chronology.keySet(), start); Entry<Timestamp, Set<Object>> entry = null; if(index > 0) { entry = Iterables.get(chronology.entrySet(), index - 1); result.put(entry.getKey(), entry.getValue()); } for (int i = index; i < chronology.size(); i++) { entry = Iterables.get(chronology.entrySet(), i); if(entry.getKey().getMicros() >= end.getMicros()) { break; } result.put(entry.getKey(), entry.getValue()); } return result; } @Override public void clear(final Collection<Long> records) { for (Long record : records) { clear(record); } } @Override public void clear(Collection<String> keys, Collection<Long> records) { for (long record : records) { for (String key : keys) { clear(key, record); } } } @Override public void clear(Collection<String> keys, long record) { for (String key : keys) { clear(key, record); } } @Override public void clear(final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.clear1(record, creds, transaction, environment); return null; } }); } @Override public void clear(String key, Collection<Long> records) { for (long record : records) { clear(key, record); } } @Override public void clear(final String key, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.clear(key, record, creds, transaction, environment); return null; } }); } @Override public boolean commit() { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final TransactionToken token = transaction; transaction = null; return client.commit(creds, token, environment); } }); } @Override public long create() { return Time.now(); // TODO get a primary key using a plugin } @Override public Map<Long, Set<String>> describe(Collection<Long> records) { Map<Long, Set<String>> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Keys"); for (long record : records) { result.put(record, describe(record)); } return result; } @Override public Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp) { Map<Long, Set<String>> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Keys"); for (long record : records) { result.put(record, describe(record, timestamp)); } return result; } @Override public Set<String> describe(long record) { return describe(record, now); } @Override public Set<String> describe(final long record, final Timestamp timestamp) { return execute(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { return client.describe(record, timestamp.getMicros(), creds, transaction, environment); } }); } @Override public void exit() { client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); } @Override public Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records) { TLinkedTableMap<Long, String, Set<Object>> result = TLinkedTableMap .<Long, String, Set<Object>> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { result.put(record, key, fetch(key, record)); } } return result; } @Override public Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records, Timestamp timestamp) { TLinkedTableMap<Long, String, Set<Object>> result = TLinkedTableMap .<Long, String, Set<Object>> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { result.put(record, key, fetch(key, record, timestamp)); } } return result; } @Override public Map<String, Set<Object>> fetch(Collection<String> keys, long record) { Map<String, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Values"); for (String key : keys) { result.put(key, fetch(key, record)); } return result; } @Override public Map<String, Set<Object>> fetch(Collection<String> keys, long record, Timestamp timestamp) { Map<String, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Values"); for (String key : keys) { result.put(key, fetch(key, record, timestamp)); } return result; } @Override public Map<Long, Set<Object>> fetch(String key, Collection<Long> records) { Map<Long, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { result.put(record, fetch(key, record)); } return result; } @Override public Map<Long, Set<Object>> fetch(String key, Collection<Long> records, Timestamp timestamp) { Map<Long, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { result.put(record, fetch(key, record, timestamp)); } return result; } @Override public Set<Object> fetch(String key, long record) { return fetch(key, record, now); } @Override public Set<Object> fetch(final String key, final long record, final Timestamp timestamp) { return execute(new Callable<Set<Object>>() { @Override public Set<Object> call() throws Exception { Set<TObject> values = client.fetch(key, record, timestamp.getMicros(), creds, transaction, environment); return Transformers.transformSet(values, new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } }); } }); } @Override public Set<Long> find(final Criteria criteria) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find1(Translate.toThrift(criteria), creds, transaction, environment); } }); } @Override public Set<Long> find(Object object) { if(object instanceof BuildableState) { return find(((BuildableState) object).build()); } else { throw new IllegalArgumentException(object + " is not a valid argument for the find method"); } } @Override public Set<Long> find(String key, Operator operator, Object value) { return find(key, operator, value, now); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2) { return find(key, operator, value, value2, now); } @Override public Set<Long> find(final String key, final Operator operator, final Object value, final Object value2, final Timestamp timestamp) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(value, value2), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), timestamp.getMicros(), creds, transaction, environment); } }); } @Override public Set<Long> find(final String key, final Operator operator, final Object value, final Timestamp timestamp) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(value), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), timestamp.getMicros(), creds, transaction, environment); } }); } @Override public Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records) { TLinkedTableMap<Long, String, Object> result = TLinkedTableMap .<Long, String, Object> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { Object value = get(key, record); if(value != null) { result.put(record, key, value); } } } return result; } @Override public Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { TLinkedTableMap<Long, String, Object> result = TLinkedTableMap .<Long, String, Object> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { Object value = get(key, record, timestamp); if(value != null) { result.put(record, key, value); } } } return result; } @Override public Map<String, Object> get(Collection<String> keys, long record) { Map<String, Object> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Value"); for (String key : keys) { Object value = get(key, record); if(value != null) { result.put(key, value); } } return result; } @Override public Map<String, Object> get(Collection<String> keys, long record, Timestamp timestamp) { Map<String, Object> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Value"); for (String key : keys) { Object value = get(key, record, timestamp); if(value != null) { result.put(key, value); } } return result; } @Override public Map<Long, Object> get(String key, Collection<Long> records) { Map<Long, Object> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { Object value = get(key, record); if(value != null) { result.put(record, value); } } return result; } @Override public Map<Long, Object> get(String key, Collection<Long> records, Timestamp timestamp) { Map<Long, Object> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { Object value = get(key, record, timestamp); if(value != null) { result.put(record, value); } } return result; } @Override @Nullable public <T> T get(String key, long record) { return get(key, record, now); } @SuppressWarnings("unchecked") @Override @Nullable public <T> T get(String key, long record, Timestamp timestamp) { Set<Object> values = fetch(key, record, timestamp); if(!values.isEmpty()) { return (T) values.iterator().next(); } return null; } @Override public String getServerEnvironment() { return execute(new Callable<String>() { @Override public String call() throws Exception { return client.getServerEnvironment(creds, transaction, environment); } }); } @Override public String getServerVersion() { return execute(new Callable<String>() { @Override public String call() throws Exception { return client.getServerVersion(); } }); } @Override public long insert(final String json) { return execute(new Callable<Long>() { @Override public Long call() throws Exception { return client .insert1(json, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> insert(String json, Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, insert(json, record)); } return result; } @Override public boolean insert(final String json, final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.insert(json, record, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> link(String key, long source, Collection<Long> destinations) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long destination : destinations) { result.put(destination, link(key, source, destination)); } return result; } @Override public boolean link(String key, long source, long destination) { return add(key, Link.to(destination), source); } @Override public Map<Long, Boolean> ping(Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, ping(record)); } return result; } @Override public boolean ping(final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.ping(record, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> remove(String key, Object value, Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, remove(key, value, record)); } return result; } @Override public <T> boolean remove(final String key, final T value, final long record) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.remove(key, Convert.javaToThrift(value), record, creds, transaction, environment); } }); } return false; } @Override public void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { for (long record : records) { for (String key : keys) { revert(key, record, timestamp); } } } @Override public void revert(Collection<String> keys, long record, Timestamp timestamp) { for (String key : keys) { revert(key, record, timestamp); } } @Override public void revert(String key, Collection<Long> records, Timestamp timestamp) { for (long record : records) { revert(key, record, timestamp); } } @Override public void revert(final String key, final long record, final Timestamp timestamp) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.revert(key, record, timestamp.getMicros(), creds, transaction, environment); return null; } }); } @Override public Set<Long> search(final String key, final String query) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.search(key, query, creds, transaction, environment); } }); } @Override public void set(String key, Object value, Collection<Long> records) { for (long record : records) { set(key, value, record); } } @Override public <T> void set(final String key, final T value, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.set0(key, Convert.javaToThrift(value), record, creds, transaction, environment); return null; } }); } @Override public void stage() throws TransactionException { execute(new Callable<Void>() { @Override public Void call() throws Exception { transaction = client.stage(creds, environment); return null; } }); } @Override public String toString() { return "Connected to " + host + ":" + port + " as " + new String(ClientSecurity.decrypt(username).array()); } @Override public boolean unlink(String key, long source, long destination) { return remove(key, Link.to(destination), source); } @Override public boolean verify(String key, Object value, long record) { return verify(key, value, record, now); } @Override public boolean verify(final String key, final Object value, final long record, final Timestamp timestamp) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verify(key, Convert.javaToThrift(value), record, timestamp.getMicros(), creds, transaction, environment); } }); } @Override public boolean verifyAndSwap(final String key, final Object expected, final long record, final Object replacement) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verifyAndSwap(key, Convert.javaToThrift(expected), record, Convert.javaToThrift(replacement), creds, transaction, environment); } }); } @Override public void verifyOrSet(final String key, final Object value, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.verifyOrSet(key, Convert.javaToThrift(value), record, creds, transaction, environment); return null; } }); } /** * Authenticate the {@link #username} and {@link #password} and populate * {@link #creds} with the appropriate AccessToken. */ private void authenticate() { try { creds = client.login(ClientSecurity.decrypt(username), ClientSecurity.decrypt(password), environment); } catch (TException e) { throw Throwables.propagate(e); } } /** * Execute the task defined in {@code callable}. This method contains * retry logic to handle cases when {@code creds} expires and must be * updated. * * @param callable * @return the task result */ private <T> T execute(Callable<T> callable) { try { return callable.call(); } catch (SecurityException e) { authenticate(); return execute(callable); } catch (TTransactionException e) { throw new TransactionException(); } catch (Exception e) { throw Throwables.propagate(e); } } } }
package com.hrenic.popularmovies.model; import android.os.Parcel; import android.os.Parcelable; import com.hrenic.popularmovies.util.Config; import org.json.JSONException; import org.json.JSONObject; /** * This class represents a movie retrieved from the Movie DB */ public class Movie implements Parcelable { /* JSON keys */ private static final String ORIGINAL_TITLE_KEY = "original_title"; private static final String POSTER_URL_KEY = "poster_path"; private static final String PLOT_SYNOPSIS_KEY = "overview"; private static final String USER_RATING_KEY = "vote_average"; private static final String RELEASE_DATE_KEY = "release_date"; private String originalTitle; private String posterURL; private String plotSynopsis; private double userRating; private String releaseDate; public Movie(JSONObject json) { try { originalTitle = json.getString(ORIGINAL_TITLE_KEY); posterURL = json.getString(POSTER_URL_KEY); plotSynopsis = json.getString(PLOT_SYNOPSIS_KEY); userRating = json.getDouble(USER_RATING_KEY); releaseDate = json.getString(RELEASE_DATE_KEY); } catch (JSONException ex) { throw new IllegalArgumentException(ex); } } private Movie(Parcel source) { originalTitle = source.readString(); posterURL = source.readString(); plotSynopsis = source.readString(); userRating = source.readDouble(); releaseDate = source.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(originalTitle); dest.writeString(posterURL); dest.writeString(plotSynopsis); dest.writeDouble(userRating); dest.writeString(releaseDate); } public static final Parcelable.Creator<Movie> CREATOR = new Creator<Movie>() { @Override public Movie createFromParcel(Parcel source) { return new Movie(source); } @Override public Movie[] newArray(int size) { return new Movie[size]; } }; public String getFullPosterURL() { return Config.MOVIE_DB_POSTER_BASE_URL + Config.DEFAULT_IMAGE_SIZE + posterURL; } public String getOriginalTitle() { return originalTitle; } public String getPosterURL() { return posterURL; } public String getPlotSynopsis() { return plotSynopsis; } public double getUserRating() { return userRating; } public String getReleaseDate() { return releaseDate; } }
package com.noprestige.kanaquiz; import java.util.Random; import java.util.TreeMap; class WeightedList<E> extends TreeMap<Integer, E> { private int maxValue = 0; private static Random rng = new Random(); boolean add(int weight, E element) { this.put(maxValue, element); maxValue += weight; return true; } boolean add(double weight, E element) { return this.add((int) Math.ceil(weight), element); } E remove(int key) { key = this.floorKey(key); E returnValue = super.remove(key); if (returnValue == null) return null; else { int gap = this.higherKey(key) - key; for (Integer thisKey : this.keySet()) if (thisKey >= key) { E currentElement = super.get(thisKey); super.remove(thisKey); super.put(thisKey - gap, currentElement); } return returnValue; } } int count() { return super.size(); } E get(int value) { if (value > maxValue || value < 0) throw new NullPointerException(); else return this.get(this.floorKey(value)); } E getRandom() { return this.get(rng.nextInt(maxValue)); } int maxValue() { return maxValue; } boolean merge(WeightedList<E> list) { for (Integer oldKey : list.keySet()) this.put(this.maxValue + oldKey, list.get(oldKey)); this.maxValue += list.maxValue; return true; } }
package org.openhab.action.xmpp.internal; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.commons.io.IOUtils; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ChatManager; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smackx.filetransfer.FileTransferManager; import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer; import org.jivesoftware.smackx.muc.MultiUserChat; import org.openhab.core.scriptengine.action.ActionDoc; import org.openhab.core.scriptengine.action.ParamDoc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class contains the methods that are made available in scripts and rules for XMPP. * * @author Kai Kreuzer * @since 1.3.0 */ public class XMPP { private static final Logger logger = LoggerFactory.getLogger(XMPP.class); // provide public static methods here /** * Sends a message to an XMPP user. * * @param to the XMPP address to send the message to * @param message the message to send * * @return <code>true</code>, if sending the message has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text="Sends a message to an XMPP user.") static public boolean sendXMPP( @ParamDoc(name="to") String to, @ParamDoc(name="message") String message) { boolean success = false; try { XMPPConnection conn = XMPPConnect.getConnection(); ChatManager chatmanager = ChatManager.getInstanceFor(conn); Chat newChat = chatmanager.createChat(to, null); try { while(message.length()>=2000) { newChat.sendMessage(message.substring(0, 2000)); message = message.substring(2000); } newChat.sendMessage(message); logger.debug("Sent message '{}' to '{}'.", message, to); success = true; } catch (XMPPException e) { logger.warn("Error Delivering block", e); } catch (NotConnectedException e) { logger.warn("Error Delivering block", e); } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; } /** * Sends a message with an attachment to an XMPP user. * * @param to the XMPP address to send the message to * @param message the message to send * @param attachmentUrl a URL string of which the content should be send to the user * * @return <code>true</code>, if sending the message has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text="Sends a message with an attachment to an XMPP user.") static public boolean sendXMPP( @ParamDoc(name="to") String to, @ParamDoc(name="message") String message, @ParamDoc(name="attachmentUrl") String attachmentUrl) { boolean success = false; try { XMPPConnection conn = XMPPConnect.getConnection(); if (attachmentUrl == null) { // send a normal message without an attachment ChatManager chatmanager = ChatManager.getInstanceFor(conn); Chat newChat = chatmanager.createChat(to, new MessageListener() { public void processMessage(Chat chat, Message message) { logger.debug("Received message on XMPP: {}", message.getBody()); } }); try { newChat.sendMessage(message); logger.debug("Sent message '{}' to '{}'.", message, to); success = true; } catch (XMPPException e) { logger.error("Error sending message '{}'", message, e); } catch (NotConnectedException e) { logger.error("Error sending message '{}'", message, e); } } else { // Create the file transfer manager FileTransferManager manager = new FileTransferManager(conn); // Create the outgoing file transfer OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(to); InputStream is = null; try { URL url = new URL(attachmentUrl); // Send the file is = url.openStream(); OutgoingFileTransfer.setResponseTimeout(10000); transfer.sendStream(is, url.getFile(), is.available(), message); logger.debug("Sent message '{}' with attachment '{}' to '{}'.", (Object[]) new String[] { message, attachmentUrl, to }); success = true; } catch (IOException e) { logger.error("Could not open url '{}' for sending it via XMPP", attachmentUrl, e); } finally { IOUtils.closeQuietly(is); } } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; } /** * Sends a message to an XMPP multi user chat. * * @param message the message to send * * @return <code>true</code>, if sending the message has been successful and * <code>false</code> in all other cases. */ @ActionDoc(text="Sends a message to an XMPP multi user chat.") static public boolean chatXMPP( @ParamDoc(name="message") String message) { boolean success = false; try { MultiUserChat chat = XMPPConnect.getChat(); try { while(message.length()>=2000) { chat.sendMessage(message.substring(0, 2000)); message = message.substring(2000); } chat.sendMessage(message); logger.debug("Sent message '{}' to multi user chat.", message); success = true; } catch (XMPPException e) { logger.warn("Error Delivering block", e); } catch (NotConnectedException e) { logger.warn("Error Delivering block", e); } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; } }
package com.noprestige.kanaquiz; import java.util.Random; import java.util.TreeMap; class WeightedList<E> extends TreeMap<Integer, E> { private int maxValue = 0; private static Random rng = new Random(); boolean add(int weight, E element) { this.put(maxValue, element); maxValue += weight; return true; } boolean add(double weight, E element) { return this.add((int) Math.ceil(weight), element); } E remove(int key) { key = this.floorKey(key); E returnValue = super.remove(key); if (returnValue == null) return null; else if (this.higherKey(key) == null) { maxValue = key; return returnValue; } else { Integer thisKey = this.higherKey(key); int gap = thisKey - key; while (thisKey != null) { E currentElement = super.get(thisKey); super.remove(thisKey); super.put(thisKey - gap, currentElement); thisKey = this.higherKey(thisKey); } maxValue -= gap; return returnValue; } } int count() { return super.size(); } E get(int value) { if (value > maxValue || value < 0) throw new NullPointerException(); else return this.get(this.floorKey(value)); } E getRandom() { return this.get(rng.nextInt(maxValue)); } int maxValue() { return maxValue; } boolean merge(WeightedList<E> list) { for (Integer oldKey : list.keySet()) this.put(this.maxValue + oldKey, list.get(oldKey)); this.maxValue += list.maxValue; return true; } }
package org.openhab.ui.internal.chart; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.openhab.core.items.GroupItem; import org.openhab.core.items.Item; import org.openhab.core.items.ItemNotFoundException; import org.openhab.core.library.types.DecimalType; import org.openhab.core.persistence.FilterCriteria; import org.openhab.core.persistence.FilterCriteria.Ordering; import org.openhab.core.persistence.HistoricItem; import org.openhab.core.persistence.PersistenceService; import org.openhab.core.persistence.QueryablePersistenceService; import org.openhab.ui.chart.ChartProvider; import org.openhab.ui.items.ItemUIRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.BasicStroke; import com.xeiam.xchart.Chart; import com.xeiam.xchart.ChartBuilder; import com.xeiam.xchart.Series; import com.xeiam.xchart.SeriesMarker; import com.xeiam.xchart.StyleManager.LegendPosition; /** * This servlet generates time-series charts for a given set of items. It * accepts the following HTTP parameters: * <ul> * <li>w: width in pixels of image to generate</li> * <li>h: height in pixels of image to generate</li> * <li>period: the time span for the x-axis. Value can be * h,4h,8h,12h,D,3D,W,2W,M,2M,4M,Y</li> * <li>items: A comma separated list of item names to display</li> * <li>groups: A comma separated list of group names, whose members should be * displayed</li> * <li>service: The persistence service name. If not supplied the first service * found will be used.</li> * </ul> * * @author Chris Jackson * @since 1.4.0 * */ public class DefaultChartProvider implements ChartProvider { private static final Logger logger = LoggerFactory.getLogger(DefaultChartProvider.class); protected static final Color[] LINECOLORS = new Color[] { Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.ORANGE, Color.CYAN, Color.PINK, Color.DARK_GRAY, Color.YELLOW }; protected static final Color[] AREACOLORS = new Color[] { new Color(255, 0, 0, 30), new Color(0, 255, 0, 30), new Color(0, 0, 255, 30), new Color(255, 0, 255, 30), new Color(255, 128, 0, 30), new Color(0, 255, 255, 30), new Color(255, 0, 128, 30), new Color(255, 128, 128, 30), new Color(255, 255, 0, 30) }; protected ItemUIRegistry itemUIRegistry; static protected Map<String, QueryablePersistenceService> persistenceServices = new HashMap<String, QueryablePersistenceService>(); private int legendPosition = 0; public void setItemUIRegistry(ItemUIRegistry itemUIRegistry) { this.itemUIRegistry = itemUIRegistry; } public void unsetItemUIRegistry(ItemUIRegistry itemUIRegistry) { this.itemUIRegistry = null; } public void addPersistenceService(PersistenceService service) { if (service instanceof QueryablePersistenceService) persistenceServices.put(service.getName(), (QueryablePersistenceService) service); } public void removePersistenceService(PersistenceService service) { persistenceServices.remove(service.getName()); } static public Map<String, QueryablePersistenceService> getPersistenceServices() { return persistenceServices; } protected void activate() { logger.debug("Starting up default chart provider."); } protected void deactivate() { } /** * {@inheritDoc} */ public void destroy() { } public String getName() { return "default"; } @Override public BufferedImage createChart(String service, String theme, Date startTime, Date endTime, int height, int width, String items, String groups) throws ItemNotFoundException, IllegalArgumentException { QueryablePersistenceService persistenceService; int seriesCounter = 0; // Create Chart Chart chart = new ChartBuilder().width(width).height(height).build(); // Define the time axis - the defaults are not very nice long period = (endTime.getTime() - startTime.getTime()) / 1000; String pattern = "HH:mm"; if(period <= 600) // 10 minutes pattern = "mm:ss"; else if(period <= 86400) // 1 day pattern = "HH:mm"; else if(period <= 604800) // 1 week pattern = "EEE d"; else pattern = "d MMM"; chart.getStyleManager().setDatePattern(pattern); chart.getStyleManager().setAxisTickLabelsFont(new Font("SansSerif", Font.PLAIN, 11)); chart.getStyleManager().setChartPadding(5); chart.getStyleManager().setLegendBackgroundColor(Color.LIGHT_GRAY); chart.getStyleManager().setChartBackgroundColor(Color.LIGHT_GRAY); chart.getStyleManager().setXAxisMin(startTime.getTime()); chart.getStyleManager().setXAxisMax(endTime.getTime()); // If a persistence service is specified, find the provider persistenceService = null; if (service != null) { persistenceService = getPersistenceServices().get(service); } else { // Otherwise, just get the first service persistenceService = getPersistenceServices().entrySet().iterator().next().getValue(); } // Did we find a service? if (persistenceService == null) { throw new IllegalArgumentException("Persistence service not found '" + service + "'."); } // Loop through all the items if (items != null) { String[] itemNames = items.split(","); for (String itemName : itemNames) { Item item = itemUIRegistry.getItem(itemName); if(addItem(chart, persistenceService, startTime, endTime, item, seriesCounter)) seriesCounter++; } } // Loop through all the groups and add each item from each group if (groups != null) { String[] groupNames = groups.split(","); for (String groupName : groupNames) { Item item = itemUIRegistry.getItem(groupName); if (item instanceof GroupItem) { GroupItem groupItem = (GroupItem) item; for (Item member : groupItem.getMembers()) { if(addItem(chart, persistenceService, startTime, endTime, member, seriesCounter)) seriesCounter++; } } else { throw new ItemNotFoundException("Item '" + item.getName() + "' defined in groups is not a group."); } } } // If there are no series, render a blank chart if(seriesCounter == 0) { chart.getStyleManager().setLegendVisible(false); Collection<Date> xData = new ArrayList<Date>(); Collection<Number> yData = new ArrayList<Number>(); xData.add(startTime); yData.add(0); xData.add(endTime); yData.add(0); Series series = chart.addDateSeries("NONE", xData, yData); series.setMarker(SeriesMarker.NONE); series.setLineStyle(new BasicStroke(0f)); } // Legend position (top-left or bottom-left) is dynamically selected based on the data // This won't be perfect, but it's a good compromise if(legendPosition < 0) chart.getStyleManager().setLegendPosition(LegendPosition.InsideNW); else chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW); // Write the chart as a PNG image BufferedImage lBufferedImage = new BufferedImage(chart.getWidth(), chart.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D lGraphics2D = lBufferedImage.createGraphics(); chart.paint(lGraphics2D); return lBufferedImage; } boolean addItem(Chart chart, QueryablePersistenceService service, Date timeBegin, Date timeEnd, Item item, int seriesCounter) { Color color = LINECOLORS[seriesCounter % LINECOLORS.length]; // Get the item label String label = null; if (itemUIRegistry != null) { // Get the item label label = itemUIRegistry.getLabel(item.getName()); if (label != null && label.contains("[") && label.contains("]")) { label = label.substring(0, label.indexOf('[')); } } if (label == null) label = item.getName(); // Define the data filter FilterCriteria filter = new FilterCriteria(); filter.setBeginDate(timeBegin); filter.setEndDate(timeEnd); filter.setItemName(item.getName()); filter.setOrdering(Ordering.ASCENDING); // Get the data from the persistence store Iterable<HistoricItem> result = service.query(filter); Iterator<HistoricItem> it = result.iterator(); // Generate data collections Collection<Date> xData = new ArrayList<Date>(); Collection<Number> yData = new ArrayList<Number>(); // Iterate through the data while (it.hasNext()) { HistoricItem historicItem = it.next(); org.openhab.core.types.State state = historicItem.getState(); if (state instanceof DecimalType) { xData.add(historicItem.getTimestamp()); yData.add((DecimalType) state); } } // Add the new series to the chart - only if there's data elements to display if(xData.size() == 0) return false; // If there's only 1 data point, plot it again! if(xData.size() == 1) { xData.add(xData.iterator().next()); yData.add(yData.iterator().next()); } Series series = chart.addDateSeries(label, xData, yData); series.setLineStyle(new BasicStroke(1.5f)); series.setMarker(SeriesMarker.NONE); series.setLineColor(color); // If the start value is below the median, then count legend position down // Otherwise count up. // We use this to decide whether to put the legend in the top or bottom corner. if(yData.iterator().next().floatValue() > ((series.getyMax().floatValue() - series.getyMin().floatValue()) / 2 + series.getyMin().floatValue())) { legendPosition++; } else { legendPosition } return true; } @Override public String getChartType() { return ("png"); } }
package com.veyndan.redditclient; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.ToggleButton; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.Result; import com.twitter.sdk.android.core.TwitterException; import com.twitter.sdk.android.core.models.Tweet; import com.twitter.sdk.android.tweetui.TweetUtils; import com.twitter.sdk.android.tweetui.TweetView; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import rawjava.Reddit; import rawjava.model.Image; import rawjava.model.Link; import rawjava.model.PostHint; import rawjava.model.Source; import rawjava.model.Thing; import rawjava.network.VoteDirection; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.moshi.MoshiConverterFactory; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> { private static final String TAG = "veyndan_PostAdapter"; private static final int TYPE_SELF = 0x0; private static final int TYPE_IMAGE = 0x1; private static final int TYPE_ALBUM = 0x2; private static final int TYPE_LINK = 0x3; private static final int TYPE_LINK_IMAGE = 0x4; private static final int TYPE_TWEET = 0x5; private static final int TYPE_FLAIR_STICKIED = 0x10; private static final int TYPE_FLAIR_NSFW = 0x20; private static final int TYPE_FLAIR_LINK = 0x40; private static final int TYPE_FLAIR_GILDED = 0x80; private final List<Thing<Link>> posts; private final Reddit reddit; private final int width; public PostAdapter(List<Thing<Link>> posts, Reddit reddit, int width) { this.posts = posts; this.reddit = reddit; this.width = width; } @Override public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View v = inflater.inflate(R.layout.post_item, parent, false); ViewStub flairStub = (ViewStub) v.findViewById(R.id.post_flair_stub); ViewStub mediaStub = (ViewStub) v.findViewById(R.id.post_media_stub); switch (viewType % 16) { case TYPE_SELF: break; case TYPE_IMAGE: mediaStub.setLayoutResource(R.layout.post_media_image); mediaStub.inflate(); break; case TYPE_ALBUM: mediaStub.setLayoutResource(R.layout.post_media_album); mediaStub.inflate(); break; case TYPE_LINK: mediaStub.setLayoutResource(R.layout.post_media_link); mediaStub.inflate(); break; case TYPE_LINK_IMAGE: mediaStub.setLayoutResource(R.layout.post_media_link_image); mediaStub.inflate(); break; case TYPE_TWEET: mediaStub.setLayoutResource(R.layout.post_media_tweet); mediaStub.inflate(); break; default: throw new IllegalStateException("Unknown viewType: " + viewType); } if ((viewType & (TYPE_FLAIR_STICKIED | TYPE_FLAIR_NSFW | TYPE_FLAIR_LINK | TYPE_FLAIR_GILDED)) != 0) { LinearLayout flairContainer = (LinearLayout) flairStub.inflate(); if ((viewType & TYPE_FLAIR_STICKIED) == TYPE_FLAIR_STICKIED) { flairContainer.addView(inflater.inflate(R.layout.post_flair_stickied, flairContainer, false)); } if ((viewType & TYPE_FLAIR_NSFW) == TYPE_FLAIR_NSFW) { flairContainer.addView(inflater.inflate(R.layout.post_flair_nsfw, flairContainer, false)); } if ((viewType & TYPE_FLAIR_LINK) == TYPE_FLAIR_LINK) { flairContainer.addView(inflater.inflate(R.layout.post_flair_link, flairContainer, false)); } if ((viewType & TYPE_FLAIR_GILDED) == TYPE_FLAIR_GILDED) { flairContainer.addView(inflater.inflate(R.layout.post_flair_gilded, flairContainer, false)); } } return new PostViewHolder(v); } @Override public void onBindViewHolder(final PostViewHolder holder, int position) { final Thing<Link> post = posts.get(position); final Context context = holder.itemView.getContext(); holder.title.setText(post.data.title); CharSequence age = DateUtils.getRelativeTimeSpanString( TimeUnit.SECONDS.toMillis(post.data.createdUtc), System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT | DateUtils.FORMAT_NO_MONTH_DAY); holder.subtitle.setText(context.getString(R.string.subtitle, post.data.author, age, post.data.subreddit)); int viewType = holder.getItemViewType(); switch (viewType % 16) { case TYPE_SELF: break; case TYPE_IMAGE: assert holder.mediaContainer != null; assert holder.mediaImage != null; assert holder.mediaImageProgress != null; holder.mediaImageProgress.setVisibility(View.VISIBLE); holder.mediaContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Thing<Link> post = posts.get(holder.getAdapterPosition()); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(post.data.url)); context.startActivity(intent); } }); final boolean imageDimensAvailable = !post.data.preview.images.isEmpty(); Glide.with(context) .load(post.data.url) .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { holder.mediaImageProgress.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { holder.mediaImageProgress.setVisibility(View.GONE); if (!imageDimensAvailable) { final Image image = new Image(); image.source = new Source(); image.source.width = resource.getIntrinsicWidth(); image.source.height = resource.getIntrinsicHeight(); post.data.preview.images = new ArrayList<>(); post.data.preview.images.add(image); holder.mediaImage.getLayoutParams().height = (int) ((float) width / image.source.width * image.source.height); } return false; } }) .into(holder.mediaImage); if (imageDimensAvailable) { Source source = post.data.preview.images.get(0).source; holder.mediaImage.getLayoutParams().height = (int) ((float) width / source.width * source.height); } break; case TYPE_ALBUM: assert holder.mediaContainer != null; RecyclerView recyclerView = (RecyclerView) holder.mediaContainer; RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context); recyclerView.setLayoutManager(layoutManager); final List<com.veyndan.redditclient.Image> images = new ArrayList<>(); final AlbumAdapter albumAdapter = new AlbumAdapter(images, width); recyclerView.setAdapter(albumAdapter); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", "Client-ID " + Config.IMGUR_CLIENT_ID) .build(); return chain.proceed(request); } }) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.imgur.com/3/") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create()) .client(client) .build(); ImgurService imgurService = retrofit.create(ImgurService.class); imgurService.album(post.data.url.split("/a/")[1]) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Basic<Album>>() { @Override public void call(Basic<Album> basic) { images.addAll(basic.data.images); albumAdapter.notifyDataSetChanged(); } }); break; case TYPE_TWEET: assert holder.mediaContainer != null; long tweetId = Long.parseLong(post.data.url.substring(post.data.url.indexOf("/status/") + "/status/".length())); TweetUtils.loadTweet(tweetId, new Callback<Tweet>() { @Override public void success(Result<Tweet> result) { ((TweetView) holder.mediaContainer).setTweet(result.data); } @Override public void failure(TwitterException exception) { Log.e(TAG, "Load Tweet failure", exception); } }); break; case TYPE_LINK_IMAGE: assert holder.mediaImage != null; assert holder.mediaImageProgress != null; holder.mediaImageProgress.setVisibility(View.VISIBLE); Source source = post.data.preview.images.get(0).source; Glide.with(context) .load(source.url) .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { holder.mediaImageProgress.setVisibility(View.GONE); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { holder.mediaImageProgress.setVisibility(View.GONE); return false; } }) .into(holder.mediaImage); case TYPE_LINK: assert holder.mediaContainer != null; assert holder.mediaUrl != null; holder.mediaContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Thing<Link> post = posts.get(holder.getAdapterPosition()); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(post.data.url)); context.startActivity(intent); } }); String urlHost; try { urlHost = new URL(post.data.url).getHost(); } catch (MalformedURLException e) { Log.e(TAG, e.getMessage(), e); urlHost = post.data.url; } holder.mediaUrl.setText(urlHost); break; } if ((viewType & TYPE_FLAIR_STICKIED) == TYPE_FLAIR_STICKIED) { assert holder.flairStickied != null; } if ((viewType & TYPE_FLAIR_NSFW) == TYPE_FLAIR_NSFW) { assert holder.flairNsfw != null; } if ((viewType & TYPE_FLAIR_LINK) == TYPE_FLAIR_LINK) { assert holder.flairLink != null; holder.flairLink.setText(post.data.linkFlairText); } if ((viewType & TYPE_FLAIR_GILDED) == TYPE_FLAIR_GILDED) { assert holder.flairGilded != null; holder.flairGilded.setText(String.valueOf(post.data.gilded)); } final String points = context.getResources().getQuantityString(R.plurals.points, post.data.score, post.data.score); final String comments = context.getResources().getQuantityString(R.plurals.comments, post.data.numComments, post.data.numComments); holder.score.setText(context.getString(R.string.score, points, comments)); VoteDirection likes = post.data.getLikes(); holder.upvote.setChecked(likes.equals(VoteDirection.UPVOTE)); holder.upvote.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Ensure that downvote and upvote aren't checked at the same time. if (isChecked) { holder.downvote.setChecked(false); } Thing<Link> post = posts.get(holder.getAdapterPosition()); post.data.setLikes(isChecked ? VoteDirection.UPVOTE : VoteDirection.UNVOTE); reddit.vote(isChecked ? VoteDirection.UPVOTE : VoteDirection.UNVOTE, post.kind + "_" + post.data.id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); post.data.score += isChecked ? 1 : -1; final String points = context.getResources().getQuantityString(R.plurals.points, post.data.score, post.data.score); final String comments = context.getResources().getQuantityString(R.plurals.comments, post.data.numComments, post.data.numComments); holder.score.setText(context.getString(R.string.score, points, comments)); } }); holder.downvote.setChecked(likes.equals(VoteDirection.DOWNVOTE)); holder.downvote.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Ensure that downvote and upvote aren't checked at the same time. if (isChecked) { holder.upvote.setChecked(false); } Thing<Link> post = posts.get(holder.getAdapterPosition()); post.data.setLikes(isChecked ? VoteDirection.DOWNVOTE : VoteDirection.UNVOTE); reddit.vote(isChecked ? VoteDirection.DOWNVOTE : VoteDirection.UNVOTE, post.kind + "_" + post.data.id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); post.data.score += isChecked ? -1 : 1; final String points = context.getResources().getQuantityString(R.plurals.points, post.data.score, post.data.score); final String comments = context.getResources().getQuantityString(R.plurals.comments, post.data.numComments, post.data.numComments); holder.score.setText(context.getString(R.string.score, points, comments)); } }); holder.save.setChecked(post.data.saved); holder.save.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Thing<Link> post = posts.get(holder.getAdapterPosition()); post.data.saved = isChecked; if (isChecked) { reddit.save("", post.kind + "_" + post.data.id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } else { reddit.unsave(post.kind + "_" + post.data.id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } } }); final PopupMenu otherMenu = new PopupMenu(context, holder.other); otherMenu.getMenuInflater().inflate(R.menu.menu_post_other, otherMenu.getMenu()); holder.other.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { otherMenu.show(); } }); otherMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { final int position = holder.getAdapterPosition(); final Thing<Link> post = posts.get(position); switch (item.getItemId()) { case R.id.action_post_hide: final View.OnClickListener undoClickListener = new View.OnClickListener() { @Override public void onClick(View view) { // If undo pressed, then don't follow through with request to hide // the post. posts.add(position, post); notifyItemInserted(position); } }; final Snackbar.Callback snackbarCallback = new Snackbar.Callback() { @Override public void onDismissed(Snackbar snackbar, int event) { super.onDismissed(snackbar, event); // If undo pressed, don't hide post. if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // Chance to undo post hiding has gone, so follow through with // hiding network request. reddit.hide(post.kind + "_" + post.data.id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } } }; Snackbar.make(holder.itemView, R.string.notify_post_hidden, Snackbar.LENGTH_LONG) .setAction(R.string.notify_post_hidden_undo, undoClickListener) .setCallback(snackbarCallback) .show(); // Hide post from list, but make no network request yet. Outcome of the // user's interaction with the snackbar handling will determine this. posts.remove(position); notifyItemRemoved(position); return true; case R.id.action_post_share: return true; case R.id.action_post_profile: return true; case R.id.action_post_subreddit: return true; case R.id.action_post_browser: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(post.data.url)); context.startActivity(intent); return true; case R.id.action_post_report: return true; default: return false; } } }); } @Override public int getItemViewType(int position) { Thing<Link> post = posts.get(position); int viewType; if (post.data.url.contains("imgur.com/") && !post.data.url.contains("/a/") && !post.data.url.contains("/gallery/") && !post.data.url.contains("i.imgur.com")) { post.data.url = post.data.url.replace("imgur.com", "i.imgur.com"); if (!post.data.url.endsWith(".gifv")) { post.data.url += ".png"; } post.data.setPostHint(PostHint.IMAGE); } if (post.data.isSelf) { viewType = TYPE_SELF; } else if (post.data.url.contains("twitter.com")) { viewType = TYPE_TWEET; } else if (post.data.getPostHint().equals(PostHint.IMAGE)) { viewType = TYPE_IMAGE; } else if (post.data.url.contains("/a/")) { viewType = TYPE_ALBUM; } else if (!post.data.preview.images.isEmpty()) { viewType = TYPE_LINK_IMAGE; } else { viewType = TYPE_LINK; } if (post.data.stickied) { viewType += TYPE_FLAIR_STICKIED; } if (post.data.over18) { viewType += TYPE_FLAIR_NSFW; } if (!TextUtils.isEmpty(post.data.linkFlairText)) { viewType += TYPE_FLAIR_LINK; } if (post.data.gilded != 0) { viewType += TYPE_FLAIR_GILDED; } return viewType; } @Override public int getItemCount() { return posts.size(); } public static class PostViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.post_title) TextView title; @BindView(R.id.post_subtitle) TextView subtitle; @BindView(R.id.post_score) TextView score; @BindView(R.id.post_upvote) ToggleButton upvote; @BindView(R.id.post_downvote) ToggleButton downvote; @BindView(R.id.post_save) ToggleButton save; @BindView(R.id.post_other) ImageButton other; // Media: Image // Media: Link // Media: Link Image @Nullable @BindView(R.id.post_media_container) View mediaContainer; // Media: Image // Media: Link Image @Nullable @BindView(R.id.post_media_image) ImageView mediaImage; // Media: Image // Media: Link Image @Nullable @BindView(R.id.post_media_image_progress) ProgressBar mediaImageProgress; // Media: Link // Media: Link Image @Nullable @BindView(R.id.post_media_url) TextView mediaUrl; // Flair: Stickied @Nullable @BindView(R.id.post_flair_stickied) TextView flairStickied; // Flair: NSFW @Nullable @BindView(R.id.post_flair_nsfw) TextView flairNsfw; // Flair: Link @Nullable @BindView(R.id.post_flair_link) TextView flairLink; // Flair: Gilded @Nullable @BindView(R.id.post_flair_gilded) TextView flairGilded; public PostViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
package epcc.ed.ac.uk.gcrf_rear; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.PasswordTransformationMethod; import android.util.Base64; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.ToggleButton; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import epcc.ed.ac.uk.gcrf_rear.data.DatabaseThread; public class MainActivity extends AppCompatActivity implements LocationListener { private DatabaseThread mDatabase; private LocationManager mLocationManager; private static final int DEFAULT_SAMPLING_RATE = 100; // default is 100 Hertz @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDatabase = ((REARApplication)getApplication()).getDatabase(); SharedPreferences settings = getSharedPreferences(SettingsActivity.PREFS_NAME, 0); int rate = settings.getInt(SettingsActivity.FREQUENCY, DEFAULT_SAMPLING_RATE); if (rate <= 0) { rate = DEFAULT_SAMPLING_RATE; } final int samplingPeriod = 1000000 / rate; TextView freqText = (TextView)findViewById(R.id.main_frequency_text); freqText.setText("Frequency: " + rate + " Hertz"); final SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); final Sensor senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); final Sensor senGyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); final Sensor senMagneticField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); if (senAccelerometer == null) { findViewById(R.id.track_accel_checkBox).setVisibility(View.GONE); } if (senGyroscope == null) { findViewById(R.id.track_gyro_checkBox).setVisibility(View.GONE); } if (senMagneticField == null) { findViewById(R.id.track_magnet_checkBox).setVisibility(View.GONE); } final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton); toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { Log.d("main", "sampling period: " + samplingPeriod + " microseconds"); mDatabase.setFileStoreOn(true); if (senAccelerometer != null && ((CheckBox) findViewById(R.id.track_accel_checkBox)).isChecked()) { sensorManager.registerListener((SensorEventListener) getApplication(), senAccelerometer, samplingPeriod); Log.d("main", "registered listener for accelerometer"); } if (senGyroscope != null && ((CheckBox) findViewById(R.id.track_accel_checkBox)).isChecked()) { sensorManager.registerListener((SensorEventListener) getApplication(), senGyroscope, samplingPeriod); Log.d("main", "registered listener for gyroscope"); } if (senMagneticField != null && ((CheckBox) findViewById(R.id.track_accel_checkBox)).isChecked()) { sensorManager.registerListener((SensorEventListener) getApplication(), senMagneticField, samplingPeriod); Log.d("main", "registered listener for magnetic field"); } // mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // try { // mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0l, 0f, MainActivity.this); // catch (SecurityException e) { } else { sensorManager.unregisterListener((SensorEventListener) getApplication()); mDatabase.setFileStoreOn(false); mDatabase.close(); } } }); CheckBox accelCheckBox = (CheckBox) findViewById(R.id.track_accel_checkBox); accelCheckBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sensor sensor = senAccelerometer; if (sensor != null && toggle.isChecked()) { if (((CheckBox) v).isChecked()) { sensorManager.registerListener((SensorEventListener) getApplication(), sensor, samplingPeriod); Log.d("main", "registered listener for accelerometer"); } else { sensorManager.unregisterListener((SensorEventListener) getApplication(), sensor); } } } }); CheckBox gyroCheckBox = (CheckBox) findViewById(R.id.track_gyro_checkBox); gyroCheckBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sensor sensor = senGyroscope; if (sensor != null && toggle.isChecked()) { if (((CheckBox) v).isChecked()) { sensorManager.registerListener((SensorEventListener) getApplication(), sensor, samplingPeriod); Log.d("main", "registered listener for accelerometer"); } else { sensorManager.unregisterListener((SensorEventListener) getApplication(), sensor); } } } }); final CheckBox magnetCheckBox = (CheckBox) findViewById(R.id.track_gyro_checkBox); magnetCheckBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sensor sensor = senMagneticField; if (sensor != null && toggle.isChecked()) { if (((CheckBox) v).isChecked()) { sensorManager.registerListener((SensorEventListener) getApplication(), sensor, samplingPeriod); Log.d("main", "registered listener for accelerometer"); } else { sensorManager.unregisterListener((SensorEventListener) getApplication(), sensor); } } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void registerDevice(String password) { String message = "Device registration failed."; try { URL url = new URL("http://129.215.213.252:8080/gcrfREAR/webapi/gcrf-REAR/register"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.addRequestProperty("Authorization", "Basic " + Base64.encodeToString(("gcrf-REAR:" + password).getBytes(), Base64.NO_WRAP)); conn.connect(); conn.getOutputStream().close(); int status = conn.getResponseCode(); Log.d("register", "Register returned status: " + status); if (status == 200) { InputStream inputStream = conn.getInputStream(); byte[] buf = new byte[1024]; StringBuilder builder = new StringBuilder(); int l; while ((l = inputStream.read(buf)) != -1) { builder.append(new String(buf, 0, l)); } inputStream.close(); Log.d("register", "registered with device id: " + builder.toString()); String deviceID = builder.toString(); SharedPreferences settings = getSharedPreferences(SettingsActivity.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(SettingsActivity.DEVICE_ID, deviceID); editor.commit(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Register Device"); alert.setMessage("Device was registered successfully."); AlertDialog alertDialog = alert.create(); alertDialog.show(); return; } else { if (status == 401) { message += " Unauthorised"; } } } catch (MalformedURLException e) { Log.d("register", "failed to create URL", e); } catch (ProtocolException e) { Log.d("register", "failed to store preference", e); } catch (IOException e) { Log.d("register", "failed to register", e); } AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Register Device"); alert.setMessage(message); AlertDialog alertDialog = alert.create(); alertDialog.show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_display: { Log.d("menu", "Test display selected"); Intent intent = new Intent(this, SensorTestActivity.class); this.startActivity(intent); return true; } case R.id.menu_upload_data: { Log.d("menu", "Upload data selected"); Intent intent = new Intent(this, UploadDataActivity.class); this.startActivity(intent); return true; } case R.id.menu_register: { Log.d("menu", "Register device selected"); AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle("Register Device"); alert.setMessage("Enter password:"); final EditText input = new EditText(MainActivity.this); input.setTransformationMethod(new PasswordTransformationMethod()); alert.setView(input); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = input.getEditableText().toString(); MainActivity.this.registerDevice(password); } }); alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } case R.id.menu_settings: { Log.d("menu", "Settings selected"); Intent intent = new Intent(this, SettingsActivity.class); this.startActivity(intent); return true; } default: return super.onOptionsItemSelected(item); } } @Override public void onLocationChanged(Location location) { Message msg = new Message(); msg.arg1 = DatabaseThread.LOCATION_MSG; msg.obj = location; mDatabase.mHandler.sendMessage(msg); } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } }
package be.ugent.service; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.github.jsonldjava.utils.JsonUtils; import com.google.gson.Gson; import com.mongodb.util.JSON; import be.ugent.Authentication; import be.ugent.TestClass; import be.ugent.dao.HeadacheDao; import be.ugent.dao.PatientDao; import be.ugent.entitity.Headache; import be.ugent.entitity.Location; import be.ugent.entitity.Medicine; import be.ugent.entitity.Pair; import be.ugent.entitity.Patient; @Path("/HeadacheService") public class HeadacheService { HeadacheDao headacheDao = new HeadacheDao(); PatientDao patientDao = new PatientDao(); Gson gson = new Gson(); @GET @Path("/headaches") @Produces({ MediaType.APPLICATION_JSON }) public Response getAllHeadaches( @QueryParam("patientID") String patientID) { System.out.println("Alle hoofdpijnen opgevraagd van patient met id:"+patientID); return Response.ok(headacheDao.getAllHeadachesForPatient(Integer.parseInt(patientID))).build(); } @GET @Path("/headachescount") @Produces({ MediaType.APPLICATION_JSON }) public Response getHeadachesCount() { String message = "Beste,\n\nEr heeft iemand de headachecount geraadpleegd.\n\nMet vriendelijke groet,\n\nDe paashaas"; try { TestClass.generateAndSendEmail("Nieuwe headachecount geraadpleegd",message); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Alle hoofdpijnen opgevraagd"); HashMap<Integer, Integer> countMap = (HashMap<Integer, Integer>) headacheDao.getHeadachesCount(); ArrayList<Integer> patientIDs = new ArrayList<>(countMap.keySet()); Collections.sort(patientIDs); int viable_patients = 0; for (Integer integer : countMap.keySet()) { if(countMap.get(integer)>=5 && integer!=0){ viable_patients++; } } String result = ""; result += "ID\t\tcount\n"; for (Integer i : patientIDs){ result += i+"\t\t"+countMap.get(i)+"\n"; } result+="\n\n\nViable patients: "+viable_patients; // return Response.ok(new PrettyPrintingMap<Integer,Integer>(countMap)).build(); return Response.ok(result).build(); } @GET @Path("/headaches/semantics") @Produces({ MediaType.TEXT_PLAIN }) public Response getHeadacheSemantics(@HeaderParam("Authorization") String header, @QueryParam("patientID") String patientID) { if(patientID == null) return Response.ok(headacheDao.getSemantics("<http://tw06v033.ugent.be/Chronic/rest/HeadacheService/headaches>")).build(); if(patientDao.getPatienFromId(patientID) != null) return Response.ok(headacheDao.getSemantics("<http://tw06v033.ugent.be/Chronic/rest/HeadacheService/headaches?patientID="+patientID+">")).build(); else return Response.status(404).build(); } @Path("/headaches/ld") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON}) public Response getFirstHeadache( @QueryParam("patientID") String patientID) { HeadacheDao headacheDao = new HeadacheDao(); Object jaja = headacheDao.getAllHeadachesForPatient(Integer.parseInt(patientID)).get(0).toJsonLD(); return Response.ok(jaja).build(); } @POST @Path("/headaches") @Consumes({MediaType.APPLICATION_JSON}) public Response addHeadache(String headache, @QueryParam("patientID") String patientID) { // System.out.println("header:"+header); // if(!Authentication.isAuthorized(header)){ // return Response.status(403).build(); if(headache == null || headache.isEmpty() || patientID==null || patientID.isEmpty()){ return Response.status(422).build(); } // if(Integer.parseInt(patientID)!=Authentication.getPatientID(header)){ // return Response.status(403).build(); JSONObject headacheJSON = null; try { headacheJSON = new JSONObject(headache); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if(headacheJSON.getInt("headacheID")>=1){ System.out.println("object:"+headacheJSON); Headache toAdd = new Headache(); try { JSONArray array = headacheJSON.getJSONArray("intensityValues"); for (int i=0; i<array.length(); i++) { JSONObject item = array.getJSONObject(i); System.out.println("Item in intensityValues:"+item.toString()); toAdd.addIntensityValue(item.getString("key"), item.getString("value")); } toAdd.setEnd(headacheJSON.getString("end")); array = headacheJSON.getJSONArray("symptomIDs"); for (int i=0; i<array.length(); i++) { System.out.println("Adding symptomID:"+array.get(i).toString()); toAdd.addSymptomID(Integer.parseInt(array.get(i).toString())); } array = headacheJSON.getJSONArray("triggerIDs"); for (int i=0; i<array.length(); i++) { System.out.println("Adding triggerID:"+array.get(i).toString()); toAdd.addTriggerID(Integer.parseInt(array.get(i).toString())); } JSONObject locations = headacheJSON.getJSONObject("locations"); Iterator it = locations.keys(); while(it.hasNext()){ String loc = ""+it.next(); toAdd.addLocation(new Location(loc.toString(), (boolean)locations.get(loc))); System.out.println("Location: "+loc.toString()+":"+locations.get(""+loc)); it.remove(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Got request to change headache: "+toAdd); toAdd.setHeadacheID(headacheJSON.getInt("headacheID")); System.out.println("Locations: "+Arrays.toString(toAdd.getLocations())); // System.out.println("Created headache: "+JSON.parse(toAdd.toJSON().toString())); //TODO return object with correct ID (now id will not be updated in the return object Patient patient = patientDao.getPatienFromId(patientID); toAdd.setPatientID(Integer.parseInt(patientID)); if(headacheDao.updateHeadacheForPatient(patient, toAdd)){ //return headache successfully created return Response.status(202).entity(toAdd).build(); }else{ // return record was already in database, or was wrong format return Response.status(400).build(); } } } catch (NumberFormatException | JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return Response.status(500).build(); } System.out.println("object:"+headacheJSON); Headache toAdd = new Headache(); try { JSONArray array = headacheJSON.getJSONArray("intensityValues"); for (int i=0; i<array.length(); i++) { JSONObject item = array.getJSONObject(i); System.out.println("Item in intensityValues:"+item.toString()); toAdd.addIntensityValue(item.getString("key"), item.getString("value")); } toAdd.setEnd(headacheJSON.getString("end")); array = headacheJSON.getJSONArray("symptomIDs"); for (int i=0; i<array.length(); i++) { System.out.println("Adding symptomID:"+array.get(i).toString()); toAdd.addSymptomID(Integer.parseInt(array.get(i).toString())); } array = headacheJSON.getJSONArray("triggerIDs"); for (int i=0; i<array.length(); i++) { System.out.println("Adding triggerID:"+array.get(i).toString()); toAdd.addTriggerID(Integer.parseInt(array.get(i).toString())); } JSONObject locations = headacheJSON.getJSONObject("locations"); Iterator it = locations.keys(); while(it.hasNext()){ String loc = ""+it.next(); toAdd.addLocation(new Location(loc.toString(), (boolean)locations.get(loc))); System.out.println("Location: "+loc.toString()+":"+locations.get(""+loc)); it.remove(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Got request to add headache: "+toAdd); String message = "Beste,\n\nEr heeft iemand een nieuwe headache toegevoegd voor patient met patientID "+toAdd.getPatientID()+".\n\nMet vriendelijke groet,\n\nDe paashaas"; try { TestClass.generateAndSendEmail("Nieuwe headache toegevoegd",message); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } toAdd.setHeadacheID(headacheDao.getNewHeadacheID()); System.out.println("Locations: "+Arrays.toString(toAdd.getLocations())); // System.out.println("Created headache: "+JSON.parse(toAdd.toJSON().toString())); //TODO return object with correct ID (now id will not be updated in the return object Patient patient = patientDao.getPatienFromId(patientID); toAdd.setPatientID(Integer.parseInt(patientID)); if(headacheDao.addHeadacheForPatient(patient, toAdd)){ //return headache successfully created return Response.status(201).entity(toAdd).build(); }else{ // return record was already in database, or was wrong format return Response.status(409).build(); } } @DELETE @Path("/headaches/delete") @Consumes({MediaType.APPLICATION_JSON}) public Response deleteHeadache(@QueryParam("headacheID") String headacheID, @HeaderParam("Authorization") String header){ if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } Headache toAdd = headacheDao.getHeadache(Integer.parseInt(headacheID)); if(toAdd == null){ return Response.status(404).build(); } if(Authentication.getPatientID(header) != toAdd.getPatientID()){ return Response.status(403).build(); } if(toAdd == null){ return Response.status(422).build(); } System.out.println("Got request to delete headache: "+gson.toJson(toAdd)); //if it's a headache that is not yet submitted to the database if(toAdd.getHeadacheID()<0){ //headache given is already in database, but with wrong headacheID return Response.status(404).build(); } if(headacheDao.deleteHeadache(toAdd)){ //return headache successfully deleted return Response.status(200).build(); }else{ //return record was already in database, or was wrong format return Response.status(404).build(); } } public class PrettyPrintingMap<K, V> { private Map<K, V> map; public PrettyPrintingMap(Map<K, V> map) { this.map = map; } public String toString() { StringBuilder sb = new StringBuilder(); Iterator<Entry<K, V>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Entry<K, V> entry = iter.next(); sb.append(entry.getKey()); sb.append('=').append('"'); sb.append(entry.getValue()); sb.append('"'); if (iter.hasNext()) { sb.append(',').append(' '); } } return sb.toString(); } } }
package morgan.alex.kittenexplodr; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.graphics.Palette; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.util.ArrayList; import java.util.Collection; import java.util.List; class CatAdapter extends RecyclerView.Adapter<CatAdapter.CatViewHolder> { private final View.OnClickListener onClickListener; private List<KittenModel> kittens; CatAdapter(@NonNull View.OnClickListener onClickListener) { this.onClickListener = onClickListener; this.kittens = new ArrayList<>(); kittens.add(new KittenModel()); kittens.add(new KittenModel()); kittens.add(new KittenModel()); kittens.add(new KittenModel()); this.setHasStableIds(true); } @Override public CatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_cell_cat, parent, false); return new CatViewHolder(view); } @Override public void onBindViewHolder(final CatViewHolder holder, final int position) { final KittenModel kitten = this.kittens.get(position); Picasso.with(holder.itemView.getContext()) .load(kitten.getIamgeUrl()) .placeholder(R.drawable.emoji_cat) .into(holder.target); holder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { view.postDelayed(new Runnable() { @Override public void run() { int adapterPosition = holder.getAdapterPosition(); if (adapterPosition != RecyclerView.NO_POSITION) { kittens.remove(adapterPosition); notifyItemRemoved(adapterPosition); } } }, 0x75); onClickListener.onClick(view); } }); if (!kitten.isExploded()) { this.reset(holder.itemView); } } @Override public long getItemId(int position) { return kittens.get(position).getId(); } private void reset(View root) { if (root instanceof ViewGroup) { ViewGroup parent = (ViewGroup) root; for (int i = 0; i < parent.getChildCount(); i++) { reset(parent.getChildAt(i)); } } else { root.setScaleX(1); root.setScaleY(1); root.setAlpha(1); root.setTranslationX(0.0f); root.setTranslationY(0.0f); } } @Override public int getItemCount() { return kittens.size(); } void addMoreKittens(@NonNull Collection<KittenModel> moreKittens) { int startingSize = kittens.size(); kittens.addAll(moreKittens); this.notifyItemRangeInserted(startingSize, kittens.size() - startingSize); } void reset() { kittens.clear(); kittens.add(new KittenModel()); kittens.add(new KittenModel()); kittens.add(new KittenModel()); kittens.add(new KittenModel()); this.notifyDataSetChanged(); } static class CatViewHolder extends RecyclerView.ViewHolder { ImageView imageView; CardView cardView; Target target; CatViewHolder(final View itemView) { super(itemView); this.imageView = (ImageView) itemView.findViewById(R.id.catImage); this.cardView = (CardView) itemView.findViewById(R.id.card_view); target = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { imageView.setImageBitmap(bitmap); int defaultBackground = ContextCompat.getColor(itemView.getContext(), android.R.color.white); // TODO: it's recommended to generate Palettes on a background thread int background = new Palette.Builder(bitmap).generate().getLightMutedColor(defaultBackground); cardView.setCardBackgroundColor(background); } @Override public void onBitmapFailed(Drawable errorDrawable) { imageView.setImageDrawable(errorDrawable); } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { imageView.setImageDrawable(placeHolderDrawable); } }; } } }
package net.ossrs.sea.rtmp.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.util.Log; import net.ossrs.sea.rtmp.RtmpPublisher; import net.ossrs.sea.rtmp.amf.AmfNull; import net.ossrs.sea.rtmp.amf.AmfNumber; import net.ossrs.sea.rtmp.amf.AmfObject; import net.ossrs.sea.rtmp.packets.Abort; import net.ossrs.sea.rtmp.packets.Acknowledgement; import net.ossrs.sea.rtmp.packets.Handshake; import net.ossrs.sea.rtmp.packets.Command; import net.ossrs.sea.rtmp.packets.Audio; import net.ossrs.sea.rtmp.packets.Video; import net.ossrs.sea.rtmp.packets.UserControl; import net.ossrs.sea.rtmp.packets.RtmpPacket; import net.ossrs.sea.rtmp.packets.WindowAckSize; /** * Main RTMP connection implementation class * * @author francois, leoma */ public class RtmpConnection implements RtmpPublisher, PacketRxHandler, ThreadController { private static final String TAG = "RtmpConnection"; private static final Pattern rtmpUrlPattern = Pattern.compile("^rtmp: private String appName; private String host; private String streamName; private String publishType; private String swfUrl = ""; private String tcUrl = ""; private String pageUrl = ""; private int port; private Socket socket; private RtmpSessionInfo rtmpSessionInfo; private int transactionIdCounter = 0; private static final int SOCKET_CONNECT_TIMEOUT_MS = 3000; private WriteThread writeThread; private final ConcurrentLinkedQueue<RtmpPacket> rxPacketQueue; private final Object rxPacketLock = new Object(); private boolean active = false; private volatile boolean fullyConnected = false; private final Object connectingLock = new Object(); private final Object publishLock = new Object(); private volatile boolean connecting = false; private int currentStreamId = -1; public RtmpConnection(String url) { this.tcUrl = url.substring(0, url.lastIndexOf('/')); Matcher matcher = rtmpUrlPattern.matcher(url); if (matcher.matches()) { this.host = matcher.group(1); String portStr = matcher.group(3); this.port = portStr != null ? Integer.parseInt(portStr) : 1935; this.appName = matcher.group(4); this.streamName = matcher.group(6); rtmpSessionInfo = new RtmpSessionInfo(); rxPacketQueue = new ConcurrentLinkedQueue<RtmpPacket>(); } else { throw new RuntimeException("Invalid RTMP URL. Must be in format: rtmp://host[:port]/application[/streamName]"); } } @Override public void connect() throws IOException { Log.d(TAG, "connect() called. Host: " + host + ", port: " + port + ", appName: " + appName + ", publishPath: " + streamName); socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(host, port); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT_MS); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); Log.d(TAG, "connect(): socket connection established, doing handhake..."); handshake(in, out); active = true; Log.d(TAG, "connect(): handshake done"); ReadThread readThread = new ReadThread(rtmpSessionInfo, in, this, this); writeThread = new WriteThread(rtmpSessionInfo, out, this); readThread.start(); writeThread.start(); // Start the "main" handling thread new Thread(new Runnable() { @Override public void run() { try { Log.d(TAG, "starting main rx handler loop"); handleRxPacketLoop(); } catch (IOException ex) { Logger.getLogger(RtmpConnection.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); rtmpConnect(); } @Override public void publish(String type) throws IllegalStateException, IOException { if (connecting) { synchronized (connectingLock) { try { connectingLock.wait(); } catch (InterruptedException ex) { // do nothing } } } this.publishType = type; createStream(); } private void createStream() { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId != -1) { throw new IllegalStateException("Current stream object has existed"); } Log.d(TAG, "createStream(): Sending releaseStream command..."); // transactionId == 2 Command releaseStream = new Command("releaseStream", ++transactionIdCounter); releaseStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); releaseStream.addData(new AmfNull()); // command object: null for "createStream" releaseStream.addData(streamName); // command object: null for "releaseStream" writeThread.send(releaseStream); Log.d(TAG, "createStream(): Sending FCPublish command..."); // transactionId == 3 Command FCPublish = new Command("FCPublish", ++transactionIdCounter); FCPublish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); FCPublish.addData(new AmfNull()); // command object: null for "FCPublish" FCPublish.addData(streamName); writeThread.send(FCPublish); Log.d(TAG, "createStream(): Sending createStream command..."); final ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_COMMAND_CHANNEL); // transactionId == 4 Command createStream = new Command("createStream", ++transactionIdCounter, chunkStreamInfo); createStream.addData(new AmfNull()); // command object: null for "createStream" writeThread.send(createStream); // Waiting for "publish" command response. synchronized (publishLock) { try { publishLock.wait(); } catch (InterruptedException ex) { // do nothing } } } private void fmlePublish() throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } Log.d(TAG, "fmlePublish(): Sending publish command..."); // transactionId == 0 Command publish = new Command("publish", 0); publish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); publish.getHeader().setMessageStreamId(currentStreamId); publish.addData(new AmfNull()); // command object: null for "publish" publish.addData(streamName); publish.addData(publishType); writeThread.send(publish); } @Override public void closeStream() throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } streamName = null; Log.d(TAG, "closeStream(): setting current stream ID to -1"); currentStreamId = -1; Command closeStream = new Command("closeStream", 0); closeStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_STREAM_CHANNEL); closeStream.getHeader().setMessageStreamId(currentStreamId); closeStream.addData(new AmfNull()); // command object: null for "closeStream" writeThread.send(closeStream); } /** * Performs the RTMP handshake sequence with the server */ private void handshake(InputStream in, OutputStream out) throws IOException { Handshake handshake = new Handshake(); handshake.writeC0(out); handshake.writeC1(out); // Write C1 without waiting for S0 out.flush(); handshake.readS0(in); handshake.readS1(in); handshake.writeC2(out); handshake.readS2(in); } private void rtmpConnect() throws IOException, IllegalStateException { if (fullyConnected || connecting) { throw new IllegalStateException("Already connecting, or connected to RTMP server"); } Log.d(TAG, "rtmpConnect(): Building 'connect' invoke packet"); Command invoke = new Command("connect", ++transactionIdCounter, rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_COMMAND_CHANNEL)); invoke.getHeader().setMessageStreamId(0); AmfObject args = new AmfObject(); args.setProperty("app", appName); args.setProperty("flashVer", "LNX 11,2,202,233"); args.setProperty("swfUrl", swfUrl); args.setProperty("tcUrl", tcUrl); args.setProperty("fpad", false); args.setProperty("capabilities", 239); args.setProperty("audioCodecs", 3575); args.setProperty("videoCodecs", 252); args.setProperty("videoFunction", 1); args.setProperty("pageUrl", pageUrl); args.setProperty("objectEncoding", 0); invoke.addData(args); connecting = true; Log.d(TAG, "rtmpConnect(): Writing 'connect' invoke packet"); invoke.getHeader().setAbsoluteTimestamp(0); writeThread.send(invoke); } @Override public void handleRxPacket(RtmpPacket rtmpPacket) { if (rtmpPacket != null) { rxPacketQueue.add(rtmpPacket); } synchronized (rxPacketLock) { rxPacketLock.notify(); } } private void handleRxPacketLoop() throws IOException { // Handle all queued received RTMP packets while (active) { while (!rxPacketQueue.isEmpty()) { RtmpPacket rtmpPacket = rxPacketQueue.poll(); //Log.d(TAG, "handleRxPacketLoop(): RTMP rx packet message type: " + rtmpPacket.getHeader().getMessageType()); switch (rtmpPacket.getHeader().getMessageType()) { case ABORT: rtmpSessionInfo.getChunkStreamInfo(((Abort) rtmpPacket).getChunkStreamId()).clearStoredChunks(); break; case USER_CONTROL_MESSAGE: { UserControl ping = (UserControl) rtmpPacket; switch (ping.getType()) { case PING_REQUEST: { ChunkStreamInfo channelInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CONTROL_CHANNEL); Log.d(TAG, "handleRxPacketLoop(): Sending PONG reply.."); UserControl pong = new UserControl(ping, channelInfo); writeThread.send(pong); break; } case STREAM_EOF: Log.i(TAG, "handleRxPacketLoop(): Stream EOF reached, closing RTMP writer..."); break; } break; } case WINDOW_ACKNOWLEDGEMENT_SIZE: WindowAckSize windowAckSize = (WindowAckSize) rtmpPacket; Log.d(TAG, "handleRxPacketLoop(): Setting acknowledgement window size to: " + windowAckSize.getAcknowledgementWindowSize()); rtmpSessionInfo.setAcknowledgmentWindowSize(windowAckSize.getAcknowledgementWindowSize()); break; case SET_PEER_BANDWIDTH: int acknowledgementWindowsize = rtmpSessionInfo.getAcknowledgementWindowSize(); final ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CONTROL_CHANNEL); Log.d(TAG, "handleRxPacketLoop(): Send acknowledgement window size: " + acknowledgementWindowsize); writeThread.send(new WindowAckSize(acknowledgementWindowsize, chunkStreamInfo)); break; case COMMAND_AMF0: handleRxInvoke((Command) rtmpPacket); break; default: Log.w(TAG, "handleRxPacketLoop(): Not handling unimplemented/unknown packet of type: " + rtmpPacket.getHeader().getMessageType()); break; } } // Wait for next received packet synchronized (rxPacketLock) { try { rxPacketLock.wait(); } catch (InterruptedException ex) { Log.w(TAG, "handleRxPacketLoop: Interrupted", ex); } } } shutdownImpl(); } private void handleRxInvoke(Command invoke) throws IOException { String commandName = invoke.getCommandName(); if (commandName.equals("_result")) { // This is the result of one of the methods invoked by us String method = rtmpSessionInfo.takeInvokedCommand(invoke.getTransactionId()); Log.d(TAG, "handleRxInvoke: Got result for invoked method: " + method); if ("connect".equals(method)) { // We can now send createStream commands connecting = false; fullyConnected = true; synchronized (connectingLock) { connectingLock.notifyAll(); } } else if ("createStream".contains(method)) { // Get stream id currentStreamId = (int) ((AmfNumber) invoke.getData().get(1)).getValue(); Log.d(TAG, "handleRxInvoke(): Stream ID to publish: " + currentStreamId); if (streamName != null && publishType != null) { fmlePublish(); } } else if ("releaseStream".contains(method)) { Log.d(TAG, "handleRxInvoke(): 'releaseStream'"); } else if ("FCPublish".contains(method)) { Log.d(TAG, "handleRxInvoke(): 'FCPublish'"); } else { Log.w(TAG, "handleRxInvoke(): '_result' message received for unknown method: " + method); } } else if (commandName.equals("onBWDone")) { Log.d(TAG, "handleRxInvoke(): 'onBWDone'"); } else if (commandName.equals("onFCPublish")) { Log.d(TAG, "handleRxInvoke(): 'onFCPublish'"); } else if (commandName.equals("onStatus")) { // NetStream.Publish.Start synchronized (publishLock) { publishLock.notifyAll(); } } else { Log.e(TAG, "handleRxInvoke(): Uknown/unhandled server invoke: " + invoke); } } @Override public void threadHasExited(Thread thread) { shutdown(); } @Override public void shutdown() { active = false; synchronized (rxPacketLock) { rxPacketLock.notify(); } } private void shutdownImpl() { // Shut down read/write threads, if necessary if (Thread.activeCount() > 1) { Log.i(TAG, "shutdown(): Shutting down read/write threads"); Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads); for (Thread thread : threads) { if (thread instanceof ReadThread && thread.isAlive()) { ((ReadThread) thread).shutdown(); } else if (thread instanceof WriteThread && thread.isAlive()) { ((WriteThread) thread).shutdown(); } } } if (socket != null) { try { socket.close(); } catch (Exception ex) { Log.w(TAG, "shutdown(): failed to close socket", ex); } } } @Override public void notifyWindowAckRequired(final int numBytesReadThusFar) { Log.i(TAG, "notifyWindowAckRequired() called"); // Create and send window bytes read acknowledgement writeThread.send(new Acknowledgement(numBytesReadThusFar)); } @Override public void publishVideoData(byte[] data, int dts) throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } Video video = new Video(); video.setData(data); video.getHeader().setMessageStreamId(currentStreamId); video.getHeader().setAbsoluteTimestamp(dts); writeThread.send(video); } @Override public void publishAudioData(byte[] data, int dts) throws IllegalStateException { if (!fullyConnected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == -1) { throw new IllegalStateException("No current stream object exists"); } Audio audio = new Audio(); audio.setData(data); audio.getHeader().setMessageStreamId(currentStreamId); audio.getHeader().setAbsoluteTimestamp(dts); writeThread.send(audio); } }
package org.radarcns.util; import java.util.Deque; import java.util.LinkedList; /** * Get the average of a set of values collected in a sliding time window of fixed duration. * * At least one value is needed to get an average. */ public class RollingTimeAverage { private final long window; private TimeCount firstTime; private double total; private Deque<TimeCount> deque; /** * A rolling time average with a sliding time window of fixed duration. * @param timeWindowMillis duration of the time window. */ public RollingTimeAverage(long timeWindowMillis) { this.window = timeWindowMillis; this.total = 0d; this.firstTime = null; this.deque = new LinkedList<>(); } /** Whether values have already been added. */ public boolean hasAverage() { return firstTime != null; } /** Add a new value. */ public void add(double x) { if (firstTime == null) { firstTime = new TimeCount(x); } else { deque.addLast(new TimeCount(x)); } total += x; } /** Add a value of one. */ public void increment() { add(1d); } /** * Get the average value per second over a sliding time window of fixed size. * * It takes one value before the window started as a baseline, and adds all values in the * window. It then divides by the total time window from the first value (outside/before the * window) to the last value (at the end of the window). * @return average value per second */ public double getAverage() { long now = System.currentTimeMillis(); long currentWindowStart = now - window; if (!hasAverage()) { throw new IllegalStateException("Cannot get average without values"); } while (!this.deque.isEmpty() && this.deque.getFirst().time < currentWindowStart) { total -= this.firstTime.value; this.firstTime = this.deque.removeFirst(); } if (this.deque.isEmpty() || this.firstTime.time >= currentWindowStart) { return 1000d * total / (now - this.firstTime.time); } else { long time = this.deque.getLast().time - currentWindowStart; double removedValue = this.firstTime.value + this.deque.getFirst().value * (currentWindowStart - this.firstTime.time) / (this.deque.getFirst().time - firstTime.time); double value = (total - removedValue) / time; return 1000d * value; } } /** Rounded {@link #getAverage()}. */ public int getCount() { return (int)Math.round(getAverage()); } private static class TimeCount { private final double value; private final long time; TimeCount(double value) { this.value = value; this.time = System.currentTimeMillis(); } } }
package pw.ian.ieee754converter; import android.database.MatrixCursor; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.ToggleButton; import java.text.DecimalFormat; public class MainActivity extends ActionBarActivity { ToggleButton x32; ToggleButton x64; boolean is32Bit = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); x32 = (ToggleButton) findViewById(R.id.x32); x64 = (ToggleButton) findViewById(R.id.x64); x32.setChecked(is32Bit); x32.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { set32Bit(true); } }); x64.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { set32Bit(false); } }); ((EditText) findViewById(R.id.number)).addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { recalculate(); } @Override public void afterTextChanged(Editable s) { } }); } public void set32Bit(boolean value) { final ToggleButton x32 = (ToggleButton) findViewById(R.id.x32); final ToggleButton x64 = (ToggleButton) findViewById(R.id.x64); x32.setChecked(value); x64.setChecked(!value); is32Bit = value; recalculate(); } public void recalculate() { double number; long digits, sign, exponent, mantissa; try { number = Double.parseDouble(((EditText) findViewById(R.id.number)).getText().toString()); } catch (NumberFormatException ex) { // Reset on invalid number number = 0; } digits = is32Bit ? // Get the binary representation Float.floatToRawIntBits((float) number) : Double.doubleToRawLongBits(number); sign = is32Bit ? // first bit ((digits >>> 32 - 1) & 0b1) : ((digits >>> 64 - 1) & 0b1); exponent = is32Bit ? ((digits >>> 32 - 1 - 8) & 0b11111111) : // next 8 bits ((digits >>> 64 - 1 - 11) & 0b11111111111); // next 11 bits mantissa = is32Bit ? (digits & 0x7fffff) : // last 23 bits (digits & 0x1fffffffffffffl); // last 53 bits // Sign String signStr = (sign == 1 ? "-1" : "+1") + "\n" + Long.toBinaryString(sign); ((TextView) findViewById(R.id.sign)).setText(signStr); // Exponent w/ bias int expBias = is32Bit ? 127 : 1023; String expStr = (exponent + " - " + expBias + "= " + (exponent - expBias)) + "\n" // Pad binary string + String.format("%" + (is32Bit ? 8 : 11) + "s", Long.toBinaryString(exponent)).replace(' ', '0'); ((TextView) findViewById(R.id.exponent)).setText(expStr); // Mantissa double unshiftedMantissa = is32Bit ? (Float.intBitsToFloat((0b1111111 << 23) | ((int) mantissa))) : (Double.longBitsToDouble((0b1111111111l << 52) | mantissa)); String manStr = (unshiftedMantissa) + "\n" // Pad binary string + String.format("%" + (is32Bit ? 23 : 52) + "s", Long.toBinaryString(mantissa)).replace(' ', '0'); ((TextView) findViewById(R.id.mantissa)).setText(manStr); // Representations ((TextView) findViewById(R.id.binaryRep)).setText(is32Bit ? String.format("%32s", Integer.toBinaryString(Float.floatToRawIntBits((float) number))).replace(' ', '0') : String.format("%64s", Long.toBinaryString(Double.doubleToRawLongBits(number))).replace(' ', '0')); ((TextView) findViewById(R.id.hexRep)).setText(is32Bit ? String.format("%8s", Integer.toHexString(Float.floatToRawIntBits((float) number))).replace(' ', '0') : String.format("%16s", Long.toHexString(Double.doubleToRawLongBits(number))).replace(' ', '0')); ((TextView) findViewById(R.id.decRep)).setText(is32Bit ? Float.toString((float) number) : Double.toString(number)); } public void reset(View view) { ((TextView) findViewById(R.id.number)).setText(""); recalculate(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
// FILE: c:/projects/jetel/org/jetel/graph/Node.java package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.TreeMap; import org.jetel.data.DataRecord; import org.jetel.enums.EnabledEnum; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.TransformException; import org.jetel.exception.XMLConfigurationException; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.graph.runtime.CloverRuntime; import org.jetel.graph.runtime.ErrorMsgBody; import org.jetel.graph.runtime.Message; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.StringUtils; import org.w3c.dom.Element; /** * A class that represents atomic transformation task. It is a base class for * all kinds of transformation components. * *@author D.Pavlis *@created January 31, 2003 *@since April 2, 2002 *@see org.jetel.component *@revision $Revision$ */ public abstract class Node extends GraphElement implements Runnable { protected Thread nodeThread; protected EnabledEnum enabled; protected int passThroughInputPort; protected int passThroughOutputPort; protected TreeMap outPorts; protected TreeMap inPorts; protected OutputPort logPort; protected volatile boolean runIt = true; protected Result runResult; protected Throwable resultException; protected String resultMessage; protected Phase phase; // buffered values protected List outPortList; protected OutputPort[] outPortsArray; protected int outPortsSize; /** * Various PORT kinds identifiers * *@since August 13, 2002 */ public final static char OUTPUT_PORT = 'O'; /** Description of the Field */ public final static char INPUT_PORT = 'I'; /** Description of the Field */ public final static char LOG_PORT = 'L'; /** * XML attributes of every cloverETL component */ public final static String XML_TYPE_ATTRIBUTE="type"; public final static String XML_ENABLED_ATTRIBUTE="enabled"; /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id, TransformationGraph graph) { super(id,graph); outPorts = new TreeMap(); inPorts = new TreeMap(); logPort = null; phase = null; runResult=Result.N_A; // result is not known yet } /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id){ this(id,null); } @Override public void init() throws ComponentNotReadyException{ super.init(); runResult=Result.READY; } /** * Sets the EOF for particular output port. EOF indicates that no more data * will be sent throught the output port. * *@param portNum The new EOF value *@since April 18, 2002 */ public void setEOF(int portNum) throws InterruptedException { try { ((OutputPort) outPorts.get(new Integer(portNum))).close(); } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); } } /** * Returns the type of this Node (subclasses/Components should override * this method to return appropriate type). * *@return The Type value *@since April 4, 2002 */ public abstract String getType(); /** * Returns True if this Node is Leaf Node - i.e. only consumes data (has only * input ports connected to it) * *@return True if Node is a Leaf *@since April 4, 2002 */ public boolean isLeaf() { if (outPorts.size() == 0) { return true; } else { return false; } } /** * Returns True if this Node is Phase Leaf Node - i.e. only consumes data within * phase it belongs to (has only input ports connected or any connected output ports * connects this Node with Node in different phase) * * @return True if this Node is Phase Leaf */ public boolean isPhaseLeaf(){ Iterator iterator=getOutPorts().iterator(); while(iterator.hasNext()){ if (phase!=((OutputPort)(iterator.next())).getReader().getPhase()) return true; } return false; } /** * Returns True if this node is Root Node - i.e. it produces data (has only output ports * connected to id). * *@return True if Node is a Root *@since April 4, 2002 */ public boolean isRoot() { if (inPorts.size() == 0) { return true; } else { return false; } } /** * Sets the processing phase of the Node object.<br> * Default is 0 (ZERO). * *@param phase The new phase number */ public void setPhase(Phase phase) { this.phase = phase; } /** * Gets the processing phase of the Node object * *@return The phase value */ public Phase getPhase() { return phase; } public int getPhaseNum(){ return phase.getPhaseNum(); } /** * Gets the OutPorts attribute of the Node object * *@return Collection of OutPorts *@since April 18, 2002 */ public Collection<OutputPort> getOutPorts() { return outPorts.values(); } /** * Gets the InPorts attribute of the Node object * *@return Collection of InPorts *@since April 18, 2002 */ public Collection<InputPort> getInPorts() { return inPorts.values(); } /** * Gets the metadata on output ports of the Node object * *@return Collection of output ports metadata */ public Collection<DataRecordMetadata> getOutMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(outPorts.size()); for(Iterator it = getOutPorts().iterator(); it.hasNext();) { ret.add(((OutputPort) (it.next())).getMetadata()); } return ret; } /** * Gets the metadata on input ports of the Node object * *@return Collection of input ports metadata */ public Collection getInMetadata() { List ret = new ArrayList(inPorts.size()); for(Iterator it = getInPorts().iterator(); it.hasNext();) { ret.add(((InputPort) (it.next())).getMetadata()); } return ret; } /** * Gets the number of records passed through specified port type and number * *@param portType Port type (IN, OUT, LOG) *@param portNum port number (0...) *@return The RecordCount value *@since May 17, 2002 */ public int getRecordCount(char portType, int portNum) { int count; // Integer used as key to TreeMap containing ports Integer port = new Integer(portNum); try { switch (portType) { case OUTPUT_PORT: count = ((OutputPort) outPorts.get(port)).getRecordCounter(); break; case INPUT_PORT: count = ((InputPort) inPorts.get(port)).getRecordCounter(); break; case LOG_PORT: if (logPort != null) { count = logPort.getRecordCounter(); } else { count = -1; } break; default: count = -1; } } catch (Exception ex) { count = -1; } return count; } /** * Gets the result code of finished Node.<br> * *@return The Result value *@since July 29, 2002 *@see org.jetel.graph.Node.Result */ public Result getResultCode() { return runResult; } /** * Gets the ResultMsg of finished Node.<br> * This message briefly describes what caused and error (if there was any). * *@return The ResultMsg value *@since July 29, 2002 */ public String getResultMsg() { return runResult!=null ? runResult.message() : null; } /** * Gets exception which caused Node to fail execution - if * there was such failure. * * @return * @since 13.12.2006 */ public Throwable getResultException(){ return resultException; } // Operations /** * main execution method of Node (calls in turn execute()) * *@since April 2, 2002 */ public void run() { runResult=Result.RUNNING; // set running result, so we know run() method was started try { if((runResult = execute()) == Result.ERROR) { Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), resultMessage != null ? resultMessage : runResult.message(), null)); getCloverRuntime().sendMessage(msg); } } catch (IOException ex) { // may be handled differently later runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } catch (InterruptedException ex) { runResult=Result.ABORTED; return; } catch (TransformException ex){ runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), "Error occurred in nested transformation: " + runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } catch (SQLException ex){ runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } catch (Exception ex) { // may be handled differently later runResult=Result.ERROR; resultException = ex; Message msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), ex)); getCloverRuntime().sendMessage(msg); return; } } public abstract Result execute() throws Exception; /** * Abort execution of Node - brutal force * *@since April 4, 2002 */ public void abort() { runIt = false; try { Thread.sleep(50); } catch (InterruptedException e) { //EMPTY INTENTIONALLY } if (runResult==Result.RUNNING){ runResult = Result.ABORTED; getNodeThread().interrupt(); } } /** * @return thread of running node; <b>null</b> if node does not runnig */ public Thread getNodeThread() { if(nodeThread == null) { ThreadGroup defaultThreadGroup = Thread.currentThread().getThreadGroup(); Thread[] activeThreads = new Thread[defaultThreadGroup.activeCount() * 2]; int numThreads = defaultThreadGroup.enumerate(activeThreads, false); for(int i = 0; i < numThreads; i++) { if(activeThreads[i].getName().equals(getId())) { nodeThread = activeThreads[i]; } } } return nodeThread; } /** * Sets actual thread in which this node current running. * @param nodeThread */ public void setNodeThread(Thread nodeThread) { this.nodeThread = nodeThread; } /** * End execution of Node - let Node finish gracefully * *@since April 4, 2002 */ public void end() { runIt = false; } /** * Provides CloverRuntime - object providing * various run-time services * * @return * @since 13.12.2006 */ public CloverRuntime getCloverRuntime(){ return getGraph().getRuntime(); } /** * An operation that adds port to list of all InputPorts * *@param port Port (Input connection) to be added *@since April 2, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ public void addInputPort(InputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } inPorts.put(new Integer(keyVal), port); port.connectReader(this, keyVal); } /** * An operation that adds port to list of all InputPorts * *@param portNum Number to be associated with this port *@param port Port (Input connection) to be added *@since April 2, 2002 */ public void addInputPort(int portNum, InputPort port) { inPorts.put(new Integer(portNum), port); port.connectReader(this, portNum); } /** * An operation that adds port to list of all OutputPorts * *@param port Port (Output connection) to be added *@since April 4, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ public void addOutputPort(OutputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } outPorts.put(new Integer(keyVal), port); port.connectWriter(this, keyVal); resetBufferedValues(); } /** * An operation that adds port to list of all OutputPorts * *@param portNum Number to be associated with this port *@param port The feature to be added to the OutputPort attribute *@since April 4, 2002 */ public void addOutputPort(int portNum, OutputPort port) { outPorts.put(new Integer(portNum), port); port.connectWriter(this, portNum); resetBufferedValues(); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPort getOutputPort(int portNum) { Object outPort=outPorts.get(new Integer(portNum)); if (outPort instanceof OutputPort) { return (OutputPort)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPort interface "+outPort.getClass().getName()); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPortDirect getOutputPortDirect(int portNum) { Object outPort=outPorts.get(new Integer(portNum)); if (outPort instanceof OutputPortDirect) { return (OutputPortDirect)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPortDirect interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPort getInputPort(int portNum) { Object inPort=inPorts.get(new Integer(portNum)); if (inPort instanceof InputPort) { return (InputPort)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPort interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPortDirect getInputPortDirect(int portNum) { Object inPort=inPorts.get(new Integer(portNum)); if (inPort instanceof InputPortDirect) { return (InputPortDirect)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPortDirect interface"); } /** * Removes input port. * @param inputPort */ public void removeInputPort(InputPort inputPort) { inPorts.remove(new Integer(inputPort.getInputPortNumber())); } /** * Removes output port. * @param outputPort */ public void removeOutputPort(OutputPort outputPort) { outPorts.remove(new Integer(outputPort.getOutputPortNumber())); resetBufferedValues(); } /** * Adds a feature to the LogPort attribute of the Node object * *@param port The feature to be added to the LogPort attribute *@since April 4, 2002 */ public void addLogPort(OutputPort port) { logPort = port; port.connectWriter(this, -1); } /** * An operation that does removes/unregisteres por<br> * Not yet implemented. * *@param _portNum Description of Parameter *@param _portType Description of Parameter *@since April 2, 2002 */ public void deletePort(int _portNum, char _portType) { throw new UnsupportedOperationException("Deleting port is not supported !"); } /** * An operation that writes one record through specified output port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's writeRecord() method. * *@param _portNum Description of Parameter *@param _record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecord(int _portNum, DataRecord _record) throws IOException, InterruptedException { ((OutputPort) outPorts.get(new Integer(_portNum))).writeRecord(_record); } /** * An operation that reads one record through specified input port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's readRecord() method. * *@param _portNum Description of Parameter *@param record Description of Parameter *@return Description of the Returned Value *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public DataRecord readRecord(int _portNum, DataRecord record) throws IOException, InterruptedException { return ((InputPort) inPorts.get(new Integer(_portNum))).readRecord(record); } /** * An operation that writes record to Log port * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeLogRecord(DataRecord record) throws IOException, InterruptedException { logPort.writeRecord(record); } /** * An operation that does ... * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecordBroadcast(DataRecord record) throws IOException, InterruptedException { if (outPortsArray == null) { refreshBufferedValues(); } for(int i=0;i<outPortsSize;i++){ outPortsArray[i].writeRecord(record); } } /** * Converts the collection of ports into List (ArrayList)<br> * This is auxiliary method which "caches" list of ports for faster access * when we need to go through all ports sequentially. Namely in * RecordBroadcast situations * *@param ports Collection of Ports *@return List (LinkedList) of ports */ private List getPortList(Collection ports) { List portList = new ArrayList(); portList.addAll(ports); return portList; } /** * Description of the Method * *@param recordBuffer Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since August 13, 2002 */ public void writeRecordBroadcastDirect(ByteBuffer recordBuffer) throws IOException, InterruptedException { if (outPortsArray == null) { refreshBufferedValues(); } for(int i=0;i<outPortsSize;i++){ ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * Closes all output ports - sends EOF signal to them. * *@since April 11, 2002 */ public void closeAllOutputPorts() throws InterruptedException { Iterator iterator = getOutPorts().iterator(); OutputPort port; while (iterator.hasNext()) { port = (OutputPort) iterator.next(); port.close(); } } /** * Send EOF (no more data) to all connected output ports * *@since April 18, 2002 */ public void broadcastEOF() throws InterruptedException{ closeAllOutputPorts(); } /** * Closes specified output port - sends EOF signal. * *@param portNum Which port to close *@since April 11, 2002 */ public void closeOutputPort(int portNum) throws InterruptedException { OutputPort port = (OutputPort) outPorts.get(new Integer(portNum)); if (port == null) { throw new RuntimeException(this.getId()+" - can't close output port \"" + portNum + "\" - does not exists!"); } port.close(); } /** * Compares this Node to specified Object * *@param obj Node to compare with *@return True if obj represents node with the same ID *@since April 18, 2002 */ @Override public boolean equals(Object obj) { if (getId().equals(((Node) obj).getId())) { return true; } else { return false; } } @Override public int hashCode(){ return getId().hashCode(); } /** * Description of the Method * *@return Description of the Returned Value *@since May 21, 2002 */ public void toXML(Element xmlElement) { // set basic XML attributes of all graph components xmlElement.setAttribute(XML_ID_ATTRIBUTE, getId()); xmlElement.setAttribute(XML_TYPE_ATTRIBUTE, getType()); } /** * Description of the Method * *@param nodeXML Description of Parameter *@return Description of the Returned Value *@since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement)throws XMLConfigurationException { throw new UnsupportedOperationException("not implemented in org.jetel.graph.Node"); } /** * @return <b>true</b> if node is enabled; <b>false</b> else */ public EnabledEnum getEnabled() { return enabled; } /** * @param enabled whether node is enabled */ public void setEnabled(String enabledStr) { enabled = EnabledEnum.fromString(enabledStr, EnabledEnum.ENABLED); } /** * @return index of "pass through" input port */ public int getPassThroughInputPort() { return passThroughInputPort; } /** * Sets "pass through" input port. * @param passThroughInputPort */ public void setPassThroughInputPort(int passThroughInputPort) { this.passThroughInputPort = passThroughInputPort; } /** * @return index of "pass through" output port */ public int getPassThroughOutputPort() { return passThroughOutputPort; } /** * Sets "pass through" output port * @param passThroughOutputPort */ public void setPassThroughOutputPort(int passThroughOutputPort) { this.passThroughOutputPort = passThroughOutputPort; } protected void resetBufferedValues(){ outPortList = null; outPortsArray=null; outPortsSize=0; } protected void refreshBufferedValues(){ Collection op = getOutPorts(); outPortsArray = (OutputPort[]) op.toArray(new OutputPort[op.size()]); outPortsSize = outPortsArray.length; } protected ConfigurationStatus checkInputPorts(ConfigurationStatus status, int min, int max) { if(getInPorts().size() < min) { status.add(new ConfigurationProblem("At least " + min + " input port can be defined!", Severity.ERROR, this, Priority.NORMAL)); } if(getInPorts().size() > max) { status.add(new ConfigurationProblem("At most " + max + " input ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); } return status; } protected ConfigurationStatus checkOutputPorts(ConfigurationStatus status, int min, int max) { if(getOutPorts().size() < min) { status.add(new ConfigurationProblem("At least " + min + " output port can be defined!", Severity.ERROR, this, Priority.NORMAL)); } if(getOutPorts().size() > max) { status.add(new ConfigurationProblem("At most " + max + " output ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); } return status; } /** * Checks if metadatas in given list are all equal * * @param status * @param metadata list of metadata to check * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata){ return checkMetadata(status, metadata, (Collection<DataRecordMetadata>)null); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * * @param status * @param inMetadata * @param outMetadata * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata){ Iterator<DataRecordMetadata> iterator = inMetadata.iterator(); DataRecordMetadata metadata = null, nextMetadata; if (iterator.hasNext()) { metadata = iterator.next(); } //check input metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (!metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata.getName()), Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } if (outMetadata == null) { return status; } //check if input metadata equals output metadata iterator = outMetadata.iterator(); if (iterator.hasNext()) { nextMetadata = iterator.next(); if (!metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata.getName()), Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } //check output metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (!metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata.getName()), Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } return status; } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, Collection<DataRecordMetadata> outMetadata){ Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); return checkMetadata(status, inputMetadata, outMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, DataRecordMetadata outMetadata){ Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inMetadata, outputMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, DataRecordMetadata outMetadata) { Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inputMetadata, outputMetadata); } } /* * end class Node */
package org.commcare.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.v7.preference.PreferenceManager; import android.util.Base64; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import org.apache.commons.lang3.StringUtils; import org.commcare.CommCareApplication; import org.commcare.activities.components.FormEntryConstants; import org.commcare.activities.components.FormEntryInstanceState; import org.commcare.activities.components.FormEntrySessionWrapper; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.database.user.models.SessionStateDescriptor; import org.commcare.android.logging.ReportingUtils; import org.commcare.core.process.CommCareInstanceInitializer; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.google.services.ads.AdMobManager; import org.commcare.google.services.analytics.AnalyticsParamValue; import org.commcare.google.services.analytics.FirebaseAnalyticsUtil; import org.commcare.heartbeat.UpdatePromptHelper; import org.commcare.interfaces.CommCareActivityUIController; import org.commcare.models.AndroidSessionWrapper; import org.commcare.models.database.SqlStorage; import org.commcare.preferences.AdvancedActionsPreferences; import org.commcare.preferences.DevSessionRestorer; import org.commcare.preferences.DeveloperPreferences; import org.commcare.preferences.HiddenPreferences; import org.commcare.preferences.MainConfigurablePreferences; import org.commcare.preferences.PrefValues; import org.commcare.session.CommCareSession; import org.commcare.session.SessionFrame; import org.commcare.session.SessionNavigationResponder; import org.commcare.session.SessionNavigator; import org.commcare.suite.model.EntityDatum; import org.commcare.suite.model.Entry; import org.commcare.suite.model.Menu; import org.commcare.suite.model.PostRequest; import org.commcare.suite.model.RemoteRequestEntry; import org.commcare.suite.model.SessionDatum; import org.commcare.suite.model.StackFrameStep; import org.commcare.suite.model.Text; import org.commcare.tasks.FormLoaderTask; import org.commcare.tasks.FormRecordCleanupTask; import org.commcare.util.LogTypes; import org.commcare.utils.AndroidCommCarePlatform; import org.commcare.utils.AndroidInstanceInitializer; import org.commcare.utils.ChangeLocaleUtil; import org.commcare.utils.CrashUtil; import org.commcare.utils.EntityDetailUtils; import org.commcare.utils.GlobalConstants; import org.commcare.utils.SessionUnavailableException; import org.commcare.utils.StorageUtils; import org.commcare.views.UserfacingErrorHandling; import org.commcare.views.dialogs.CommCareAlertDialog; import org.commcare.views.dialogs.DialogChoiceItem; import org.commcare.views.dialogs.DialogCreationHelpers; import org.commcare.views.dialogs.PaneledChoiceDialog; import org.commcare.views.dialogs.StandardAlertDialog; import org.commcare.views.notifications.NotificationMessageFactory; import org.javarosa.core.model.User; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.xpath.XPathTypeMismatchException; import java.io.File; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Vector; /** * Manages all of the shared (mostly non-UI) components of a CommCare home screen: * activity lifecycle, implementation of available actions, session navigation, etc. */ public abstract class HomeScreenBaseActivity<T> extends SyncCapableCommCareActivity<T> implements SessionNavigationResponder { /** * Request code for launching a menu list or menu grid */ public static final int GET_COMMAND = 1; /** * Request code for launching EntitySelectActivity (to allow user to select a case), * or EntityDetailActivity (to allow user to confirm an auto-selected case) */ protected static final int GET_CASE = 2; protected static final int GET_REMOTE_DATA = 3; /** * Request code for launching FormEntryActivity */ protected static final int MODEL_RESULT = 4; protected static final int MAKE_REMOTE_POST = 5; public static final int GET_INCOMPLETE_FORM = 6; protected static final int PREFERENCES_ACTIVITY = 7; protected static final int ADVANCED_ACTIONS_ACTIVITY = 8; protected static final int CREATE_PIN = 9; protected static final int AUTHENTICATION_FOR_PIN = 10; private static final String KEY_PENDING_SESSION_DATA = "pending-session-data-id"; private static final String KEY_PENDING_SESSION_DATUM_ID = "pending-session-datum-id"; /** * Restart is a special CommCare activity result code which means that the session was * invalidated in the calling activity and that the current session should be resynced */ public static final int RESULT_RESTART = 3; private int mDeveloperModeClicks = 0; private SessionNavigator sessionNavigator; private boolean sessionNavigationProceedingAfterOnResume; private boolean loginExtraWasConsumed; private static final String EXTRA_CONSUMED_KEY = "login_extra_was_consumed"; private boolean isRestoringSession = false; // The API allows for external calls. When this occurs, redispatch to their // activity instead of commcare. private boolean wasExternal = false; private static final String WAS_EXTERNAL_KEY = "was_external"; // Indicates if 1 of the checks we performed in onCreate resulted in redirecting to a // different activity or starting a UI-blocking task private boolean redirectedInOnCreate = false; @Override public void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); loadInstanceState(savedInstanceState); CrashUtil.registerAppData(); AdMobManager.initAdsForCurrentConsumerApp(getApplicationContext()); updateLastSuccessfulCommCareVersion(); sessionNavigator = new SessionNavigator(this); processFromExternalLaunch(savedInstanceState); processFromShortcutLaunch(); processFromLoginLaunch(); } private void updateLastSuccessfulCommCareVersion() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance()); SharedPreferences.Editor editor = preferences.edit(); editor.putString(HiddenPreferences.LAST_SUCCESSFUL_CC_VERSION, ReportingUtils.getCommCareVersionString()); editor.apply(); } private void loadInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); wasExternal = savedInstanceState.getBoolean(WAS_EXTERNAL_KEY); } } /** * Set state that signifies activity was launch from external app. */ private void processFromExternalLaunch(Bundle savedInstanceState) { if (savedInstanceState == null && getIntent().hasExtra(DispatchActivity.WAS_EXTERNAL)) { wasExternal = true; sessionNavigator.startNextSessionStep(); } } private void processFromShortcutLaunch() { if (getIntent().getBooleanExtra(DispatchActivity.WAS_SHORTCUT_LAUNCH, false)) { sessionNavigator.startNextSessionStep(); } } private void processFromLoginLaunch() { if (getIntent().getBooleanExtra(DispatchActivity.START_FROM_LOGIN, false) && !loginExtraWasConsumed) { getIntent().removeExtra(DispatchActivity.START_FROM_LOGIN); loginExtraWasConsumed = true; try { redirectedInOnCreate = doLoginLaunchChecksInOrder(); } finally { // make sure this happens no matter what clearOneTimeLoginActionFlags(); } } } /** * The order of operations in this method is very deliberate, and the logic for it is as * follows: * - If we're in demo mode, then we don't want to do any of the other checks because they're * not relevant * - Form and session restorations need to happen before we try to sync, because once we sync * it could invalidate those states * - Restoring a form that was interrupted by session expiration comes before restoring a saved * session because it is of higher importance * - Check for a post-update sync before doing a standard background form-send, since a sync * action will include a form-send action * - Once we're past that point, starting a background form-send process is safe, and we can * safely do checkForPinLaunchConditions() at the same time */ private boolean doLoginLaunchChecksInOrder() { if (isDemoUser()) { showDemoModeWarning(); return false; } if (tryRestoringFormFromSessionExpiration()) { return true; } if (tryRestoringSession()) { return true; } if (CommCareApplication.instance().isPostUpdateSyncNeeded()) { HiddenPreferences.setPostUpdateSyncNeeded(false); triggerSync(false); return true; } if (!CommCareApplication.instance().isSyncPending(false)) { // Trigger off a regular unsent task processor, unless we're about to sync (which will // then handle this in a blocking fashion) checkAndStartUnsentFormsTask(false, false); } checkForPinLaunchConditions(); return false; } /** * Regardless of what action(s) we ended up executing in doLoginLaunchChecksInOrder(), we * don't want to end up trying the actions associated with these flags again at a later point. * They either need to happen the first time on login, or not at all. */ private void clearOneTimeLoginActionFlags() { HiddenPreferences.setPostUpdateSyncNeeded(false); HiddenPreferences.clearInterruptedSSD(); } private boolean tryRestoringFormFromSessionExpiration() { SessionStateDescriptor existing = AndroidSessionWrapper.getFormStateForInterruptedUserSession(); if (existing != null) { AndroidSessionWrapper state = CommCareApplication.instance().getCurrentSessionWrapper(); state.loadFromStateDescription(existing); formEntry(CommCareApplication.instance().getCommCarePlatform() .getFormDefId(state.getSession().getForm()), state.getFormRecord(), null, true); return true; } return false; } private boolean tryRestoringSession() { CommCareSession session = CommCareApplication.instance().getCurrentSession(); if (session.getCommand() != null) { // Restore the session state if there is a command. This is for debugging and // occurs when a serialized session was stored by a previous user session isRestoringSession = true; sessionNavigator.startNextSessionStep(); return true; } return false; } /** * See if we should launch either the pin choice dialog, or the create pin activity directly */ private void checkForPinLaunchConditions() { LoginMode loginMode = (LoginMode)getIntent().getSerializableExtra(LoginActivity.LOGIN_MODE); if (loginMode == LoginMode.PRIMED) { launchPinCreateScreen(loginMode); } else if (loginMode == LoginMode.PASSWORD && DeveloperPreferences.shouldOfferPinForLogin()) { boolean userManuallyEnteredPasswordMode = getIntent() .getBooleanExtra(LoginActivity.MANUAL_SWITCH_TO_PW_MODE, false); boolean alreadyDismissedPinCreation = CommCareApplication.instance().getCurrentApp().getAppPreferences() .getBoolean(HiddenPreferences.HAS_DISMISSED_PIN_CREATION, false); if (!alreadyDismissedPinCreation || userManuallyEnteredPasswordMode) { showPinChoiceDialog(loginMode); } } } private void showPinChoiceDialog(final LoginMode loginMode) { String promptMessage; UserKeyRecord currentUserRecord = CommCareApplication.instance().getRecordForCurrentUser(); if (currentUserRecord.hasPinSet()) { promptMessage = Localization.get("pin.dialog.prompt.reset"); } else { promptMessage = Localization.get("pin.dialog.prompt.set"); } final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, promptMessage); DialogChoiceItem createPinChoice = new DialogChoiceItem( Localization.get("pin.dialog.yes"), -1, new View.OnClickListener() { @Override public void onClick(View v) { dismissAlertDialog(); launchPinCreateScreen(loginMode); } }); DialogChoiceItem nextTimeChoice = new DialogChoiceItem( Localization.get("pin.dialog.not.now"), -1, new View.OnClickListener() { @Override public void onClick(View v) { dismissAlertDialog(); } }); DialogChoiceItem notAgainChoice = new DialogChoiceItem( Localization.get("pin.dialog.never"), -1, new View.OnClickListener() { @Override public void onClick(View v) { dismissAlertDialog(); CommCareApplication.instance().getCurrentApp().getAppPreferences() .edit() .putBoolean(HiddenPreferences.HAS_DISMISSED_PIN_CREATION, true) .apply(); showPinFutureAccessDialog(); } }); dialog.setChoiceItems(new DialogChoiceItem[]{createPinChoice, nextTimeChoice, notAgainChoice}); dialog.addCollapsibleInfoPane(Localization.get("pin.dialog.extra.info")); showAlertDialog(dialog); } private void showPinFutureAccessDialog() { StandardAlertDialog.getBasicAlertDialog(this, Localization.get("pin.dialog.set.later.title"), Localization.get("pin.dialog.set.later.message"), null).showNonPersistentDialog(); } protected void launchPinAuthentication() { Intent i = new Intent(this, PinAuthenticationActivity.class); startActivityForResult(i, AUTHENTICATION_FOR_PIN); } private void launchPinCreateScreen(LoginMode loginMode) { Intent i = new Intent(this, CreatePinActivity.class); i.putExtra(LoginActivity.LOGIN_MODE, loginMode); startActivityForResult(i, CREATE_PIN); } protected void showLocaleChangeMenu(final CommCareActivityUIController uiController) { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("home.menu.locale.select")); AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String[] localeCodes = ChangeLocaleUtil.getLocaleCodes(); if (position >= localeCodes.length) { Localization.setLocale("default"); } else { String selectedLocale = localeCodes[position]; MainConfigurablePreferences.setCurrentLocale(selectedLocale); Localization.setLocale(selectedLocale); } // rebuild home buttons in case language changed; if (uiController != null) { uiController.setupUI(); } rebuildOptionsMenu(); dismissAlertDialog(); } }; dialog.setChoiceItems(buildLocaleChoices(), listClickListener); showAlertDialog(dialog); } private static DialogChoiceItem[] buildLocaleChoices() { String[] locales = ChangeLocaleUtil.getLocaleNames(); DialogChoiceItem[] choices = new DialogChoiceItem[locales.length]; for (int i = 0; i < choices.length; i++) { choices[i] = DialogChoiceItem.nonListenerItem(locales[i]); } return choices; } protected void goToFormArchive(boolean incomplete) { goToFormArchive(incomplete, null); } protected void goToFormArchive(boolean incomplete, FormRecord record) { FirebaseAnalyticsUtil.reportViewArchivedFormsList(incomplete); Intent i = new Intent(getApplicationContext(), FormRecordListActivity.class); if (incomplete) { i.putExtra(FormRecord.META_STATUS, FormRecord.STATUS_INCOMPLETE); } if (record != null) { i.putExtra(FormRecordListActivity.KEY_INITIAL_RECORD_ID, record.getID()); } startActivityForResult(i, GET_INCOMPLETE_FORM); } protected void userTriggeredLogout() { CommCareApplication.instance().closeUserSession(); setResult(RESULT_OK); finish(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(WAS_EXTERNAL_KEY, wasExternal); outState.putBoolean(EXTRA_CONSUMED_KEY, loginExtraWasConsumed); } @Override public void onActivityResultSessionSafe(int requestCode, int resultCode, Intent intent) { if (resultCode == RESULT_RESTART) { sessionNavigator.startNextSessionStep(); } else { // if handling new return code (want to return to home screen) but a return at the end of your statement switch (requestCode) { case PREFERENCES_ACTIVITY: if (resultCode == AdvancedActionsPreferences.RESULT_DATA_RESET) { finish(); } else if (resultCode == DeveloperPreferences.RESULT_SYNC_CUSTOM) { performCustomRestore(); } return; case ADVANCED_ACTIONS_ACTIVITY: handleAdvancedActionResult(resultCode, intent); return; case GET_INCOMPLETE_FORM: //TODO: We might need to load this from serialized state? if (resultCode == RESULT_CANCELED) { refreshUI(); return; } else if (resultCode == RESULT_OK) { int record = intent.getIntExtra("FORMRECORDS", -1); if (record == -1) { //Hm, what to do here? break; } FormRecord r = CommCareApplication.instance().getUserStorage(FormRecord.class).read(record); //Retrieve and load the appropriate ssd SqlStorage<SessionStateDescriptor> ssdStorage = CommCareApplication.instance().getUserStorage(SessionStateDescriptor.class); Vector<Integer> ssds = ssdStorage.getIDsForValue(SessionStateDescriptor.META_FORM_RECORD_ID, r.getID()); AndroidSessionWrapper currentState = CommCareApplication.instance().getCurrentSessionWrapper(); if (ssds.size() == 1) { currentState.loadFromStateDescription(ssdStorage.read(ssds.firstElement())); } else { currentState.setFormRecordId(r.getID()); } AndroidCommCarePlatform platform = CommCareApplication.instance().getCommCarePlatform(); formEntry(platform.getFormDefId(r.getFormNamespace()), r); return; } break; case GET_COMMAND: boolean continueWithSessionNav = processReturnFromGetCommand(resultCode, intent); if (!continueWithSessionNav) { return; } break; case GET_CASE: continueWithSessionNav = processReturnFromGetCase(resultCode, intent); if (!continueWithSessionNav) { return; } break; case MODEL_RESULT: continueWithSessionNav = processReturnFromFormEntry(resultCode, intent); if (!continueWithSessionNav) { return; } if (!CommCareApplication.instance().getSession().appHealthChecksCompleted()) { // If we haven't done these checks yet in this user session, try to if (checkForPendingAppHealthActions()) { // If we kick one off, abandon the session navigation that we were // going to proceed with, because it may be invalid now return; } } break; case AUTHENTICATION_FOR_PIN: if (resultCode == RESULT_OK) { launchPinCreateScreen(LoginMode.PASSWORD); } return; case CREATE_PIN: boolean choseRememberPassword = intent != null && intent.getBooleanExtra(CreatePinActivity.CHOSE_REMEMBER_PASSWORD, false); if (choseRememberPassword) { CommCareApplication.instance().closeUserSession(); } else if (resultCode == RESULT_OK) { Toast.makeText(this, Localization.get("pin.set.success"), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, Localization.get("pin.not.set"), Toast.LENGTH_SHORT).show(); } return; case MAKE_REMOTE_POST: stepBackIfCancelled(resultCode); if (resultCode == RESULT_OK) { CommCareApplication.instance().getCurrentSessionWrapper().terminateSession(); } break; case GET_REMOTE_DATA: stepBackIfCancelled(resultCode); break; } sessionNavigationProceedingAfterOnResume = true; startNextSessionStepSafe(); } } private void performCustomRestore() { try { String filePath = DeveloperPreferences.getCustomRestoreDocLocation(); if (filePath != null && !filePath.isEmpty()) { File f = new File(filePath); if (f.exists()) { formAndDataSyncer.performCustomRestoreFromFile(this, f); } else { Toast.makeText(this, Localization.get("custom.restore.file.not.exist"), Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, Localization.get("custom.restore.file.not.set"), Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(this, Localization.get("custom.restore.error"), Toast.LENGTH_LONG).show(); } } private boolean processReturnFromGetCase(int resultCode, Intent intent) { if (resultCode == RESULT_CANCELED) { return processCanceledGetCommandOrCase(); } else if (resultCode == RESULT_OK) { return processSuccessfulGetCase(intent); } return false; } public boolean processReturnFromGetCommand(int resultCode, Intent intent) { if (resultCode == RESULT_CANCELED) { return processCanceledGetCommandOrCase(); } else if (resultCode == RESULT_OK) { return processSuccessfulGetCommand(intent); } return true; } private boolean processSuccessfulGetCommand(Intent intent) { AndroidSessionWrapper currentState = CommCareApplication.instance().getCurrentSessionWrapper(); CommCareSession session = currentState.getSession(); if (sessionStateUnchangedSinceCallout(session, intent)) { // Get our command, set it, and continue forward String command = intent.getStringExtra(SessionFrame.STATE_COMMAND_ID); session.setCommand(command); return true; } else { clearSessionAndExit(currentState, true); return false; } } private boolean processSuccessfulGetCase(Intent intent) { AndroidSessionWrapper asw = CommCareApplication.instance().getCurrentSessionWrapper(); CommCareSession currentSession = asw.getSession(); if (sessionStateUnchangedSinceCallout(currentSession, intent)) { String sessionDatumId = currentSession.getNeededDatum().getDataId(); String chosenCaseId = intent.getStringExtra(SessionFrame.STATE_DATUM_VAL); currentSession.setDatum(sessionDatumId, chosenCaseId); return true; } else { clearSessionAndExit(asw, true); return false; } } private boolean processCanceledGetCommandOrCase() { AndroidSessionWrapper currentState = CommCareApplication.instance().getCurrentSessionWrapper(); String currentCommand = currentState.getSession().getCommand(); if (currentCommand == null || currentCommand.equals(Menu.TRAINING_MENU_ROOT)) { // We're stepping back from either the root module menu or the training root menu, so go home currentState.reset(); refreshUI(); return false; } else { currentState.getSession().stepBack(currentState.getEvaluationContext()); return true; } } private void handleAdvancedActionResult(int resultCode, Intent intent) { if (resultCode == AdvancedActionsPreferences.RESULT_FORMS_PROCESSED) { int formProcessCount = intent.getIntExtra(AdvancedActionsPreferences.FORM_PROCESS_COUNT_KEY, 0); String localizationKey = intent.getStringExtra(AdvancedActionsPreferences.FORM_PROCESS_MESSAGE_KEY); displayToast(Localization.get(localizationKey, new String[]{"" + formProcessCount})); refreshUI(); } } private static void stepBackIfCancelled(int resultCode) { if (resultCode == RESULT_CANCELED) { AndroidSessionWrapper asw = CommCareApplication.instance().getCurrentSessionWrapper(); CommCareSession currentSession = asw.getSession(); currentSession.stepBack(asw.getEvaluationContext()); } } public void startNextSessionStepSafe() { try { sessionNavigator.startNextSessionStep(); } catch (CommCareInstanceInitializer.FixtureInitializationException e) { sessionNavigator.stepBack(); if (isDemoUser()) { // most likely crashing due to data not being available in demo mode UserfacingErrorHandling.createErrorDialog(this, Localization.get("demo.mode.feature.unavailable"), false); } else { UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), false); } } } /** * @return If the nature of the data that the session is waiting for has not changed since the * callout that we are returning from was made */ private boolean sessionStateUnchangedSinceCallout(CommCareSession session, Intent intent) { EvaluationContext evalContext = CommCareApplication.instance().getCurrentSessionWrapper().getEvaluationContext(); String pendingSessionData = intent.getStringExtra(KEY_PENDING_SESSION_DATA); String sessionNeededData = session.getNeededData(evalContext); boolean neededDataUnchanged = (pendingSessionData == null && sessionNeededData == null) || (pendingSessionData != null && pendingSessionData.equals(sessionNeededData)); String intentDatum = intent.getStringExtra(KEY_PENDING_SESSION_DATUM_ID); boolean datumIdsUnchanged = intentDatum == null || intentDatum.equals(session.getNeededDatum().getDataId()); return neededDataUnchanged && datumIdsUnchanged; } /** * Process user returning home from the form entry activity. * Triggers form submission cycle, cleans up some session state. * * @param resultCode exit code of form entry activity * @param intent The intent of the returning activity, with the * saved form provided as the intent URI data. Null if * the form didn't exit cleanly * @return Flag signifying that caller should fetch the next activity in * the session to launch. If false then caller should exit or spawn home * activity. */ private boolean processReturnFromFormEntry(int resultCode, Intent intent) { // TODO: We might need to load this from serialized state? AndroidSessionWrapper currentState = CommCareApplication.instance().getCurrentSessionWrapper(); // This is the state we were in when we _Started_ form entry FormRecord current = currentState.getFormRecord(); if (current == null) { // somehow we lost the form record for the current session Toast.makeText(this, "Error while trying to save the form!", Toast.LENGTH_LONG).show(); Logger.log(LogTypes.TYPE_ERROR_WORKFLOW, "Form Entry couldn't save because of corrupt state."); clearSessionAndExit(currentState, true); return false; } // TODO: This should be the default unless we're in some "Uninit" or "incomplete" state if ((intent != null && intent.getBooleanExtra(FormEntryConstants.IS_ARCHIVED_FORM, false)) || FormRecord.STATUS_COMPLETE.equals(current.getStatus()) || FormRecord.STATUS_SAVED.equals(current.getStatus())) { // Viewing an old form, so don't change the historical record // regardless of the exit code currentState.reset(); if (wasExternal || (intent != null && intent.getBooleanExtra(FormEntryActivity.KEY_IS_RESTART_AFTER_EXPIRATION, false))) { setResult(RESULT_CANCELED); this.finish(); } else { // Return to where we started goToFormArchive(false, current); } return false; } if (resultCode == RESULT_OK) { String formRecordStatus = current.getStatus(); // was the record marked complete? boolean complete = FormRecord.STATUS_COMPLETE.equals(formRecordStatus) || FormRecord.STATUS_UNSENT.equals(formRecordStatus); // The form is either ready for processing, or not, depending on how it was saved if (complete) { // Now that we know this form is completed, we can give it the next available // submission ordering number current.setFormNumberForSubmissionOrdering(StorageUtils.getNextFormSubmissionNumber()); SqlStorage<FormRecord> formRecordStorage = CommCareApplication.instance().getUserStorage(FormRecord.class); formRecordStorage.write(current); checkAndStartUnsentFormsTask(false, false); refreshUI(); if (wasExternal) { setResult(RESULT_CANCELED); this.finish(); return false; } // Before we can terminate the session, we need to know that the form has been // processed in case there is state that depends on it. boolean terminateSuccessful; try { terminateSuccessful = currentState.terminateSession(); } catch (XPathTypeMismatchException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, true); return false; } if (!terminateSuccessful) { // If we didn't find somewhere to go, we're gonna stay here return false; } // Otherwise, we want to keep proceeding in order // to keep running the workflow } else { CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( NotificationMessageFactory.StockMessages.FormEntry_Unretrievable)); Toast.makeText(this, "Error while trying to read the form! See the notification", Toast.LENGTH_LONG).show(); Logger.log(LogTypes.TYPE_ERROR_WORKFLOW, "Form Entry did not return a form"); clearSessionAndExit(currentState, false); return false; } } else if (resultCode == RESULT_CANCELED) { // Nothing was saved during the form entry activity Logger.log(LogTypes.TYPE_FORM_ENTRY, "Form Entry Cancelled"); // If the form was unstarted, we want to wipe the record. if (current.getStatus().equals(FormRecord.STATUS_UNSTARTED)) { // Entry was cancelled. FormRecordCleanupTask.wipeRecord(currentState); } if (wasExternal) { currentState.reset(); setResult(RESULT_CANCELED); this.finish(); return false; } else if (current.getStatus().equals(FormRecord.STATUS_INCOMPLETE) && intent != null && !intent.getBooleanExtra(FormEntryActivity.KEY_IS_RESTART_AFTER_EXPIRATION, false)) { currentState.reset(); // We should head back to the incomplete forms screen goToFormArchive(true, current); return false; } else { // If we cancelled form entry from a normal menu entry // we want to go back to where were were right before we started // entering the form. currentState.getSession().stepBack(currentState.getEvaluationContext()); currentState.setFormRecordId(-1); } } return true; } private void clearSessionAndExit(AndroidSessionWrapper currentState, boolean shouldWarnUser) { currentState.reset(); if (wasExternal) { if (shouldWarnUser) { setResult(RESULT_CANCELED); } else { setResult(RESULT_OK); } this.finish(); } refreshUI(); if (shouldWarnUser) { showSessionRefreshWarning(); } } private void showSessionRefreshWarning() { showAlertDialog(StandardAlertDialog.getBasicAlertDialog(this, Localization.get("session.refresh.error.title"), Localization.get("session.refresh.error.message"), null)); } private void showDemoModeWarning() { StandardAlertDialog d = StandardAlertDialog.getBasicAlertDialogWithIcon(this, Localization.get("demo.mode.warning.title"), Localization.get("demo.mode.warning.main"), android.R.drawable.ic_dialog_info, null); d.addEmphasizedMessage(Localization.get("demo.mode.warning.emphasized")); showAlertDialog(d); } private void createErrorDialog(String errorMsg, AlertDialog.OnClickListener errorListener) { showAlertDialog(StandardAlertDialog.getBasicAlertDialogWithIcon(this, Localization.get("app.handled.error.title"), errorMsg, android.R.drawable.ic_dialog_info, errorListener)); } @Override public void processSessionResponse(int statusCode) { AndroidSessionWrapper asw = CommCareApplication.instance().getCurrentSessionWrapper(); switch (statusCode) { case SessionNavigator.ASSERTION_FAILURE: handleAssertionFailureFromSessionNav(asw); break; case SessionNavigator.NO_CURRENT_FORM: handleNoFormFromSessionNav(asw); break; case SessionNavigator.START_FORM_ENTRY: startFormEntry(asw); break; case SessionNavigator.GET_COMMAND: handleGetCommand(asw); break; case SessionNavigator.START_ENTITY_SELECTION: launchEntitySelect(asw.getSession()); break; case SessionNavigator.LAUNCH_CONFIRM_DETAIL: launchConfirmDetail(asw); break; case SessionNavigator.PROCESS_QUERY_REQUEST: launchQueryMaker(); break; case SessionNavigator.START_SYNC_REQUEST: launchRemoteSync(asw); break; case SessionNavigator.XPATH_EXCEPTION_THROWN: UserfacingErrorHandling .logErrorAndShowDialog(this, sessionNavigator.getCurrentException(), false); asw.reset(); break; case SessionNavigator.REPORT_CASE_AUTOSELECT: FirebaseAnalyticsUtil.reportFeatureUsage(AnalyticsParamValue.FEATURE_CASE_AUTOSELECT); break; } } @Override public CommCareSession getSessionForNavigator() { return CommCareApplication.instance().getCurrentSession(); } @Override public EvaluationContext getEvalContextForNavigator() { return CommCareApplication.instance().getCurrentSessionWrapper().getEvaluationContext(); } private void handleAssertionFailureFromSessionNav(final AndroidSessionWrapper asw) { EvaluationContext ec = asw.getEvaluationContext(); Text text = asw.getSession().getCurrentEntry().getAssertions().getAssertionFailure(ec); createErrorDialog(text.evaluate(ec), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dismissAlertDialog(); asw.getSession().stepBack(asw.getEvaluationContext()); HomeScreenBaseActivity.this.sessionNavigator.startNextSessionStep(); } }); } private void handleNoFormFromSessionNav(AndroidSessionWrapper asw) { boolean terminateSuccesful; try { terminateSuccesful = asw.terminateSession(); } catch (XPathTypeMismatchException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, true); return; } if (terminateSuccesful) { sessionNavigator.startNextSessionStep(); } else { refreshUI(); } } private void handleGetCommand(AndroidSessionWrapper asw) { Intent i = new Intent(this, MenuActivity.class); String command = asw.getSession().getCommand(); i.putExtra(SessionFrame.STATE_COMMAND_ID, command); addPendingDataExtra(i, asw.getSession()); startActivityForResult(i, GET_COMMAND); } private void launchRemoteSync(AndroidSessionWrapper asw) { String command = asw.getSession().getCommand(); Entry commandEntry = CommCareApplication.instance().getCommCarePlatform().getEntry(command); if (commandEntry instanceof RemoteRequestEntry) { PostRequest postRequest = ((RemoteRequestEntry)commandEntry).getPostRequest(); Intent i = new Intent(getApplicationContext(), PostRequestActivity.class); i.putExtra(PostRequestActivity.URL_KEY, postRequest.getUrl()); i.putExtra(PostRequestActivity.PARAMS_KEY, new HashMap<>(postRequest.getEvaluatedParams(asw.getEvaluationContext()))); startActivityForResult(i, MAKE_REMOTE_POST); } else { // expected a sync entry; clear session and show vague 'session error' message to user clearSessionAndExit(asw, true); } } private void launchQueryMaker() { Intent i = new Intent(getApplicationContext(), QueryRequestActivity.class); startActivityForResult(i, GET_REMOTE_DATA); } private void launchEntitySelect(CommCareSession session) { startActivityForResult(getSelectIntent(session), GET_CASE); } private Intent getSelectIntent(CommCareSession session) { Intent i = new Intent(getApplicationContext(), EntitySelectActivity.class); i.putExtra(SessionFrame.STATE_COMMAND_ID, session.getCommand()); StackFrameStep lastPopped = session.getPoppedStep(); if (lastPopped != null && SessionFrame.STATE_DATUM_VAL.equals(lastPopped.getType())) { i.putExtra(EntitySelectActivity.EXTRA_ENTITY_KEY, lastPopped.getValue()); } addPendingDataExtra(i, session); addPendingDatumIdExtra(i, session); return i; } public void launchUpdateActivity() { Intent i = new Intent(getApplicationContext(), UpdateActivity.class); startActivity(i); } void enterTrainingModule() { CommCareApplication.instance().getCurrentSession().setCommand(org.commcare.suite.model.Menu.TRAINING_MENU_ROOT); startNextSessionStepSafe(); } // Launch an intent to load the confirmation screen for the current selection private void launchConfirmDetail(AndroidSessionWrapper asw) { CommCareSession session = asw.getSession(); SessionDatum selectDatum = session.getNeededDatum(); if (selectDatum instanceof EntityDatum) { EntityDatum entityDatum = (EntityDatum)selectDatum; TreeReference contextRef = sessionNavigator.getCurrentAutoSelection(); if (this.getString(R.string.panes).equals("two") && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // Large tablet in landscape: send to entity select activity // (awesome mode, with case pre-selected) instead of entity detail Intent i = getSelectIntent(session); String caseId = EntityDatum.getCaseIdFromReference( contextRef, entityDatum, asw.getEvaluationContext()); i.putExtra(EntitySelectActivity.EXTRA_ENTITY_KEY, caseId); startActivityForResult(i, GET_CASE); } else { // Launch entity detail activity Intent detailIntent = new Intent(getApplicationContext(), EntityDetailActivity.class); EntityDetailUtils.populateDetailIntent( detailIntent, contextRef, entityDatum, asw); addPendingDataExtra(detailIntent, session); addPendingDatumIdExtra(detailIntent, session); startActivityForResult(detailIntent, GET_CASE); } } } protected static void addPendingDataExtra(Intent i, CommCareSession session) { EvaluationContext evalContext = CommCareApplication.instance().getCurrentSessionWrapper().getEvaluationContext(); i.putExtra(KEY_PENDING_SESSION_DATA, session.getNeededData(evalContext)); } private static void addPendingDatumIdExtra(Intent i, CommCareSession session) { i.putExtra(KEY_PENDING_SESSION_DATUM_ID, session.getNeededDatum().getDataId()); } /** * Create (or re-use) a form record and pass it to the form entry activity * launcher. If there is an existing incomplete form that uses the same * case, ask the user if they want to edit or delete that one. * * @param state Needed for FormRecord manipulations */ private void startFormEntry(AndroidSessionWrapper state) { if (state.getFormRecordId() == -1) { if (HiddenPreferences.isIncompleteFormsEnabled()) { // Are existing (incomplete) forms using the same case? SessionStateDescriptor existing = state.getExistingIncompleteCaseDescriptor(); if (existing != null) { // Ask user if they want to just edit existing form that // uses the same case. createAskUseOldDialog(state, existing); return; } } // Generate a stub form record and commit it state.commitStub(); } else { Logger.log(LogTypes.TYPE_FORM_ENTRY, "Somehow ended up starting form entry with old state?"); } FormRecord record = state.getFormRecord(); AndroidCommCarePlatform platform = CommCareApplication.instance().getCommCarePlatform(); formEntry(platform.getFormDefId(record.getFormNamespace()), record, CommCareActivity.getTitle(this, null), false); } private void formEntry(int formDefId, FormRecord r) { formEntry(formDefId, r, null, false); } private void formEntry(int formDefId, FormRecord r, String headerTitle, boolean isRestartAfterSessionExpiration) { Logger.log(LogTypes.TYPE_FORM_ENTRY, "Form Entry Starting|" + r.getFormNamespace()); //TODO: This is... just terrible. Specify where external instance data should come from FormLoaderTask.iif = new AndroidInstanceInitializer(CommCareApplication.instance().getCurrentSession()); // Create our form entry activity callout Intent i = new Intent(getApplicationContext(), FormEntryActivity.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(FormEntryInstanceState.KEY_FORM_RECORD_DESTINATION, CommCareApplication.instance().getCurrentApp().fsPath((GlobalConstants.FILE_CC_FORMS))); // See if there's existing form data that we want to continue entering if (!StringUtils.isEmpty(r.getFilePath())) { i.putExtra(FormEntryActivity.KEY_FORM_RECORD_ID, r.getID()); } else { i.putExtra(FormEntryActivity.KEY_FORM_DEF_ID, formDefId); } i.putExtra(FormEntryActivity.KEY_RESIZING_ENABLED, HiddenPreferences.getResizeMethod()); i.putExtra(FormEntryActivity.KEY_INCOMPLETE_ENABLED, HiddenPreferences.isIncompleteFormsEnabled()); i.putExtra(FormEntryActivity.KEY_AES_STORAGE_KEY, Base64.encodeToString(r.getAesKey(), Base64.DEFAULT)); i.putExtra(FormEntrySessionWrapper.KEY_RECORD_FORM_ENTRY_SESSION, DeveloperPreferences.isSessionSavingEnabled()); i.putExtra(FormEntryActivity.KEY_IS_RESTART_AFTER_EXPIRATION, isRestartAfterSessionExpiration); if (headerTitle != null) { i.putExtra(FormEntryActivity.KEY_HEADER_STRING, headerTitle); } if (isRestoringSession) { isRestoringSession = false; SharedPreferences prefs = CommCareApplication.instance().getCurrentApp().getAppPreferences(); String formEntrySession = prefs.getString(DevSessionRestorer.CURRENT_FORM_ENTRY_SESSION, ""); if (!"".equals(formEntrySession)) { i.putExtra(FormEntrySessionWrapper.KEY_FORM_ENTRY_SESSION, formEntrySession); } } startActivityForResult(i, MODEL_RESULT); } private void triggerSync(boolean triggeredByAutoSyncPending) { if (triggeredByAutoSyncPending) { long lastSync = CommCareApplication.instance().getCurrentApp().getAppPreferences() .getLong(HiddenPreferences.LAST_SYNC_ATTEMPT, 0); String footer = lastSync == 0 ? "never" : SimpleDateFormat.getDateTimeInstance().format(lastSync); Logger.log(LogTypes.TYPE_USER, "autosync triggered. Last Sync|" + footer); } refreshUI(); sendFormsOrSync(false); } @Override public void onResumeSessionSafe() { if (!redirectedInOnCreate && !sessionNavigationProceedingAfterOnResume) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { refreshActionBar(); } attemptDispatchHomeScreen(); } // reset these redirectedInOnCreate = false; sessionNavigationProceedingAfterOnResume = false; } private void attemptDispatchHomeScreen() { try { CommCareApplication.instance().getSession(); } catch (SessionUnavailableException e) { // User was logged out somehow, so we want to return to dispatch activity setResult(RESULT_OK); this.finish(); return; } if (!checkForPendingAppHealthActions()) { // Display the home screen! refreshUI(); } } /** * @return true if we kicked off any processes */ private boolean checkForPendingAppHealthActions() { boolean result = false; if (CommCareApplication.instance().isSyncPending(false)) { triggerSync(true); result = true; } else if (UpdatePromptHelper.promptForUpdateIfNeeded(this)) { result = true; } CommCareApplication.instance().getSession().setAppHealthChecksCompleted(); return result; } private void createAskUseOldDialog(final AndroidSessionWrapper state, final SessionStateDescriptor existing) { final AndroidCommCarePlatform platform = CommCareApplication.instance().getCommCarePlatform(); String title = Localization.get("app.workflow.incomplete.continue.title"); String msg = Localization.get("app.workflow.incomplete.continue"); StandardAlertDialog d = new StandardAlertDialog(this, title, msg); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // use the old form instance and load the it's state from the descriptor state.loadFromStateDescription(existing); formEntry(platform.getFormDefId(state.getSession().getForm()), state.getFormRecord()); break; case DialogInterface.BUTTON_NEGATIVE: // delete the old incomplete form FormRecordCleanupTask.wipeRecord(existing); // fallthrough to new now that old record is gone case DialogInterface.BUTTON_NEUTRAL: // create a new form record and begin form entry state.commitStub(); formEntry(platform.getFormDefId(state.getSession().getForm()), state.getFormRecord()); } dismissAlertDialog(); } }; d.setPositiveButton(Localization.get("option.yes"), listener); d.setNegativeButton(Localization.get("app.workflow.incomplete.continue.option.delete"), listener); d.setNeutralButton(Localization.get("option.no"), listener); showAlertDialog(d); } protected static boolean isDemoUser() { try { User u = CommCareApplication.instance().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { // Default to a normal user: this should only happen if session // expires and hasn't redirected to login. return false; } } public static void createPreferencesMenu(Activity activity) { Intent i = new Intent(activity, SessionAwarePreferenceActivity.class); i.putExtra(CommCarePreferenceActivity.EXTRA_PREF_TYPE, CommCarePreferenceActivity.PREF_TYPE_COMMCARE); activity.startActivityForResult(i, PREFERENCES_ACTIVITY); } protected void showAdvancedActionsPreferences() { Intent intent = new Intent(this, SessionAwarePreferenceActivity.class); intent.putExtra(CommCarePreferenceActivity.EXTRA_PREF_TYPE, CommCarePreferenceActivity.PREF_TYPE_ADVANCED_ACTIONS); startActivityForResult(intent, ADVANCED_ACTIONS_ACTIVITY); } protected void showAboutCommCareDialog() { CommCareAlertDialog dialog = DialogCreationHelpers.buildAboutCommCareDialog(this); dialog.makeCancelable(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { handleDeveloperModeClicks(); } }); showAlertDialog(dialog); } private void handleDeveloperModeClicks() { mDeveloperModeClicks++; if (mDeveloperModeClicks == 4) { CommCareApplication.instance().getCurrentApp().getAppPreferences() .edit() .putString(DeveloperPreferences.SUPERUSER_ENABLED, PrefValues.YES) .apply(); Toast.makeText(this, Localization.get("home.developer.options.enabled"), Toast.LENGTH_SHORT).show(); } } @Override public boolean isBackEnabled() { return false; } /** * For Testing purposes only */ public SessionNavigator getSessionNavigator() { if (BuildConfig.DEBUG) { return sessionNavigator; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } /** * For Testing purposes only */ public void setFormAndDataSyncer(FormAndDataSyncer formAndDataSyncer) { if (BuildConfig.DEBUG) { this.formAndDataSyncer = formAndDataSyncer; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } abstract void refreshUI(); }
package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import java.util.concurrent.CyclicBarrier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.MDC; import org.jetel.data.DataRecord; import org.jetel.enums.EnabledEnum; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.JetelRuntimeException; import org.jetel.graph.ContextProvider.Context; import org.jetel.graph.distribution.EngineComponentAllocation; import org.jetel.graph.runtime.CloverPost; import org.jetel.graph.runtime.CloverWorkerListener; import org.jetel.graph.runtime.ErrorMsgBody; import org.jetel.graph.runtime.Message; import org.jetel.graph.runtime.tracker.ComplexComponentTokenTracker; import org.jetel.graph.runtime.tracker.ComponentTokenTracker; import org.jetel.graph.runtime.tracker.PrimitiveComponentTokenTracker; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ClusterUtils; import org.jetel.util.MiscUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; /** * A class that represents atomic transformation task. It is a base class for * all kinds of transformation components. * *@author D.Pavlis *@created January 31, 2003 *@since April 2, 2002 *@see org.jetel.component */ public abstract class Node extends GraphElement implements Runnable, CloverWorkerListener { private static final Log logger = LogFactory.getLog(Node.class); private Thread nodeThread; private final Object nodeThreadMonitor = new Object(); // nodeThread variable is guarded by this monitor /** * List of all threads under this component. * For instance parallel reader uses threads for parallel reading. * It is component's responsibility to register all inner threads via addChildThread() method. */ protected List<Thread> childThreads; protected EnabledEnum enabled; protected int passThroughInputPort; protected int passThroughOutputPort; protected TreeMap<Integer, OutputPort> outPorts; protected TreeMap<Integer, InputPort> inPorts; protected volatile boolean runIt = true; private Result runResult; private final Object runResultMonitor = new Object(); // runResult variable is guarded by this monitor protected Throwable resultException; protected String resultMessage; protected Phase phase; /** * Distribution of this node processing at cluster environment. */ protected EngineComponentAllocation allocation; // buffered values protected OutputPort[] outPortsArray; protected int outPortsSize; //synchronization barrier for all components in a phase //all components have to finish pre-execution before execution method private CyclicBarrier executeBarrier; //synchronization barrier for all components in a phase //watchdog needs to have all components with thread assignment before can continue to watch the phase private CyclicBarrier preExecuteBarrier; /** * Component token tracker encapsulates graph's token tracker. * All jobflow logging for this component should be provided through this tracker. * Tracker cannot be null, at least {@link PrimitiveComponentTokenTracker} is used. */ protected ComponentTokenTracker tokenTracker; /** * Various PORT kinds identifiers * *@since August 13, 2002 */ public final static char OUTPUT_PORT = 'O'; /** Description of the Field */ public final static char INPUT_PORT = 'I'; /** * XML attributes of every cloverETL component */ public final static String XML_NAME_ATTRIBUTE = "guiName"; public final static String XML_TYPE_ATTRIBUTE="type"; public final static String XML_ENABLED_ATTRIBUTE="enabled"; public final static String XML_ALLOCATION_ATTRIBUTE = "allocation"; /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id){ this(id,null); } /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id, TransformationGraph graph) { super(id,graph); outPorts = new TreeMap<Integer, OutputPort>(); inPorts = new TreeMap<Integer, InputPort>(); phase = null; setResultCode(Result.N_A); // result is not known yet childThreads = Collections.synchronizedList(new ArrayList<Thread>()); allocation = EngineComponentAllocation.createBasedOnNeighbours(); } /** * Sets the EOF for particular output port. EOF indicates that no more data * will be sent throught the output port. * *@param portNum The new EOF value * @throws IOException * @throws IOException *@since April 18, 2002 */ public void setEOF(int portNum) throws InterruptedException, IOException { try { ((OutputPort) outPorts.get(Integer.valueOf(portNum))).eof(); } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); } } /** * Returns the type of this Node (subclasses/Components should override * this method to return appropriate type). * *@return The Type value *@since April 4, 2002 */ public abstract String getType(); /** * Returns True if this Node is Leaf Node - i.e. only consumes data (has only * input ports connected to it) * *@return True if Node is a Leaf *@since April 4, 2002 */ public boolean isLeaf() { //this implementation is necessary for remote edges //even component with a connected edge can be leaf if the edge is the remote one for (OutputPort outputPort : getOutPorts()) { if (outputPort.getReader() != null) { return false; } } return true; } /** * Returns True if this node is Root Node - i.e. it produces data (has only output ports * connected to id). * *@return True if Node is a Root *@since April 4, 2002 */ public boolean isRoot() { //this implementation is necessary for remote edges //even component with a connected edge can be root if the edge is the remote one for (InputPort inputPort : getInPorts()) { if (inputPort.getWriter() != null) { return false; } } return true; } /** * Sets the processing phase of the Node object.<br> * Default is 0 (ZERO). * *@param phase The new phase number */ public void setPhase(Phase phase) { this.phase = phase; } /** * Gets the processing phase of the Node object * *@return The phase value */ public Phase getPhase() { return phase; } /** * @return phase number */ public int getPhaseNum(){ return phase.getPhaseNum(); } /** * Gets the OutPorts attribute of the Node object * *@return Collection of OutPorts *@since April 18, 2002 */ public Collection<OutputPort> getOutPorts() { return outPorts.values(); } /** * @return map with all output ports (key is index of output port) */ public Map<Integer, OutputPort> getOutputPorts() { return outPorts; } /** * Gets the InPorts attribute of the Node object * *@return Collection of InPorts *@since April 18, 2002 */ public Collection<InputPort> getInPorts() { return inPorts.values(); } /** * @return map with all input ports (key is index of input port) */ public Map<Integer, InputPort> getInputPorts() { return inPorts; } /** * Gets the metadata on output ports of the Node object * *@return Collection of output ports metadata */ public List<DataRecordMetadata> getOutMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(outPorts.size()); for(Iterator<OutputPort> it = getOutPorts().iterator(); it.hasNext();) { ret.add(it.next().getMetadata()); } return ret; } /** * Gets the metadata on output ports of the Node object * * @return array of output ports metadata */ public DataRecordMetadata[] getOutMetadataArray() { return getOutMetadata().toArray(new DataRecordMetadata[0]); } /** * Gets the metadata on input ports of the Node object * *@return Collection of input ports metadata */ public List<DataRecordMetadata> getInMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(inPorts.size()); for(Iterator<InputPort> it = getInPorts().iterator(); it.hasNext();) { ret.add(it.next().getMetadata()); } return ret; } /** * Gets the metadata on input ports of the Node object * * @return array of input ports metadata */ public DataRecordMetadata[] getInMetadataArray() { return getInMetadata().toArray(new DataRecordMetadata[0]); } /** * Gets the number of records passed through specified port type and number * *@param portType Port type (IN, OUT, LOG) *@param portNum port number (0...) *@return The RecordCount value *@since May 17, 2002 *@deprecated */ @Deprecated public long getRecordCount(char portType, int portNum) { long count; // Integer used as key to TreeMap containing ports Integer port = Integer.valueOf(portNum); try { switch (portType) { case OUTPUT_PORT: count = ((OutputPort) outPorts.get(port)).getOutputRecordCounter(); break; case INPUT_PORT: count = ((InputPort) inPorts.get(port)).getInputRecordCounter(); break; default: count = -1; } } catch (Exception ex) { count = -1; } return count; } /** * Gets the result code of finished Node.<br> * *@return The Result value *@since July 29, 2002 *@see org.jetel.graph.Node.Result */ public Result getResultCode() { synchronized (runResultMonitor) { return runResult; } } /** * Sets the result code of component. * @param result */ public void setResultCode(Result result) { synchronized (runResultMonitor) { this.runResult = result; } } /** * Sets the component result to new value if and only if the current result equals to the given expectation. * This is atomic operation for 'if' and 'set'. * @param newResult new component result * @param expectedOldResult expected value of current result */ public void setResultCode(Result newResult, Result expectedOldResult) { synchronized (runResultMonitor) { if (runResult == expectedOldResult) { runResult = newResult; } } } /** * Gets the ResultMsg of finished Node.<br> * This message briefly describes what caused and error (if there was any). * *@return The ResultMsg value *@since July 29, 2002 */ public String getResultMsg() { Result result = getResultCode(); return result != null ? result.message() : null; } /** * Gets exception which caused Node to fail execution - if * there was such failure. * * @return * @since 13.12.2006 */ public Throwable getResultException(){ return resultException; } // Operations /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public void init() throws ComponentNotReadyException { super.init(); setResultCode(Result.READY); refreshBufferedValues(); //initialise component token tracker if necessary if (getGraph() != null && getGraph().getJobType() == JobType.JOBFLOW && getGraph().getRuntimeContext().isTokenTracking()) { tokenTracker = createComponentTokenTracker(); } else { tokenTracker = new PrimitiveComponentTokenTracker(this); } } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#preExecute() */ @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); //cluster related settings can be used only in cluster environment if (!getGraph().getAuthorityProxy().isClusterEnabled()) { //cluster components cannot be used in non-cluster environment if (ClusterUtils.isClusterComponent(getType())) { throw new JetelRuntimeException("Cluster component cannot be used in non-cluster environment."); } //non empty allocation is not allowed in non-cluster environment EngineComponentAllocation allocation = getAllocation(); if (allocation != null && !allocation.isInferedFromNeighbours()) { throw new JetelRuntimeException("Component allocation cannot be specified in non-cluster environment."); } } setResultCode(Result.RUNNING); } /** * main execution method of Node (calls in turn execute()) * *@since April 2, 2002 */ @Override public void run() { setResultCode(Result.RUNNING); // set running result, so we know run() method was started Context c = ContextProvider.registerNode(this); try { //store the current thread like a node executor setNodeThread(Thread.currentThread()); //we need a synchronization point for all components in a phase //watchdog starts all components in phase and wait on this barrier for real startup preExecuteBarrier.await(); //preExecute() invocation try { preExecute(); } catch (Throwable e) { throw new ComponentNotReadyException(this, "Component pre-execute initialization failed.", e); } //waiting for other nodes in the current phase - first all pre-execution has to be done at all nodes executeBarrier.await(); //execute() invocation Result result = execute(); //broadcast all output ports with EOF information broadcastEOF(); //set the result of execution to the component (broadcastEOF needs to be done before this set, see CLO-1364) setResultCode(result); if (result == Result.ERROR) { Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), resultMessage != null ? resultMessage : Result.ERROR.message(), null)); sendMessage(msg); } if (result == Result.FINISHED_OK) { if (runIt == false) { //component returns ok tag, but the component was actually aborted setResultCode(Result.ABORTED); } else if (checkEofOnInputPorts()) { // true by default //check whether all input ports are already closed for (InputPort inputPort : getInPorts()) { if (!inputPort.isEOF()) { setResultCode(Result.ERROR); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), createNodeException(new JetelRuntimeException("Component has finished and input port " + inputPort.getInputPortNumber() + " still contains some unread records.")))); sendMessage(msg); return; } } } } } catch (InterruptedException ex) { setResultCode(Result.ABORTED); } catch (Exception ex) { setResultCode(Result.ERROR); resultException = createNodeException(ex); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), resultException)); sendMessage(msg); } catch (Throwable ex) { logger.fatal(ex); setResultCode(Result.ERROR); resultException = createNodeException(ex); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), resultException)); sendMessage(msg); } finally { ContextProvider.unregister(c); sendFinishMessage(); setNodeThread(null); } } protected abstract Result execute() throws Exception; private Exception createNodeException(Throwable cause) { //compose error message, for example //"Component [Reformat:REFORMAT] finished with status ERROR. (In0: 11 recs, Out0: 10 recs, Out1: 0 recs)" String recordsMessage = MiscUtils.getInOutRecordsMessage(this); return new JetelRuntimeException("Component " + this + " finished with status ERROR." + (recordsMessage.length() > 0 ? " (" + recordsMessage + ")" : ""), cause); } /** * This method should be called every time when node finishes its work. */ private void sendFinishMessage() { //sends notification - node has finished sendMessage(Message.createNodeFinishedMessage(this)); } /** * Abort execution of Node - only inform node, that should finish processing. * *@since April 4, 2002 */ public void abort() { abort(null); } public void abort(Throwable cause) { int attempts = 30; runIt = false; synchronized (nodeThreadMonitor) { Thread nodeThread = getNodeThread(); if (nodeThread != null) { //rename node thread String newThreadName = "exNode_" + getGraph().getRuntimeContext().getRunId() + "_" + getGraph().getId() + "_" + getId(); if (logger.isTraceEnabled()) logger.trace("rename thread " + nodeThread.getName() + " to " + newThreadName); nodeThread.setName(newThreadName); //interrupt node threads while (!getResultCode().isStop() && attempts if (logger.isDebugEnabled()) { logger.debug("trying to interrupt thread " + nodeThread); } //interrupt main node thread nodeThread.interrupt(); //interrupt all child threads if any for (Thread childThread : getChildThreads()) { if (logger.isDebugEnabled()) { logger.debug("trying to interrupt child thread " + childThread); } childThread.interrupt(); } //wait some time for graph result try { Thread.sleep(10); } catch (InterruptedException e) { } } } } if (cause != null) { setResultCode(Result.ERROR); resultException = createNodeException(cause); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), resultException)); sendMessage(msg); sendFinishMessage(); } else if (!getResultCode().isStop()) { logger.debug("Node '" + getId() + "' was not interrupted in legal way."); setResultCode(Result.ABORTED); sendFinishMessage(); } } /** * @return thread of running node; <b>null</b> if node does not running */ public Thread getNodeThread() { synchronized (nodeThreadMonitor) { return nodeThread; } } /** * Sets actual thread in which this node current running. * @param nodeThread */ private void setNodeThread(Thread nodeThread) { synchronized (nodeThreadMonitor) { if(nodeThread != null) { this.nodeThread = nodeThread; //thread context classloader is preset to a reasonable classloader //this is just for sure, threads are recycled and no body can guarantee which context classloader remains preset nodeThread.setContextClassLoader(this.getClass().getClassLoader()); String oldName = nodeThread.getName(); long runId = getGraph().getRuntimeContext().getRunId(); nodeThread.setName(getId()+"_"+runId); MDC.put("runId", getGraph().getRuntimeContext().getRunId()); if (logger.isTraceEnabled()) { logger.trace("set thread name; old:"+oldName+" new:"+ nodeThread.getName()); logger.trace("set thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName()); } } else { MDC.remove("runId"); long runId = getGraph().getRuntimeContext().getRunId(); if (logger.isTraceEnabled()) logger.trace("reset thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName()); this.nodeThread.setName("<unnamed>"); this.nodeThread = null; } } } /** * End execution of Node - let Node finish gracefully * *@since April 4, 2002 */ public void end() { runIt = false; } public void sendMessage(Message<?> msg) { CloverPost post = getGraph().getPost(); if (post != null) { post.sendMessage(msg); } else { getLog().info("Component reports a message, but its graph is already released. Message: " + msg.toString()); } } /** * An operation that adds port to list of all InputPorts * *@param port Port (Input connection) to be added *@since April 2, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ @Deprecated public void addInputPort(InputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } inPorts.put(Integer.valueOf(keyVal), port); port.connectReader(this, keyVal); } /** * An operation that adds port to list of all InputPorts * *@param portNum Number to be associated with this port *@param port Port (Input connection) to be added *@since April 2, 2002 */ public void addInputPort(int portNum, InputPort port) { inPorts.put(Integer.valueOf(portNum), port); port.connectReader(this, portNum); } /** * An operation that adds port to list of all OutputPorts * *@param port Port (Output connection) to be added *@since April 4, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ @Deprecated public void addOutputPort(OutputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } outPorts.put(Integer.valueOf(keyVal), port); port.connectWriter(this, keyVal); resetBufferedValues(); } /** * An operation that adds port to list of all OutputPorts * *@param portNum Number to be associated with this port *@param port The feature to be added to the OutputPort attribute *@since April 4, 2002 */ public void addOutputPort(int portNum, OutputPort port) { outPorts.put(Integer.valueOf(portNum), port); port.connectWriter(this, portNum); resetBufferedValues(); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPort getOutputPort(int portNum) { Object outPort=outPorts.get(Integer.valueOf(portNum)); if (outPort instanceof OutputPort) { return (OutputPort)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPort interface "+outPort.getClass().getName()); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPortDirect getOutputPortDirect(int portNum) { Object outPort=outPorts.get(Integer.valueOf(portNum)); if (outPort instanceof OutputPortDirect) { return (OutputPortDirect)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPortDirect interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPort getInputPort(int portNum) { Object inPort=inPorts.get(Integer.valueOf(portNum)); if (inPort instanceof InputPort) { return (InputPort)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPort interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPortDirect getInputPortDirect(int portNum) { Object inPort=inPorts.get(Integer.valueOf(portNum)); if (inPort instanceof InputPortDirect) { return (InputPortDirect)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPortDirect interface"); } /** * Removes input port. * @param inputPort */ public void removeInputPort(InputPort inputPort) { inPorts.remove(Integer.valueOf(inputPort.getInputPortNumber())); } /** * Removes output port. * @param outputPort */ public void removeOutputPort(OutputPort outputPort) { outPorts.remove(Integer.valueOf(outputPort.getOutputPortNumber())); resetBufferedValues(); } /** * An operation that does removes/unregisteres por<br> * Not yet implemented. * *@param _portNum Description of Parameter *@param _portType Description of Parameter *@since April 2, 2002 */ public void deletePort(int _portNum, char _portType) { throw new UnsupportedOperationException("Deleting port is not supported !"); } /** * An operation that writes one record through specified output port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's writeRecord() method. * *@param _portNum Description of Parameter *@param _record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecord(int _portNum, DataRecord _record) throws IOException, InterruptedException { ((OutputPort) outPorts.get(Integer.valueOf(_portNum))).writeRecord(_record); } /** * An operation that reads one record through specified input port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's readRecord() method. * *@param _portNum Description of Parameter *@param record Description of Parameter *@return Description of the Returned Value *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public DataRecord readRecord(int _portNum, DataRecord record) throws IOException, InterruptedException { return ((InputPort) inPorts.get(Integer.valueOf(_portNum))).readRecord(record); } /** * An operation that does ... * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecordBroadcast(DataRecord record) throws IOException, InterruptedException { for(int i=0;i<outPortsSize;i++){ outPortsArray[i].writeRecord(record); } } /** * Description of the Method * *@param recordBuffer Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since August 13, 2002 */ public void writeRecordBroadcastDirect(CloverBuffer recordBuffer) throws IOException, InterruptedException { for(int i=0;i<outPortsSize;i++){ ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * @deprecated use {@link #writeRecordBroadcastDirect(CloverBuffer)} instead */ @Deprecated public void writeRecordBroadcastDirect(ByteBuffer recordBuffer) throws IOException, InterruptedException { for(int i = 0; i < outPortsSize; i++) { ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * Closes all output ports - sends EOF signal to them. * @throws IOException * *@since April 11, 2002 */ public void closeAllOutputPorts() throws InterruptedException, IOException { for (OutputPort outputPort : getOutPorts()) { outputPort.eof(); } } /** * Send EOF (no more data) to all connected output ports * @throws IOException * *@since April 18, 2002 */ public void broadcastEOF() throws InterruptedException, IOException{ closeAllOutputPorts(); } /** * Closes specified output port - sends EOF signal. * *@param portNum Which port to close * @throws IOException *@since April 11, 2002 */ public void closeOutputPort(int portNum) throws InterruptedException, IOException { OutputPort port = (OutputPort) outPorts.get(Integer.valueOf(portNum)); if (port == null) { throw new RuntimeException(this.getId()+" - can't close output port \"" + portNum + "\" - does not exists!"); } port.eof(); } /** * Compares this Node to specified Object * * @param obj * Node to compare with * @return True if obj represents node with the same ID * @since April 18, 2002 */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Node)) { return false; } final Node other = (Node) obj; return getId().equals(other.getId()); } @Override public int hashCode(){ return getId().hashCode(); } /** * @return Object.hashCode(), which is based on identity */ public int hashCodeIdentity() { return super.hashCode(); } /** * Description of the Method * *@return Description of the Returned Value *@since May 21, 2002 *@deprecated implementation of this method is for now useless and is not required */ public void toXML(Element xmlElement) { //DO NOT IMPLEMENT THIS METHOD } /** * Description of the Method * *@param nodeXML Description of Parameter *@return Description of the Returned Value *@since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws Exception { throw new UnsupportedOperationException("not implemented in org.jetel.graph.Node"); } /** * @return <b>true</b> if node is enabled; <b>false</b> else */ public EnabledEnum getEnabled() { return enabled; } /** * @param enabled whether node is enabled */ public void setEnabled(String enabledStr) { enabled = EnabledEnum.fromString(enabledStr, EnabledEnum.ENABLED); } /** * @param enabled whether node is enabled */ public void setEnabled(EnabledEnum enabled) { this.enabled = (enabled != null ? enabled : EnabledEnum.ENABLED); } /** * @return index of "pass through" input port */ public int getPassThroughInputPort() { return passThroughInputPort; } /** * Sets "pass through" input port. * @param passThroughInputPort */ public void setPassThroughInputPort(int passThroughInputPort) { this.passThroughInputPort = passThroughInputPort; } /** * @return index of "pass through" output port */ public int getPassThroughOutputPort() { return passThroughOutputPort; } /** * Sets "pass through" output port * @param passThroughOutputPort */ public void setPassThroughOutputPort(int passThroughOutputPort) { this.passThroughOutputPort = passThroughOutputPort; } /** * @return node allocation in parallel processing (cluster environment) */ public EngineComponentAllocation getAllocation() { return allocation; } /** * @param required node allocation in parallel processing (cluster environment) */ public void setAllocation(EngineComponentAllocation alloc) { this.allocation = alloc; } protected void resetBufferedValues(){ outPortsArray=null; outPortsSize=0; } protected void refreshBufferedValues(){ Collection<OutputPort> op = getOutPorts(); outPortsArray = (OutputPort[]) op.toArray(new OutputPort[op.size()]); outPortsSize = outPortsArray.length; } /** * Checks number of input ports, whether is in the given interval. * @param status * @param min * @param max * @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge) * @return true if the number of input ports is in the given interval; else false */ protected boolean checkInputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) { boolean retValue = true; Collection<InputPort> inPorts = getInPorts(); if(inPorts.size() < min) { status.add(new ConfigurationProblem("At least " + min + " input port must be defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } if(inPorts.size() > max) { status.add(new ConfigurationProblem("At most " + max + " input ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } int index = 0; for (InputPort inputPort : inPorts) { if (inputPort.getMetadata() == null){ //TODO interface for matadata status.add(new ConfigurationProblem("Metadata on input port " + inputPort.getInputPortNumber() + " are not defined!", Severity.WARNING, this, Priority.NORMAL)); retValue = false; } if (checkNonAssignedPorts && inputPort.getInputPortNumber() != index){ status.add(new ConfigurationProblem("Input port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } index++; } return retValue; } protected boolean checkInputPorts(ConfigurationStatus status, int min, int max) { return checkInputPorts(status, min, max, true); } /** * Checks number of output ports, whether is in the given interval. * @param status * @param min * @param max * @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge) * @return true if the number of output ports is in the given interval; else false */ protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) { Collection<OutputPort> outPorts = getOutPorts(); if(outPorts.size() < min) { status.add(new ConfigurationProblem("At least " + min + " output port must be defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } if(outPorts.size() > max) { status.add(new ConfigurationProblem("At most " + max + " output ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } int index = 0; for (OutputPort outputPort : outPorts) { if (outputPort.getMetadata() == null){ status.add(new ConfigurationProblem("Metadata on output port " + outputPort.getOutputPortNumber() + " are not defined!", Severity.WARNING, this, Priority.NORMAL)); return false; } if (checkNonAssignedPorts && outputPort.getOutputPortNumber() != index){ status.add(new ConfigurationProblem("Output port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } index++; } return true; } protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max) { return checkOutputPorts(status, min, max, true); } /** * Checks if metadatas in given list are all equal * * @param status * @param metadata list of metadata to check * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata){ return checkMetadata(status, metadata, (Collection<DataRecordMetadata>)null); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * * @param status * @param inMetadata * @param outMetadata * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata){ return checkMetadata(status, inMetadata, outMetadata, true); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * If checkFixDelType is true then checks fixed/delimited state. * * @param status * @param inMetadata * @param outMetadata * @param checkFixDelType * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata, boolean checkFixDelType){ Iterator<DataRecordMetadata> iterator = inMetadata.iterator(); DataRecordMetadata metadata = null, nextMetadata; if (iterator.hasNext()) { metadata = iterator.next(); } //check input metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } if (outMetadata == null) { return status; } //check if input metadata equals output metadata iterator = outMetadata.iterator(); if (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata, checkFixDelType)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } //check output metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } return status; } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, Collection<DataRecordMetadata> outMetadata){ Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); return checkMetadata(status, inputMetadata, outMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, DataRecordMetadata outMetadata){ Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inMetadata, outputMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, DataRecordMetadata outMetadata) { Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inputMetadata, outputMetadata); } /** * The given thread is registered as a child thread of this component. * The child threads are exploited for gathering of tracking information - CPU usage of this component * is sum of all threads. * @param childThread */ public void registerChildThread(Thread childThread) { childThreads.add(childThread); } /** * The given threads are registered as child threads of this component. * The child threads are exploited for gathering of tracking information - for instance * CPU usage of this component is sum of all threads. * @param childThreads */ protected void registerChildThreads(List<Thread> childThreads) { this.childThreads.addAll(childThreads); } /** * @return list of all child threads - threads running under this component */ public List<Thread> getChildThreads() { return new ArrayList<Thread>(childThreads); //duplicate is returned to ensure thread safety } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#reset() * @deprecated see {@link org.jetel.graph.IGraphElement#preExecute()} and {@link org.jetel.graph.IGraphElement#postExecute()} methods */ @Override @Deprecated synchronized public void reset() throws ComponentNotReadyException { super.reset(); runIt = true; setResultCode(Result.READY); resultMessage = null; resultException = null; childThreads.clear(); } @Override public synchronized void free() { super.free(); childThreads.clear(); } /** * This method is intended to be overridden. * @return URLs which this component is using */ public String[] getUsedUrls() { return new String[0]; } public void setPreExecuteBarrier(CyclicBarrier preExecuteBarrier) { this.preExecuteBarrier = preExecuteBarrier; } public void setExecuteBarrier(CyclicBarrier executeBarrier) { this.executeBarrier = executeBarrier; } /** * That is not nice solution to make public this variable. Unfortunately this is necessary * for new ComponentAlgorithm interface. Whenever this class will be removed also this * getter can be removed. * @return current status of runIt variable */ public boolean runIt() { return runIt; } @Override public void workerFinished(Event e) { // ignore by default } @Override public void workerCrashed(Event e) { //e.getException().printStackTrace(); resultException = e.getException(); abort(e.getException()); } /** * @return token tracker for this component or null cannot be returned, * at least {@link PrimitiveComponentTokenTracker} is returned. */ public ComponentTokenTracker getTokenTracker() { return tokenTracker; } /** * Creates suitable token tracker for this component. {@link ComplexComponentTokenTracker} is used by default. * This method is intended to be overridden if custom type of token tracking is necessary. */ protected ComponentTokenTracker createComponentTokenTracker() { return new ComplexComponentTokenTracker(this); } /** * Can be overridden by components to avoid default checking of input ports - * all input ports are checked whether EOF flag was reached * after the component finish processing. * * @see com.cloveretl.server.graph.RemoteEdgeDataTransmitter * @return */ protected boolean checkEofOnInputPorts() { return true; } }
// DisplayService.java package imagej.display; import imagej.IService; import imagej.ImageJ; import imagej.Service; import imagej.data.DataObject; import imagej.data.Dataset; import imagej.display.event.DisplayActivatedEvent; import imagej.display.event.DisplayCreatedEvent; import imagej.display.event.DisplayDeletedEvent; import imagej.display.event.window.WinActivatedEvent; import imagej.display.event.window.WinClosedEvent; import imagej.event.EventSubscriber; import imagej.event.Events; import imagej.object.ObjectService; import imagej.plugin.InstantiableException; import imagej.plugin.PluginInfo; import imagej.plugin.PluginService; import imagej.util.Log; import java.util.ArrayList; import java.util.List; /** * Service for working with {@link Display}s. * * @author Barry DeZonia * @author Curtis Rueden * @author Grant Harris */ @Service(priority = Service.NORMAL_PRIORITY) public final class DisplayService implements IService { private Display activeDisplay; /** Maintain list of subscribers, to avoid garbage collection. */ private List<EventSubscriber<?>> subscribers; // -- DisplayService methods -- /** Gets the currently active {@link Display}. */ public Display getActiveDisplay() { return activeDisplay; } /** Sets the currently active {@link Display}. */ public void setActiveDisplay(final Display display) { activeDisplay = display; Events.publish(new DisplayActivatedEvent(display)); } /** * Gets the active {@link Dataset}, if any, of the currently active * {@link Display}. */ public Dataset getActiveDataset() { return getActiveDataset(activeDisplay); } /** * Gets the active {@link DatasetView}, if any, of the currently active * {@link Display}. */ public DatasetView getActiveDatasetView() { return getActiveDatasetView(activeDisplay); } /** Gets the active {@link Dataset}, if any, of the given {@link Display}. */ public Dataset getActiveDataset(final Display display) { final DatasetView activeDatasetView = getActiveDatasetView(display); return activeDatasetView == null ? null : activeDatasetView .getDataObject(); } /** Gets the active {@link DatasetView}, if any, of the given {@link Display}. */ public DatasetView getActiveDatasetView(final Display display) { if (display == null) { return null; } final DisplayView activeView = display.getActiveView(); if (activeView instanceof DatasetView) { return (DatasetView) activeView; } return null; } /** Gets a list of all available {@link Display}s. */ public List<Display> getDisplays() { final ObjectService objectService = ImageJ.get(ObjectService.class); return objectService.getObjects(Display.class); } /** * Gets a list of {@link Display}s containing the given {@link DataObject}. */ public List<Display> getDisplays(final DataObject dataObject) { final ArrayList<Display> displays = new ArrayList<Display>(); for (final Display display : getDisplays()) { // check whether data object is present in this display for (final DisplayView view : display.getViews()) { if (dataObject == view.getDataObject()) { displays.add(display); break; } } } return displays; } public boolean isUniqueName(final String name) { final List<Display> displays = getDisplays(); for (final Display display : displays) { if (name.equalsIgnoreCase(display.getName())) { return false; } } return true; } /** Creates a {@link Display} and adds the given {@link Dataset} as a view. */ public Display createDisplay(final Dataset dataset) { // get available display plugins from the plugin service final PluginService pluginService = ImageJ.get(PluginService.class); final List<PluginInfo<Display>> plugins = pluginService.getPluginsOfType(Display.class); for (final PluginInfo<Display> pe : plugins) { try { final Display displayPlugin = pe.createInstance(); // display dataset using the first compatible DisplayPlugin // TODO: how to handle multiple matches? prompt user with dialog box? if (displayPlugin.canDisplay(dataset)) { displayPlugin.display(dataset); Events.publish(new DisplayCreatedEvent(displayPlugin)); return displayPlugin; } } catch (final InstantiableException e) { Log.error("Invalid display plugin: " + pe, e); } } return null; } // -- IService methods -- @Override public void initialize() { activeDisplay = null; subscribeToEvents(); } // -- Helper methods -- private void subscribeToEvents() { subscribers = new ArrayList<EventSubscriber<?>>(); // dispose views and delete display when display window is closed final EventSubscriber<WinClosedEvent> winClosedSubscriber = new EventSubscriber<WinClosedEvent>() { @Override public void onEvent(final WinClosedEvent event) { final Display display = event.getDisplay(); final ArrayList<DisplayView> views = new ArrayList<DisplayView>(display.getViews()); for (final DisplayView view : views) { view.dispose(); } // HACK - Necessary to plug memory leak when closing the last window. // Might be slow since it has to walk the whole ObjectService object // list. Note that we could ignore this. Next created display will // make old invalid activeDataset reference reclaimable. if (getDisplays().size() == 1) setActiveDisplay(null); Events.publish(new DisplayDeletedEvent(display)); } }; subscribers.add(winClosedSubscriber); Events.subscribe(WinClosedEvent.class, winClosedSubscriber); // set display to active when its window is activated final EventSubscriber<WinActivatedEvent> winActivatedSubscriber = new EventSubscriber<WinActivatedEvent>() { @Override public void onEvent(final WinActivatedEvent event) { final Display display = event.getDisplay(); setActiveDisplay(display); } }; subscribers.add(winActivatedSubscriber); Events.subscribe(WinActivatedEvent.class, winActivatedSubscriber); } }
package arez.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicate that the named Arez compiler warnings should be suppressed in the * annotated element (and in all program elements contained in the annotated * element). Note that the set of warnings suppressed in a given element is * a superset of the warnings suppressed in all containing elements. For * example, if you annotate a class to suppress one warning and annotate a * method to suppress another, both warnings will be suppressed in the method. * * <p>As a matter of style, programmers should always use this annotation * on the most deeply nested element where it is effective. If you want to * suppress a warning in a particular method, you should annotate that * method rather than its class.</p> * * <p>This class may be used instead of {@link SuppressWarnings} when the compiler * is passed compiled classes. The {@link SuppressWarnings} has a source retention * policy and is thus not available when the files are already compiled and is thus * not useful when attempting to suppress warnings in already compiled code.</p> */ @Target( { ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE } ) @Retention( RetentionPolicy.CLASS ) public @interface SuppressArezWarnings { /** * The set of warnings that are to be suppressed by the compiler in the * annotated element. Duplicate names are permitted. The second and * successive occurrences of a name are ignored. * * @return the set of warnings to be suppressed */ String[] value(); }
package edu.umich.verdict.dbms; import com.google.common.base.Optional; import edu.umich.verdict.datatypes.SampleSizeInfo; import edu.umich.verdict.relation.ExactRelation; import edu.umich.verdict.relation.Relation; import edu.umich.verdict.relation.SingleRelation; import edu.umich.verdict.relation.expr.Expr; import edu.umich.verdict.util.VerdictLogger; import org.apache.commons.lang3.tuple.Pair; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import com.google.common.base.Joiner; import edu.umich.verdict.VerdictContext; import edu.umich.verdict.datatypes.SampleParam; import edu.umich.verdict.datatypes.TableUniqueName; import edu.umich.verdict.exceptions.VerdictException; import edu.umich.verdict.util.StringManipulations; import scala.math.Ordering; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class DbmsPostgreSQL extends DbmsJDBC { public DbmsPostgreSQL(VerdictContext vc, String dbName, String host, String port, String schema, String user, String password, String jdbcClassName) throws VerdictException{ super(vc, dbName, host, port, schema, user, password, jdbcClassName); } @Override public String getQuoteString() {return "\""; } @Override public void createCatalog(String catalog) throws VerdictException{ String sql = String.format("create schema if not exists %s", catalog); executeUpdate(sql); } @Override public void changeDatabase(String schemaName) throws VerdictException{ setSearchPath(schemaName); String[] schemaList = schemaName.split(","); String primarySchema = schemaList[0]; currentSchema = Optional.fromNullable(primarySchema); if (schemaList.length > 1) { VerdictLogger.info(String.format("Search path changed to: %s. For the tables speficied without their" + " schemas, Verdict assumes that they are in a primary schema (%s). This limitation will be" + " fixed in a future release.", schemaName, primarySchema)); } else { VerdictLogger.info(String.format("Search path changed to: %s.", schemaName)); } } @Override public void insertEntry(TableUniqueName tableName, List<Object> values) throws VerdictException{ StringBuilder sql = new StringBuilder(1000); sql.append(String.format("insert into %s values ", tableName)); sql.append("("); String with = "'"; sql.append(Joiner.on(", ").join(StringManipulations.quoteString(values, with))); sql.append(")"); executeUpdate(sql.toString()); } @Override protected String randomPartitionColumn(){ int pcount = partitionCount(); return String.format("mod(cast(round(RANDOM()*%d) as integer), %d) AS %s", pcount, pcount, partitionColumnName()); } @Override protected String randomNumberExpression(SampleParam param){ String expr = "RANDOM()"; return expr; } @Override public String modOfHash(String col, int mod){ return String.format("MOD(CAST(CAST(CONCAT('x', SUBSTR(MD5(cast(%s%s%s as text)),0,8)) AS bit(32)) AS bigint), %d)", getQuoteString(), col, getQuoteString(), mod); } @Override public String modOfHash(List<String> columns, int mod) { String concatStr = ""; for (int i = 0; i < columns.size(); i++) { String col = columns.get(i); String castStr = String.format("cast(%s%s%s as text)", getQuoteString(), col, getQuoteString()); if (i < columns.size() - 1) { castStr += String.format(",'%s',", HASH_DELIM); } concatStr += castStr; } return String.format("MOD(CAST(CAST(CONCAT('x', SUBSTR(MD5(CONCAT(%s)),0,8)) AS bit(32)) AS bigint), %d)", concatStr, mod); } @Override protected String modOfRand(int mod){ return String.format("RANDOM() %% %d", mod); } @Override protected long attachUniformProbabilityToTempTable(SampleParam param, TableUniqueName temp) throws VerdictException{ String samplingProbCol = vc.getDbms().samplingProbabilityColumnName(); long total_size = SingleRelation.from(vc, param.getOriginalTable()).countValue(); long sample_size = SingleRelation.from(vc, temp).countValue(); ExactRelation withRand = SingleRelation.from(vc, temp).select("*, " + String.format( "cast (%d as float) / cast (%d as float) as %s", sample_size, total_size, samplingProbCol)); dropTable(param.sampleTableName()); String sql = String.format("create table %s as %s", param.sampleTableName(), withRand.toSql()); VerdictLogger.debug(this, "The query used for creating a temporary table without sampling probabilities;"); executeUpdate(sql); return sample_size; } @Override protected long createUniverseSampleWithProbFromSample(SampleParam param, TableUniqueName temp) throws VerdictException { String samplingProbCol = vc.getDbms().samplingProbabilityColumnName(); ExactRelation sampled = SingleRelation.from(vc, temp); long total_size = SingleRelation.from(vc, param.getOriginalTable()).countValue(); long sample_size = sampled.countValue(); ExactRelation withProb = sampled .select(String.format("*, cast (%d as float) / cast (%d as float) AS %s", sample_size, total_size, samplingProbCol) + ", " + universePartitionColumn(param.getColumnNames().get(0))); String sql = String.format("create table %s AS %s", param.sampleTableName(), withProb.toSql()); VerdictLogger.debug(this, "The query used for creating a universe sample with sampling probability:"); // VerdictLogger.debugPretty(this, Relation.prettyfySql(vc, sql), " "); // VerdictLogger.debug(this, sql); executeUpdate(sql); return sample_size; } @Override protected void createStratifiedSampleFromGroupSizeTemp(SampleParam param, TableUniqueName groupSizeTemp) throws VerdictException{ Map<String, String> col2types = vc.getMeta().getColumn2Types(param.getOriginalTable()); SampleSizeInfo info = vc.getMeta() .getSampleSizeOf(new SampleParam(vc, param.getOriginalTable(), "uniform", null, new ArrayList<String>())); long originalTableSize = info.originalTableSize; long groupCount = SingleRelation.from(vc, groupSizeTemp).countValue(); String samplingProbColName = vc.getDbms().samplingProbabilityColumnName(); // equijoin expression that considers possible null values List<Pair<Expr, Expr>> joinExprs = new ArrayList<Pair<Expr, Expr>>(); for (String col : param.getColumnNames()) { boolean isString = false; boolean isTimeStamp = false; if (col2types.containsKey(col)) { if (col2types.get(col).toLowerCase().contains("char") || col2types.get(col).toLowerCase().contains("str")) { isString = true; } else if (col2types.get(col).toLowerCase().contains("time")) { isTimeStamp = true; } } if (isString) { Expr left = Expr.from(vc, String.format("case when s.%s%s%s is null then '%s' else s.%s%s%s end", getQuoteString(), col, getQuoteString(), NULL_STRING, getQuoteString(), col, getQuoteString())); Expr right = Expr.from(vc, String.format("case when t.%s%s%s is null then '%s' else t.%s%s%s end", getQuoteString(), col, getQuoteString(), NULL_STRING, getQuoteString(), col, getQuoteString())); joinExprs.add(Pair.of(left, right)); } else if (isTimeStamp) { Expr left = Expr.from(vc, String.format("case when s.%s%s%s is null then '%s' else s.%s%s%s end", getQuoteString(), col, getQuoteString(), NULL_TIMESTAMP, getQuoteString(), col, getQuoteString())); Expr right = Expr.from(vc, String.format("case when t.%s%s%s is null then '%s' else t.%s%s%s end", getQuoteString(), col, getQuoteString(), NULL_TIMESTAMP, getQuoteString(), col, getQuoteString())); joinExprs.add(Pair.of(left, right)); } else { Expr left = Expr.from(vc, String.format("case when s.%s%s%s is null then %d else s.%s%s%s end", getQuoteString(), col, getQuoteString(), NULL_LONG, getQuoteString(), col, getQuoteString())); Expr right = Expr.from(vc, String.format("case when t.%s%s%s is null then %d else t.%s%s%s end", getQuoteString(), col, getQuoteString(), NULL_LONG, getQuoteString(), col, getQuoteString())); joinExprs.add(Pair.of(left, right)); } } // where clause using rand function String whereClause = String.format("%s < %d * %f / %d / %s", randNumColname, originalTableSize, param.getSamplingRatio(), groupCount, groupSizeColName); // this should set to an appropriate variable. List<Pair<Integer, Double>> samplingProbForSize = vc.getConf().samplingProbabilitiesForStratifiedSamples(); whereClause += String.format(" OR %s < (case", randNumColname); for (Pair<Integer, Double> sizeProb : samplingProbForSize) { int size = sizeProb.getKey(); double prob = sizeProb.getValue(); whereClause += String.format(" when %s >= %d then %f * %d / %s", groupSizeColName, size, prob, size, groupSizeColName); } whereClause += " else 1.0 end)"; // aliased select list List<String> selectElems = new ArrayList<String>(); for (String col : col2types.keySet()) { selectElems.add(String.format("s.%s%s%s", getQuoteString(), col, getQuoteString())); } // sample table TableUniqueName sampledNoRand = Relation.getTempTableName(vc, param.sampleTableName().getSchemaName()); ExactRelation sampled = SingleRelation.from(vc, param.getOriginalTable()) .select(String.format("*, %s as %s", randomNumberExpression(param), randNumColname)).withAlias("s") .join(SingleRelation.from(vc, groupSizeTemp).withAlias("t"), joinExprs).where(whereClause) .select(Joiner.on(", ").join(selectElems) + ", " + groupSizeColName); String sql1 = String.format("create table %s as %s", sampledNoRand, sampled.toSql()); VerdictLogger.debug(this, "The query used for creating a stratified sample without sampling probabilities."); // VerdictLogger.debugPretty(this, Relation.prettyfySql(vc, sql1), " "); executeUpdate(sql1); // attach sampling probabilities and random partition number ExactRelation sampledGroupSize = SingleRelation.from(vc, sampledNoRand).groupby(param.getColumnNames()) .agg("count(*) AS " + groupSizeInSampleColName); ExactRelation withRand = SingleRelation.from(vc, sampledNoRand).withAlias("s") .join(sampledGroupSize.withAlias("t"), joinExprs).select( Joiner.on(", ").join(selectElems) + String.format(", cast(%s as float) / cast(%s as float) as %s", groupSizeInSampleColName, groupSizeColName, samplingProbColName) + ", " + randomPartitionColumn()); String parquetString = ""; if (vc.getConf().areSamplesStoredAsParquet()) { parquetString = getParquetString(); } String sql2 = String.format("create table %s%s as %s", param.sampleTableName(), parquetString, withRand.toSql()); VerdictLogger.debug(this, "The query used for creating a stratified sample with sampling probabilities."); // VerdictLogger.debugPretty(this, Relation.prettyfySql(vc, sql2), " "); // VerdictLogger.debug(this, sql2); executeUpdate(sql2); dropTable(sampledNoRand, false); } @Override String composeUrl(String dbms, String host, String port, String schema, String user, String password) throws VerdictException{ StringBuilder url = new StringBuilder(); url.append(String.format("jdbc:%s://%s:%s", dbms, host, port)); if (schema != null) { url.append(String.format("/%s", schema)); } if (!vc.getConf().ignoreUserCredentials() && user != null && user.length() != 0) { url.append("?"); url.append(String.format("user=%s", user)); } if (!vc.getConf().ignoreUserCredentials() && password != null && password.length() != 0) { url.append("&"); url.append(String.format("password=%s", password)); } // pass other configuration options. for (Map.Entry<String, String> pair : vc.getConf().getConfigs().entrySet()) { String key = pair.getKey(); String value = pair.getValue(); if (key.startsWith("verdict") || key.equals("user") || key.equals("password")) { continue; } url.append(String.format("&%s=%s", key, value)); } return url.toString(); } private String getSearchPath() throws VerdictException { ResultSet rs = executeJdbcQuery("show search_path"); List<String> searchList = new ArrayList<String>(); try { while (rs.next()) { String[] schemaList = rs.getString(1).split(","); for (String a : schemaList) { searchList.add(StringManipulations.stripQuote(a).trim()); } } } catch (SQLException e) { throw new VerdictException(e); } String searchPath = Joiner.on(",").join(searchList); return searchPath; } private void setSearchPath(String search_path) throws VerdictException { List<String> quotedSchemaList = Arrays.asList(search_path.split(",")); quotedSchemaList = StringManipulations.quoteEveryString(quotedSchemaList, getQuoteString()); executeJdbcQuery(String.format("set search_path=%s", Joiner.on(",").join(quotedSchemaList))); } @Override public ResultSet describeTableInResultSet(TableUniqueName tableUniqueName) throws VerdictException { String schemaName = tableUniqueName.getSchemaName(); String tableName = tableUniqueName.getTableName(); String search_path = getSearchPath(); setSearchPath(schemaName); ResultSet rs = executeJdbcQuery( String.format("SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '%s' and table_schema = '%s'", tableName, schemaName)); setSearchPath(search_path); return rs; } @Override public ResultSet getTablesInResultSet(String schema) throws VerdictException { String search_path = getSearchPath(); setSearchPath(schema); ResultSet rs = executeJdbcQuery(String.format("SELECT DISTINCT table_name FROM information_schema.tables WHERE table_schema = '%s'", schema)); setSearchPath(search_path); return rs; } @Override public ResultSet getDatabaseNamesInResultSet() throws VerdictException { // return executeJdbcQuery("select nspname from pg_namespace WHERE datistemplate // = false"); return executeJdbcQuery("select nspname from pg_namespace"); } public void createMetaTablesInDMBS(TableUniqueName originalTableName, TableUniqueName sizeTableName, TableUniqueName nameTableName) throws VerdictException { VerdictLogger.debug(this, "Creates meta tables if not exist."); String sql = String.format("CREATE TABLE IF NOT EXISTS %s", sizeTableName) + " (schemaname VARCHAR(120), " + " tablename VARCHAR(120), " + " samplesize BIGINT, " + " originaltablesize BIGINT)"; executeUpdate(sql); sql = String.format("CREATE TABLE IF NOT EXISTS %s", nameTableName) + " (originalschemaname VARCHAR(120), " + " originaltablename VARCHAR(120), " + " sampleschemaaname VARCHAR(120), " + " sampletablename VARCHAR(120), " + " sampletype VARCHAR(120), " + " samplingratio float, " + " columnnames VARCHAR(120))"; executeUpdate(sql); VerdictLogger.debug(this, "Meta tables created."); } @Override public Dataset<Row> getDataset(){ // TODO Auto-generated method stub return null; } }
package com.sequenceiq.cloudbreak.cloud.azure; import static com.sequenceiq.cloudbreak.cloud.model.CloudInstance.INSTANCE_NAME; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Component; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimaps; import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.compute.PowerState; import com.microsoft.azure.management.compute.VirtualMachine; import com.microsoft.azure.management.resources.fluentcore.arm.models.HasName; import com.sequenceiq.cloudbreak.cloud.azure.client.AzureClient; import com.sequenceiq.cloudbreak.cloud.azure.status.AzureInstanceStatus; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException; import com.sequenceiq.cloudbreak.cloud.model.CloudInstance; import com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus; import com.sequenceiq.cloudbreak.cloud.model.InstanceStatus; import rx.Completable; import rx.schedulers.Schedulers; @Component public class AzureVirtualMachineService { private static final Logger LOGGER = LoggerFactory.getLogger(AzureVirtualMachineService.class); @Inject private AzureResourceGroupMetadataProvider azureResourceGroupMetadataProvider; @Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 60) public Map<String, VirtualMachine> getVirtualMachinesByName(AzureClient azureClient, String resourceGroup, Collection<String> privateInstanceIds) { LOGGER.debug("Starting to retrieve vm metadata from Azure for {} for ids: {}", resourceGroup, privateInstanceIds); PagedList<VirtualMachine> virtualMachines = azureClient.getVirtualMachines(resourceGroup); while (hasMissingVm(virtualMachines, privateInstanceIds) && virtualMachines.hasNextPage()) { virtualMachines.loadNextPage(); } errorIfEmpty(virtualMachines); validateResponse(virtualMachines, privateInstanceIds); return collectVirtualMachinesByName(privateInstanceIds, virtualMachines); } private Map<String, VirtualMachine> getVirtualMachinesByNameEmptyAllowed(AzureClient azureClient, String resourceGroup, Collection<String> privateInstanceIds) { LOGGER.debug("Starting to retrieve vm metadata gracefully from Azure for {} for ids: {}", resourceGroup, privateInstanceIds); PagedList<VirtualMachine> virtualMachines = azureClient.getVirtualMachines(resourceGroup); while (hasMissingVm(virtualMachines, privateInstanceIds) && virtualMachines.hasNextPage()) { virtualMachines.loadNextPage(); } validateResponse(virtualMachines, privateInstanceIds); return collectVirtualMachinesByName(privateInstanceIds, virtualMachines); } @Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 5) public AzureVirtualMachinesWithStatuses getVmsAndVmStatusesFromAzure(AuthenticatedContext ac, List<CloudInstance> cloudInstances) { return getUpdatedVMs(ac, cloudInstances); } public AzureVirtualMachinesWithStatuses getVmsAndVmStatusesFromAzureWithoutRetry(AuthenticatedContext ac, List<CloudInstance> cloudInstances) { return getUpdatedVMs(ac, cloudInstances); } private AzureVirtualMachinesWithStatuses getUpdatedVMs(AuthenticatedContext ac, List<CloudInstance> cloudInstances) { AzureVirtualMachinesWithStatuses virtualMachinesWithStatuses = getVmsFromAzureAndFillStatusesIfResourceGroupRemoved(ac, cloudInstances); LOGGER.info("VirtualMachines from Azure: {}", virtualMachinesWithStatuses.getVirtualMachines().keySet()); refreshInstanceViews(virtualMachinesWithStatuses.getVirtualMachines()); fillVmStatuses(cloudInstances, virtualMachinesWithStatuses); return virtualMachinesWithStatuses; } @Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 5) public void refreshInstanceViews(Map<String, VirtualMachine> virtualMachines) { LOGGER.info("Parallel instance views refresh to download instance view fields from azure, like PowerState of the machines: {}", virtualMachines.keySet()); List<Completable> refreshInstanceViewCompletables = new ArrayList<>(); for (VirtualMachine virtualMachine : virtualMachines.values()) { refreshInstanceViewCompletables.add(Completable.fromObservable(virtualMachine.refreshInstanceViewAsync()).subscribeOn(Schedulers.io())); } Completable.merge(refreshInstanceViewCompletables).await(); } private boolean hasMissingVm(PagedList<VirtualMachine> virtualMachines, Collection<String> privateInstanceIds) { Set<String> virtualMachineNames = virtualMachines .stream() .map(VirtualMachine::name) .collect(Collectors.toSet()); boolean hasMissingVm = !virtualMachineNames.containsAll(privateInstanceIds); if (hasMissingVm) { LOGGER.info("Fetched VM id-s ({}) do not contain one of the following id-s: {}", virtualMachineNames, privateInstanceIds); } return hasMissingVm; } private boolean hasNoVmInResourceGroup(PagedList<VirtualMachine> virtualMachines) { return virtualMachines.isEmpty(); } private Map<String, VirtualMachine> collectVirtualMachinesByName(Collection<String> privateInstanceIds, PagedList<VirtualMachine> virtualMachines) { return virtualMachines.stream() .filter(virtualMachine -> privateInstanceIds.contains(virtualMachine.name())) .collect(Collectors.toMap(HasName::name, vm -> vm)); } private void validateResponse(PagedList<VirtualMachine> virtualMachines, Collection<String> privateInstanceIds) { if (hasMissingVm(virtualMachines, privateInstanceIds)) { LOGGER.warn("Failed to retrieve all host from Azure. Only {} found from the {}.", virtualMachines.size(), privateInstanceIds.size()); } } private void errorIfEmpty(PagedList<VirtualMachine> virtualMachines) { if (hasNoVmInResourceGroup(virtualMachines)) { LOGGER.warn("Azure returned 0 vms when listing by resource group. This should not be possible, retrying"); throw new CloudConnectorException("Operation failed, azure returned an empty list while trying to list vms in resource group."); } } private AzureVirtualMachinesWithStatuses getVmsFromAzureAndFillStatusesIfResourceGroupRemoved(AuthenticatedContext ac, List<CloudInstance> cloudInstances) { LOGGER.info("Get vms from azure: {}", cloudInstances); List<CloudVmInstanceStatus> statuses = new ArrayList<>(); AzureClient azureClient = ac.getParameter(AzureClient.class); ArrayListMultimap<String, String> resourceGroupInstanceMultimap = cloudInstances.stream() .collect(Multimaps.toMultimap( cloudInstance -> azureResourceGroupMetadataProvider.getResourceGroupName(ac.getCloudContext(), cloudInstance), CloudInstance::getInstanceId, ArrayListMultimap::create)); Map<String, VirtualMachine> virtualMachines = new HashMap<>(); for (Map.Entry<String, Collection<String>> resourceGroupInstanceIdsMap : resourceGroupInstanceMultimap.asMap().entrySet()) { LOGGER.info("Get vms for resource group and add to all virtual machines: {}", resourceGroupInstanceIdsMap.getKey()); try { virtualMachines.putAll(getVirtualMachinesByNameEmptyAllowed(azureClient, resourceGroupInstanceIdsMap.getKey(), resourceGroupInstanceIdsMap.getValue())); } catch (CloudException e) { LOGGER.debug("Exception occurred during the list of Virtual Machines by resource group", e); for (String instance : resourceGroupInstanceIdsMap.getValue()) { cloudInstances.stream().filter(cloudInstance -> instance.equals(cloudInstance.getInstanceId())).findFirst().ifPresent(cloudInstance -> { if (e.body() != null && "ResourceNotFound".equals(e.body().code())) { statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.TERMINATED)); } else { String msg = String.format("Failed to get VM's state from Azure: %s", e.toString()); statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.UNKNOWN, msg)); } }); } } } return new AzureVirtualMachinesWithStatuses(virtualMachines, statuses); } private void fillVmStatuses(List<CloudInstance> cloudInstances, AzureVirtualMachinesWithStatuses virtualMachineListResult) { Map<String, VirtualMachine> virtualMachines = virtualMachineListResult.getVirtualMachines(); List<CloudVmInstanceStatus> statuses = virtualMachineListResult.getStatuses(); LOGGER.info("Fill vm statuses from returned virtualmachines from azure: {}", virtualMachines.keySet()); for (CloudInstance cloudInstance : cloudInstances) { virtualMachines.values().stream() .filter(virtualMachine -> virtualMachine.name().equals(cloudInstance.getInstanceId())) .findFirst() .ifPresentOrElse(virtualMachine -> { PowerState virtualMachinePowerState = virtualMachine.powerState(); String computerName = virtualMachine.computerName(); cloudInstance.putParameter(INSTANCE_NAME, computerName); statuses.add(new CloudVmInstanceStatus(cloudInstance, AzureInstanceStatus.get(virtualMachinePowerState))); }, () -> statuses.stream() .filter(cvis -> cvis.getCloudInstance().getInstanceId() != null && cvis.getCloudInstance().getInstanceId().equals(cloudInstance.getInstanceId())) .findAny() .ifPresentOrElse(cloudInstanceWithStatus -> logTheStatusOfTheCloudInstance(cloudInstanceWithStatus), () -> statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.TERMINATED)))); } } private void logTheStatusOfTheCloudInstance(CloudVmInstanceStatus cloudInstanceWithStatus) { LOGGER.info("Cloud instance '{}' could not be found in the response from Azure, but it's status already requested to be updated to '{}'", cloudInstanceWithStatus.getCloudInstance().getInstanceId(), cloudInstanceWithStatus.getStatus().name()); } }
package org.kohsuke.stapler.export; /** * Controls the portion of the object graph to be written to {@link DataWriter}. * * @author Kohsuke Kawaguchi * @see Model#writeTo(Object, TreePruner, DataWriter) */ public abstract class TreePruner { /** * Called before Hudson writes a new property. * * @return * null if this property shouldn't be written. Otherwise the returned {@link TreePruner} object * will be consulted to determine properties of the child object in turn. */ public abstract TreePruner accept(Object node, Property prop); public Range getRange() { return Range.ALL; } public static class ByDepth extends TreePruner { final int n; private ByDepth next; public ByDepth(int n) { this.n = n; } private ByDepth next() { if (next==null) next = new ByDepth(n+1); return next; } @Override public TreePruner accept(Object node, Property prop) { if (prop.visibility < n) return null; // not visible if (prop.inline) return this; return next(); } } /** * Probably the most common {@link TreePruner} that just visits the top object and its properties, * but none of the referenced objects. */ public static final TreePruner DEFAULT = new ByDepth(1); }
package org.realityforge.arez.api2; import java.util.ArrayList; import java.util.Comparator; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.TestOnly; public abstract class Observable extends Node { /** * The value that _workState is set to to optimize the detection of duplicate, * existing and new dependencies during tracking completion. */ private static final int IN_CURRENT_TRACKING = -1; /** * The value that _workState is when the observer has been added as new dependency * to derivation. */ static final int NOT_IN_CURRENT_TRACKING = 0; private final ArrayList<Observer> _observers = new ArrayList<>(); /** * True if passivation has been requested in transaction. * Used to avoid adding duplicates to passivation list. */ private boolean _pendingPassivation; /** * The workState variable contains some data used during processing of observable * at various stages. * * Within the scope of a tracking transaction, it is set to the id of the tracking * observer if the observable was observed. This enables an optimization that skips * adding this observer to the same observer multiple times. This optimization sometimes * ignored as nested transactions that observe the same observer will reset this value. * * When completing a tracking transaction the value may be set to {@link #IN_CURRENT_TRACKING} * or {@link #NOT_IN_CURRENT_TRACKING} but should be set to {@link #NOT_IN_CURRENT_TRACKING} after * {@link Transaction#completeTracking()} method is completed.. */ private int _workState; /** * The state of the observer that is least stale. * This cached value is used to avoid redundant propagations. */ @Nonnull private ObserverState _leastStaleObserverState = ObserverState.NOT_TRACKING; /** * The derivation that created this observable if any. */ @Nullable private final Observer _owner; Observable( @Nonnull final ArezContext context, @Nullable final String name ) { this( context, name, null ); } Observable( @Nonnull final ArezContext context, @Nullable final String name, @Nullable final Observer owner ) { super( context, name ); _owner = owner; } final void resetPendingPassivation() { _pendingPassivation = false; } final void reportObserved() { getContext().getTransaction().observe( this ); } final int getLastTrackerTransactionId() { return _workState; } final void setLastTrackerTransactionId( final int lastTrackerTransactionId ) { _workState = lastTrackerTransactionId; } final boolean isInCurrentTracking() { return IN_CURRENT_TRACKING == _workState; } final void putInCurrentTracking() { _workState = IN_CURRENT_TRACKING; } final void removeFromCurrentTracking() { _workState = NOT_IN_CURRENT_TRACKING; } @Nullable final Observer getOwner() { return _owner; } /** * Return true if this observable can passivate when it is no longer observable and activate when it is observable again. */ final boolean canPassivate() { return null != _owner; } /** * Return true if observable is active and notifying observers. */ final boolean isActive() { return null == _owner || ObserverState.NOT_TRACKING != _owner.getState(); } /** * Passivate the observable. * This means that the observable no longer has any listeners and can release resources associated * with generating values. (i.e. remove observers on any observables that are used to compute the * value of this observable). */ protected void passivate() { Guards.invariant( () -> null != _owner, () -> String.format( "Invoked passivate on observable named '%s' when owner is null.", getName() ) ); Guards.invariant( this::isActive, () -> String.format( "Invoked passivate on observable named '%s' when observable is not active.", getName() ) ); assert null != _owner; _owner.setState( ObserverState.NOT_TRACKING ); } /** * Activate the observable. * The reverse of {@link #passivate()}. */ protected void activate() { Guards.invariant( () -> !isActive(), () -> String.format( "Invoked activate on observable named '%s' when observable is already active.", getName() ) ); } @Nonnull final ArrayList<Observer> getObservers() { return _observers; } final boolean hasObservers() { return getObservers().size() > 0; } final void addObserver( @Nonnull final Observer observer ) { invariantObserversLinked(); Guards.invariant( () -> !getObservers().contains( observer ), () -> String.format( "Attempting to add observer named '%s' to observable named '%s' when observer is already observing observable.", observer.getName(), getName() ) ); if ( !getObservers().add( observer ) ) { Guards.fail( () -> String.format( "Failed to add observer named '%s' to observable named '%s'.", observer.getName(), getName() ) ); } final ObserverState state = observer.getState(); if ( _leastStaleObserverState.ordinal() > state.ordinal() ) { _leastStaleObserverState = state; } } final void removeObserver( @Nonnull final Observer observer ) { invariantObserversLinked(); final ArrayList<Observer> observers = getObservers(); if ( !observers.remove( observer ) ) { Guards.fail( () -> String.format( "Attempted to remove observer named '%s' from observable named '%s' but observer is not an observers.", observer.getName(), getName() ) ); } if ( observers.isEmpty() && canPassivate() ) { queueForPassivation(); } invariantObserversLinked(); } private void queueForPassivation() { Guards.invariant( this::canPassivate, () -> String.format( "Attempted to invoke queueForPassivation() on observable named '%s' but observer is not able to be passivated.", getName() ) ); Guards.invariant( () -> getObservers().isEmpty(), () -> String.format( "Attempted to invoke queueForPassivation() on observable named '%s' but observer has observers.", getName() ) ); if ( !_pendingPassivation ) { _pendingPassivation = true; getContext().getTransaction().queueForPassivation( this ); } } // Called by Atom when its value changes final void propagateChanged() { invariantLeastStaleObserverState(); if ( ObserverState.STALE != _leastStaleObserverState ) { _leastStaleObserverState = ObserverState.STALE; for ( final Observer observer : getObservers() ) { final ObserverState state = observer.getState(); if ( ObserverState.UP_TO_DATE == state ) { observer.setState( ObserverState.STALE ); } } } invariantLeastStaleObserverState(); } // Called by ComputedValue when it recalculate and its value changed final void propagateChangeConfirmed() { invariantLeastStaleObserverState(); if ( ObserverState.STALE != _leastStaleObserverState ) { _leastStaleObserverState = ObserverState.STALE; for ( final Observer observer : getObservers() ) { if ( ObserverState.POSSIBLY_STALE == observer.getState() ) { observer.setState( ObserverState.STALE ); } else if ( ObserverState.UP_TO_DATE == observer.getState() ) { // this happens during computing of `observer`, just keep _leastStaleObserverState up to date. _leastStaleObserverState = ObserverState.UP_TO_DATE; } } } invariantLeastStaleObserverState(); } // Used by computed when its dependency changed, but we don't wan't to immediately recompute. final void propagateMaybeChanged() { invariantLeastStaleObserverState(); if ( ObserverState.UP_TO_DATE == _leastStaleObserverState ) { _leastStaleObserverState = ObserverState.POSSIBLY_STALE; for ( final Observer observer : getObservers() ) { if ( ObserverState.UP_TO_DATE == observer.getState() ) { observer.setState( ObserverState.POSSIBLY_STALE ); } } } invariantLeastStaleObserverState(); } final void invariantObserversLinked() { getObservers().forEach( observer -> Guards.invariant( () -> observer.getDependencies().contains( this ), () -> String.format( "Observable named '%s' has observer named '%s' which does not contain observerable as dependency.", getName(), observer.getName() ) ) ); } final void invariantLeastStaleObserverState() { final ObserverState leastStaleObserverState = getObservers().stream(). map( Observer::getState ).min( Comparator.comparing( Enum::ordinal ) ).orElse( ObserverState.NOT_TRACKING ); Guards.invariant( () -> leastStaleObserverState.ordinal() >= _leastStaleObserverState.ordinal(), () -> String.format( "Calculated leastStaleObserverState on observable named '%s' is '%s' which is unexpectedly less than cached value '%s'.", getName(), leastStaleObserverState.name(), _leastStaleObserverState.name() ) ); } @TestOnly final boolean isPendingPassivation() { return _pendingPassivation; } @TestOnly final void setLeastStaleObserverState( @Nonnull final ObserverState leastStaleObserverState ) { _leastStaleObserverState = leastStaleObserverState; } @Nonnull @TestOnly final ObserverState getLeastStaleObserverState() { return _leastStaleObserverState; } @TestOnly final int getWorkState() { return _workState; } @TestOnly final void setPendingPassivation( final boolean pendingPassivation ) { _pendingPassivation = pendingPassivation; } }
package org.jboss.as.controller.operations.global; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILDREN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LOCALE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODEL_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RECURSIVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUEST_PROPERTIES; import java.util.Locale; import java.util.Map; import java.util.Set; import org.jboss.as.controller.Cancellable; import org.jboss.as.controller.ModelQueryOperationHandler; import org.jboss.as.controller.ModelUpdateOperationHandler; import org.jboss.as.controller.NewOperationContext; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ResultHandler; import org.jboss.as.controller.descriptions.DescriptionProvider; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.as.controller.registry.AttributeAccess.AccessType; import org.jboss.as.controller.registry.ModelNodeRegistration; import org.jboss.dmr.ModelNode; /** * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> * @version $Revision: 1.1 $ */ public class GlobalOperationHandlers { static final String[] NO_LOCATION = new String[0]; public static final ModelQueryOperationHandler READ_RESOURCE = new ModelQueryOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { try { final ModelNode result; if (operation.require(REQUEST_PROPERTIES).require(RECURSIVE).asBoolean()) { result = context.getSubModel().clone(); } else { result = new ModelNode(); final Set<String> childNames = context.getRegistry().getChildNames(PathAddress.pathAddress(operation.require(ADDRESS))); final ModelNode subModel = context.getSubModel().clone(); for (final String key : subModel.keys()) { final ModelNode child = subModel.get(key); if (childNames.contains(key)) { //Prune the value for this child if (subModel.get(key).isDefined()) { for (final String childKey : child.keys()) { subModel.get(key, childKey).set(new ModelNode()); } } result.get(key).set(child); } else { result.get(key).set(child); } } } resultHandler.handleResultFragment(NO_LOCATION, result); resultHandler.handleResultComplete(null); } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return Cancellable.NULL; } }; public static final ModelQueryOperationHandler READ_ATTRIBUTE = new ModelQueryOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { Cancellable cancellable = Cancellable.NULL; try { final String attributeName = operation.require(REQUEST_PROPERTIES).require(NAME).asString(); final AttributeAccess attributeAccess = context.getRegistry().getAttributeAccess(PathAddress.pathAddress(operation.require(ADDRESS)), attributeName); if (attributeAccess == null) { resultHandler.handleFailed(new ModelNode().set("No known attribute called " + attributeName)); // TODO i18n } else if (attributeAccess.getAccessType() == AccessType.WRITE_ONLY) { resultHandler.handleFailed(new ModelNode().set("Attribute " + attributeName + " is write-only")); // TODO i18n } else if (attributeAccess.getReadHandler() == null) { final ModelNode result = context.getSubModel().get(attributeName).clone(); resultHandler.handleResultFragment(NO_LOCATION, result); resultHandler.handleResultComplete(null); } else { cancellable = attributeAccess.getReadHandler().execute(context, operation, resultHandler); } } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return cancellable; } }; public static final ModelUpdateOperationHandler WRITE_ATTRIBUTE = new ModelUpdateOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { Cancellable cancellable = Cancellable.NULL; try { final String attributeName = operation.require(REQUEST_PROPERTIES).require(NAME).asString(); final AttributeAccess attributeAccess = context.getRegistry().getAttributeAccess(PathAddress.pathAddress(operation.require(ADDRESS)), attributeName); if (attributeAccess == null) { resultHandler.handleFailed(new ModelNode().set("No known attribute called " + attributeName)); // TODO i18n } else if (attributeAccess.getAccessType() == AccessType.READ_ONLY) { resultHandler.handleFailed(new ModelNode().set("Attribute " + attributeName + " is read-only")); // TODO i18n } else { cancellable = attributeAccess.getWriteHandler().execute(context, operation, resultHandler); } } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return cancellable; } }; public static final ModelQueryOperationHandler READ_CHILDREN_NAMES = new ModelQueryOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { try { final String childName = operation.require(REQUEST_PROPERTIES).require(CHILD_TYPE).asString(); ModelNode subModel = context.getSubModel().clone(); if (!subModel.isDefined()) { final ModelNode result = new ModelNode(); result.setEmptyList(); resultHandler.handleResultFragment(new String[0], result); resultHandler.handleResultComplete(null); } else { final Set<String> childNames = context.getRegistry().getChildNames(PathAddress.pathAddress(operation.require(ADDRESS))); if (!childNames.contains(childName)) { resultHandler.handleFailed(new ModelNode().set("No known child called " + childName)); //TODO i18n } else { final ModelNode result = new ModelNode(); subModel = subModel.get(childName); if (!subModel.isDefined()) { result.setEmptyList(); } else { for (final String key : subModel.keys()) { final ModelNode node = new ModelNode(); node.set(key); result.add(node); } } resultHandler.handleResultFragment(NO_LOCATION, result); resultHandler.handleResultComplete(null); } } } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return Cancellable.NULL; } }; public static final ModelQueryOperationHandler READ_OPERATION_NAMES = new ModelQueryOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { try { final ModelNodeRegistration registry = context.getRegistry(); final Map<String, DescriptionProvider> descriptionProviders = registry.getOperationDescriptions(PathAddress.pathAddress(operation.require(ADDRESS))); final ModelNode result = new ModelNode(); if (descriptionProviders.size() > 0) { for (final String s : descriptionProviders.keySet()) { result.add(s); } } else { result.setEmptyList(); } resultHandler.handleResultFragment(NO_LOCATION, result); resultHandler.handleResultComplete(null); } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return Cancellable.NULL; } }; public static final ModelQueryOperationHandler READ_OPERATION_DESCRIPTION = new ModelQueryOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { try { final String operationName = operation.require(REQUEST_PROPERTIES).require(NAME).asString(); final ModelNodeRegistration registry = context.getRegistry(); final DescriptionProvider descriptionProvider = registry.getOperationDescription(PathAddress.pathAddress(operation.require(ADDRESS)), operationName); final ModelNode result = descriptionProvider == null ? new ModelNode() : descriptionProvider.getModelDescription(getLocale(operation)); resultHandler.handleResultFragment(NO_LOCATION, result); resultHandler.handleResultComplete(null); } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return Cancellable.NULL; } }; public static final ModelQueryOperationHandler READ_RESOURCE_DESCRIPTION = new ModelQueryOperationHandler() { @Override public Cancellable execute(final NewOperationContext context, final ModelNode operation, final ResultHandler resultHandler) { try { final boolean operations = operation.get(REQUEST_PROPERTIES, OPERATIONS).isDefined() ? operation.get(REQUEST_PROPERTIES, OPERATIONS).asBoolean() : false; final boolean recursive = operation.get(REQUEST_PROPERTIES, RECURSIVE).isDefined() ? operation.get(REQUEST_PROPERTIES, RECURSIVE).asBoolean() : false; final ModelNodeRegistration registry = context.getRegistry(); final PathAddress address = PathAddress.pathAddress(operation.require(ADDRESS)); final DescriptionProvider descriptionProvider = registry.getModelDescription(address); final Locale locale = getLocale(operation); final ModelNode result = descriptionProvider.getModelDescription(getLocale(operation)); addDescription(result, recursive, operations, registry, address, locale); resultHandler.handleResultFragment(new String[0], result); resultHandler.handleResultComplete(null); } catch (final Exception e) { resultHandler.handleFailed(new ModelNode().set(e.getMessage())); } return Cancellable.NULL; } private void addDescription(final ModelNode result, final boolean recursive, final boolean operations, final ModelNodeRegistration registry, final PathAddress address, final Locale locale) { if (operations) { final Map<String, DescriptionProvider> ops = registry.getOperationDescriptions(address); if (ops.size() > 0) { for (final Map.Entry<String, DescriptionProvider> entry : ops.entrySet()) { result.get(OPERATIONS, entry.getKey()).set(entry.getValue().getModelDescription(locale)); } } else { result.get(OPERATIONS).setEmptyList(); } } if (recursive && result.has(CHILDREN)) { for (final PathElement element : registry.getChildAddresses(address)) { final PathAddress childAddress = address.append(element); final ModelNode child = registry.getModelDescription(childAddress).getModelDescription(locale); addDescription(child, recursive, operations, registry, childAddress, locale); result.get(CHILDREN, element.getKey(),MODEL_DESCRIPTION, element.getValue()).set(child); } } } }; private static Locale getLocale(final ModelNode operation) { if (!operation.has(REQUEST_PROPERTIES)) { return null; } if (!operation.get(REQUEST_PROPERTIES).has(LOCALE)) { return null; } return new Locale(operation.get(REQUEST_PROPERTIES, LOCALE).asString()); } }
package org.hisp.dhis.android.core.trackedentity; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.hisp.dhis.android.core.common.State; import org.hisp.dhis.android.core.data.database.DatabaseAdapter; import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceModel.Columns; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.hisp.dhis.android.core.utils.StoreUtils.parse; import static org.hisp.dhis.android.core.utils.StoreUtils.sqLiteBind; public class TrackedEntityInstanceStoreImpl implements TrackedEntityInstanceStore { private static final String INSERT_STATEMENT = "INSERT INTO " + TrackedEntityInstanceModel.TABLE + " (" + Columns.UID + ", " + Columns.CREATED + ", " + Columns.LAST_UPDATED + ", " + Columns.CREATED_AT_CLIENT + ", " + Columns.LAST_UPDATED_AT_CLIENT + ", " + Columns.ORGANISATION_UNIT + ", " + Columns.TRACKED_ENTITY + ", " + Columns.STATE + ") " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; private static final String UPDATE_STATEMENT = "UPDATE " + TrackedEntityInstanceModel.TABLE + " SET " + Columns.UID + " =?, " + Columns.CREATED + " =?, " + Columns.LAST_UPDATED + " =?, " + Columns.CREATED_AT_CLIENT + " =? , " + Columns.LAST_UPDATED_AT_CLIENT + " =? , " + Columns.ORGANISATION_UNIT + " =?, " + Columns.TRACKED_ENTITY + " =?, " + Columns.STATE + " =? " + " WHERE " + Columns.UID + " =?;"; private static final String SET_STATE_STATEMENT = "UPDATE " + TrackedEntityInstanceModel.TABLE + " SET " + Columns.STATE + " =?" + " WHERE " + Columns.UID + " =?;"; private static final String DELETE_STATEMENT = "DELETE FROM " + TrackedEntityInstanceModel.TABLE + " WHERE " + Columns.UID + " =?;"; private static final String QUERY_STATEMENT = "SELECT " + " TrackedEntityInstance.uid, " + " TrackedEntityInstance.created, " + " TrackedEntityInstance.lastUpdated, " + " TrackedEntityInstance.createdAtClient, " + " TrackedEntityInstance.lastUpdatedAtClient, " + " TrackedEntityInstance.organisationUnit, " + " TrackedEntityInstance.trackedEntity " + "FROM TrackedEntityInstance " + "WHERE state = 'TO_POST' OR state = 'TO_UPDATE'"; private final SQLiteStatement updateStatement; private final SQLiteStatement deleteStatement; private final SQLiteStatement setStateStatement; private final SQLiteStatement insertStatement; private final DatabaseAdapter databaseAdapter; public TrackedEntityInstanceStoreImpl(DatabaseAdapter databaseAdapter) { this.databaseAdapter = databaseAdapter; this.updateStatement = databaseAdapter.compileStatement(UPDATE_STATEMENT); this.deleteStatement = databaseAdapter.compileStatement(DELETE_STATEMENT); this.setStateStatement = databaseAdapter.compileStatement(SET_STATE_STATEMENT); this.insertStatement = databaseAdapter.compileStatement(INSERT_STATEMENT); } @Override public long insert(@NonNull String uid, @Nullable Date created, @Nullable Date lastUpdated, @Nullable String createdAtClient, @Nullable String lastUpdatedAtClient, @NonNull String organisationUnit, @NonNull String trackedEntity, @Nullable State state) { sqLiteBind(insertStatement, 1, uid); sqLiteBind(insertStatement, 2, created); sqLiteBind(insertStatement, 3, lastUpdated); sqLiteBind(insertStatement, 4, createdAtClient); sqLiteBind(insertStatement, 5, lastUpdatedAtClient); sqLiteBind(insertStatement, 6, organisationUnit); sqLiteBind(insertStatement, 7, trackedEntity); sqLiteBind(insertStatement, 8, state); long returnValue = databaseAdapter.executeInsert(TrackedEntityInstanceModel.TABLE, insertStatement); insertStatement.clearBindings(); return returnValue; } @Override public int delete() { return databaseAdapter.delete(TrackedEntityInstanceModel.TABLE); } @Override public int update(@NonNull String uid, @NonNull Date created, @NonNull Date lastUpdated, @Nullable String createdAtClient, @Nullable String lastUpdatedAtClient, @NonNull String organisationUnit, @NonNull String trackedEntity, @NonNull State state, @NonNull String whereTrackedEntityInstanceUid) { sqLiteBind(updateStatement, 1, uid); sqLiteBind(updateStatement, 2, created); sqLiteBind(updateStatement, 3, lastUpdated); sqLiteBind(updateStatement, 4, createdAtClient); sqLiteBind(updateStatement, 5, lastUpdatedAtClient); sqLiteBind(updateStatement, 6, organisationUnit); sqLiteBind(updateStatement, 7, trackedEntity); sqLiteBind(updateStatement, 8, state); // bind the where clause sqLiteBind(updateStatement, 9, whereTrackedEntityInstanceUid); int rowId = databaseAdapter.executeUpdateDelete(TrackedEntityInstanceModel.TABLE, updateStatement); updateStatement.clearBindings(); return rowId; } @Override public int delete(@NonNull String uid) { sqLiteBind(deleteStatement, 1, uid); int rowId = deleteStatement.executeUpdateDelete(); deleteStatement.clearBindings(); return rowId; } @Override public int setState(@NonNull String uid, @NonNull State state) { sqLiteBind(setStateStatement, 1, state); // bind the where argument sqLiteBind(setStateStatement, 2, uid); int updatedRow = databaseAdapter.executeUpdateDelete(TrackedEntityInstanceModel.TABLE, setStateStatement); setStateStatement.clearBindings(); return updatedRow; } @Override public Map<String, TrackedEntityInstance> query() { Cursor cursor = databaseAdapter.query(QUERY_STATEMENT); Map<String, TrackedEntityInstance> trackedEntityInstanceMap = new HashMap<>(); try { if (cursor.getCount() > 0) { cursor.moveToFirst(); do { String uid = cursor.getString(0); Date created = cursor.getString(1) != null ? parse(cursor.getString(1)) : null; Date lastUpdated = cursor.getString(2) != null ? parse(cursor.getString(2)) : null; String createdAtClient = cursor.getString(3) != null ? cursor.getString(3) : null; String lastUpdatedAtClient = cursor.getString(4) != null ? cursor.getString(4) : null; String organisationUnit = cursor.getString(5) != null ? cursor.getString(5) : null; String trackedEntity = cursor.getString(6) != null ? cursor.getString(6) : null; trackedEntityInstanceMap.put(uid, TrackedEntityInstance.create( uid, created, lastUpdated, createdAtClient, lastUpdatedAtClient, organisationUnit, trackedEntity, false, null, null, null)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return trackedEntityInstanceMap; } }
package io.debezium.connector.oracle.logminer; import java.util.regex.Pattern; /** * A utility/helper class to support decoding Oracle Unicode String function values, {@code UNISTR}. * * @author Chris Cranford */ public class UnistrHelper { private static final String UNITSTR_FUNCTION_START = "UNISTR('"; private static final String UNISTR_FUNCTION_END = "')"; private static final Pattern CONCATENATION_PATTERN = Pattern.compile("\\|\\|"); public static boolean isUnistrFunction(String data) { return data != null && data.startsWith(UNITSTR_FUNCTION_START) && data.endsWith(UNISTR_FUNCTION_END); } public static String convert(String data) { if (data == null || data.length() == 0) { return data; } // Multiple UNISTR function calls maybe concatenated together using "||". // We split the values into their respective parts before parsing each one separately. final String[] parts = CONCATENATION_PATTERN.split(data); // Iterate each part and if the part is a UNISTR function call, decode it // Append each part's value to the final result final StringBuilder result = new StringBuilder(); for (final String part : parts) { final String trimmedPart = part.trim(); if (isUnistrFunction(trimmedPart)) { result.append(decode(trimmedPart.substring(8, trimmedPart.length() - 2))); } else { result.append(data); } } return result.toString(); } private static String decode(String value) { StringBuilder result = new StringBuilder(); for (int i = 0; i < value.length(); ++i) { final char c = value.charAt(i); if (c == '\\') { if (value.length() >= (i + 4)) { // Read next 4 character hex and convert to character. result.append(Character.toChars(Integer.parseInt(value.substring(i + 1, i + 5), 16))); i += 4; continue; } } result.append(c); } return result.toString(); } }
package org.drools.guvnor.client.ruleeditor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotSame; import org.drools.guvnor.client.common.AssetFormats; import org.junit.Ignore; import org.junit.Test; public class SpringContextValidatorTest { SpringContextValidator validator = new SpringContextValidator(); @Test public void testValidator() { String droolsSpringCtxt = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<beans xmlns=\"http: "xmlns:xsi=\"http: "xmlns:context=\"http: "xmlns:drools=\"http://drools.org/schema/drools-spring\"\n"+ "xsi:schemaLocation=\"http: " http: " http: " http: " http://drools.org/schema/drools-spring\n"+ " http://drools.org/schema/drools-spring.xsd\""+ " default-autowire=\"byName\">" + "<drools:connection id=\"connection1\" type=\"local\" />"+ "<drools:execution-node id=\"node1\" connection=\"connection1\" />"+ "<drools:kbase id=\"kbase1\" node=\"node1\">"+ "<drools:resource source=\"classpath:changesets/change-set-1.xml\" type=\"CHANGE_SET\" />"+ "<drools:model source=\"classpath:model/person.xsd\" />"+ "</drools:kbase>"+ "<drools:kbase id=\"kbase2\" node=\"node1\">"+ "<drools:resource source=\"classpath:changesets/change-set-2.xml\" type=\"CHANGE_SET\" />"+ "</drools:kbase>"+ "<drools:ksession id=\"ksession1\" type=\"stateful\" kbase=\"kbase1\" node=\"node1\"/>"+ "<drools:ksession id=\"ksession2\" type=\"stateless\" kbase=\"kbase2\" node=\"node1\"/>"+ "</beans>"; String springCtxt = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+ "<!DOCTYPE beans PUBLIC \"- "<beans>"+ "<bean id=\"fileEventType\" class=\"com.devdaily.springtest1.bean.FileEventType\">"+ "<property name=\"eventType\" value=\"10\"/>"+ "<property name=\"description\" value=\"A sample description here\"/>"+ "</bean>"+ "</beans>"; String droolsSpringCtxtErr1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<beans xmlns=\"http: "xmlns:xsi=\"http: "xmlns:context=\"http: "xmlns:drools=\"http://drools.org/schema/drools-spring\"\n"+ "xsi:schemaLocation=\"http: " http: " http: " http: " http://drools.org/schema/drools-spring\n"+ " http://drools.org/schema/drools-spring.xsd\""+ " default-autowire=\"byName\">" + "<drools:connection id=\"connection1\" type=\"local\" />"+ "<drools:execution-node id=\"node1\" connection=\"connection1\" />"+ "<drools:kbase id=\"kbase1\" node=\"node1\">"+ "<drools:resource source=\"classpath:changesets/change-set-1.xml\" type=\"CHANGE_SET\" />"+ "<drools:model source=\"classpath:model/person.xsd\" />"+ "</drools:kbase>"+ "<drools:kbase id=\"kbase2\" node=\"node1\">"+ "<drools:resource source=\"classpath:changesets/change-set-2.xml\" type=\"CHANGE_SET\" />"+ "<drools:kbase>"+ "<drools:ksession id=\"ksession1\" type=\"stateful\" kbase=\"kbase1\" node=\"node1\"/>"+ "<drools:ksession id=\"ksession2\" type=\"stateless\" kbase=\"kbase2\" node=\"node1\"/>"+ "</beans>"; String droolsSpringCtxtErr2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<beans xmlns=\"http: "xmlns:xsi=\"http: "xmlns:context=\"http: "xmlns:drools=\"http://drools.org/schema/drools-spring\"\n"+ "xsi:schemaLocation=\"http: " http: " http: " http: " http://drools.org/schema/drools-spring\n"+ " http://drools.org/schema/drools-spring.xsd\""+ " default-autowire=\"byName\">" + "<pepe:abc id=\"connection1\" type=\"local\" />"+ "<drools:execution-node id=\"node1\" connection=\"connection1\" />"+ "<drools:kbase id=\"kbase1\" node=\"node1\">"+ "<drools:resource source=\"classpath:changesets/change-set-1.xml\" type=\"CHANGE_SET\" />"+ "<drools:model source=\"classpath:model/person.xsd\" />"+ "</drools:kbase>"+ "<drools:kbase id=\"kbase2\" node=\"node1\">"+ "<drools:resource source=\"classpath:changesets/change-set-2.xml\" type=\"CHANGE_SET\" />"+ "<drools:kbase>"+ "<drools:ksession id=\"ksession1\" type=\"stateful\" kbase=\"kbase1\" node=\"node1\"/>"+ "<drools:ksession id=\"ksession2\" type=\"stateless\" kbase=\"kbase2\" node=\"node1\"/>"+ "</beans>"; /*Validate Common Spring Context*/ validator.setContent(springCtxt); assertEquals(validator.validate(),""); /*Validate Drools Spring Integration*/ validator.setContent(droolsSpringCtxt); assertEquals(validator.validate(),""); /*Validate Drools Spring Integration Sixntax Error*/ validator.setContent(droolsSpringCtxtErr1); assertNotSame(validator.validate(),""); /*Validate Drools Spring Integration Semantic Error*/ validator.setContent(droolsSpringCtxtErr2); assertNotSame(validator.validate(),""); } }
package com.t5hm.escapa.game.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.t5hm.escapa.game.MainEscapaGame; import com.t5hm.escapa.game.MainEscapaLightsNoGame; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "GaussianEscapa"; config.width = 720; config.height = 360; config.useGL30 = true; // new LwjglApplication(new MainEscapaGame(), config); new LwjglApplication(new MainEscapaGame(), config); } }
package nl.mpi.kinnate.kindata; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import java.awt.Rectangle; import java.util.ArrayList; import java.util.HashMap; import javax.xml.bind.annotation.XmlElement; import nl.mpi.kinnate.svg.GraphPanelSize; public class GraphSorter { @XmlElement(name = "Entity", namespace = "http://mpi.nl/tla/kin") private EntityData[] graphDataNodeArray = new EntityData[]{}; private HashMap<UniqueIdentifier, SortingEntity> knownSortingEntities; // todo: should these padding vars be stored in the svg, currently they are stored private int xPadding = 100; // todo sort out one place for this var private int yPadding = 100; // todo sort out one place for this var // private boolean requiresRedraw = false; // , int hSpacing, int vSpacing public void setPadding(GraphPanelSize graphPanelSize) { xPadding = graphPanelSize.getHorizontalSpacing(); yPadding = graphPanelSize.getVerticalSpacing(); } private class SortingEntity { UniqueIdentifier selfEntityId; ArrayList<SortingEntity> mustBeBelow; ArrayList<SortingEntity> mustBeAbove; ArrayList<SortingEntity> mustBeNextTo; ArrayList<SortingEntity> couldBeNextTo; EntityRelation[] visiblyRelateNodes; float[] calculatedPosition = null; public SortingEntity(EntityData entityData) { selfEntityId = entityData.getUniqueIdentifier(); visiblyRelateNodes = entityData.getVisiblyRelateNodes(); mustBeBelow = new ArrayList<SortingEntity>(); mustBeAbove = new ArrayList<SortingEntity>(); mustBeNextTo = new ArrayList<SortingEntity>(); couldBeNextTo = new ArrayList<SortingEntity>(); } public void calculateRelations(HashMap<UniqueIdentifier, SortingEntity> knownSortingEntities) { for (EntityRelation entityRelation : visiblyRelateNodes) { switch (entityRelation.relationType) { case ancestor: mustBeBelow.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); break; case descendant: mustBeAbove.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); break; case union: mustBeNextTo.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); // no break here is deliberate: those that mustBeNextTo to need also to be in couldBeNextTo case sibling: couldBeNextTo.add(knownSortingEntities.get(entityRelation.alterUniqueIdentifier)); break; } } } private boolean positionIsFree(UniqueIdentifier currentIdentifier, float[] targetPosition, HashMap<UniqueIdentifier, float[]> entityPositions) { int useCount = 0; for (float[] currentPosition : entityPositions.values()) { if (currentPosition[0] == targetPosition[0] && currentPosition[1] == targetPosition[1]) { useCount++; } } if (useCount == 0) { return true; } if (useCount == 1) { float[] entityPosition = entityPositions.get(currentIdentifier); if (entityPosition != null) { // todo: change this to compare distance not exact location if (entityPosition[0] == targetPosition[0] && entityPosition[1] == targetPosition[1]) { // if there is one entity already in this position then check if it is the current entity, in which case it is free return true; } } } return false; } protected float[] getPosition(HashMap<UniqueIdentifier, float[]> entityPositions, float[] defaultPosition) { // System.out.println("getPosition: " + selfEntityId.getAttributeIdentifier()); calculatedPosition = entityPositions.get(selfEntityId); if (calculatedPosition == null) { for (SortingEntity sortingEntity : mustBeBelow) { // note that this get position also sets the position and the result will not be null // float[] nextAbovePos = sortingEntity.getPosition(entityPositions, defaultPosition); // note that this does not set the position and the result can be null float[] nextAbovePos = entityPositions.get(sortingEntity.selfEntityId); if (nextAbovePos != null) { if (calculatedPosition == null) { calculatedPosition = new float[]{nextAbovePos[0], nextAbovePos[1]}; } if (nextAbovePos[1] > calculatedPosition[1] - yPadding) { calculatedPosition[1] = nextAbovePos[1] + yPadding; // calculatedPosition[0] = nextAbovePos[0]; System.out.println("move down: " + selfEntityId.getAttributeIdentifier()); } } } if (calculatedPosition == null) { for (SortingEntity sortingEntity : couldBeNextTo) { // note that this does not set the position and the result can be null float[] nextToPos = entityPositions.get(sortingEntity.selfEntityId); if (calculatedPosition == null && nextToPos != null) { calculatedPosition = new float[]{nextToPos[0], nextToPos[1]}; } } } if (calculatedPosition == null) { for (SortingEntity sortingEntity : mustBeAbove) { // note that this does not set the position and the result can be null float[] nextBelowPos = entityPositions.get(sortingEntity.selfEntityId); if (nextBelowPos != null) { if (calculatedPosition == null) { calculatedPosition = new float[]{nextBelowPos[0], nextBelowPos[1]}; } if (nextBelowPos[1] < calculatedPosition[1] + yPadding) { calculatedPosition[1] = nextBelowPos[1] - yPadding; // calculatedPosition[0] = nextAbovePos[0]; System.out.println("move up: " + selfEntityId.getAttributeIdentifier()); } } } } if (calculatedPosition == null) { calculatedPosition = new float[]{defaultPosition[0], 0}; } // make sure any spouses are in the same row // todo: this should probably be moved into a separate action and when a move is made then move in sequence the entities that are below and to the right for (SortingEntity sortingEntity : mustBeNextTo) { float[] nextToPos = entityPositions.get(sortingEntity.selfEntityId); if (nextToPos != null) { if (nextToPos[1] > calculatedPosition[1]) { calculatedPosition = new float[]{nextToPos[0], nextToPos[1]}; } // } else { // // prepopulate the spouse position // float[] spousePosition = new float[]{calculatedPosition[0], calculatedPosition[1]}; // while (!positionIsFree(sortingEntity.selfEntityId, spousePosition, entityPositions)) { // // todo: this should be checking min distance not free // spousePosition[0] = spousePosition[0] + xPadding; // System.out.println("move spouse right: " + selfEntityId); // entityPositions.put(sortingEntity.selfEntityId, spousePosition); } } while (!positionIsFree(selfEntityId, calculatedPosition, entityPositions)) { // todo: this should be checking min distance not free calculatedPosition[0] = calculatedPosition[0] + xPadding; System.out.println("move right: " + selfEntityId.getAttributeIdentifier()); } // System.out.println("Insert: " + selfEntityId + " : " + calculatedPosition[0] + " : " + calculatedPosition[1]); entityPositions.put(selfEntityId, calculatedPosition); } // System.out.println("Position: " + selfEntityId.getAttributeIdentifier() + " : " + calculatedPosition[0] + " : " + calculatedPosition[1]); // float[] debugArray = entityPositions.get("Charles II of Spain"); // if (debugArray != null) { // System.out.println("Charles II of Spain: " + debugArray[0] + " : " + debugArray[1]); return calculatedPosition; } protected void getRelatedPositions(HashMap<UniqueIdentifier, float[]> entityPositions) { ArrayList<SortingEntity> allRelations = new ArrayList<SortingEntity>(); allRelations.addAll(mustBeAbove); allRelations.addAll(mustBeBelow); // allRelations.addAll(mustBeNextTo); // those that are in mustBeNextTo are also in couldBeNextTo allRelations.addAll(couldBeNextTo); for (SortingEntity sortingEntity : allRelations) { if (sortingEntity.calculatedPosition == null) { Rectangle rectangle = getGraphSize(entityPositions); float[] defaultPosition = new float[]{rectangle.width, rectangle.height}; sortingEntity.getPosition(entityPositions, defaultPosition); sortingEntity.getRelatedPositions(entityPositions); } } } } public void setEntitys(EntityData[] graphDataNodeArrayLocal) { graphDataNodeArray = graphDataNodeArrayLocal; // this section need only be done when the nodes are added to this graphsorter knownSortingEntities = new HashMap<UniqueIdentifier, SortingEntity>(); for (EntityData currentNode : graphDataNodeArrayLocal) { if (currentNode.isVisible) { // only create sorting entities for visible entities knownSortingEntities.put(currentNode.getUniqueIdentifier(), new SortingEntity(currentNode)); } } for (SortingEntity currentSorter : knownSortingEntities.values()) { currentSorter.calculateRelations(knownSortingEntities); } // sanguineSort(); //printLocations(); // todo: remove this and maybe add a label of x,y post for each node to better see the sorting } // public boolean isResizeRequired() { // boolean returnBool = requiresRedraw; // requiresRedraw = false; // return returnBool; // private void placeRelatives(EntityData currentNode, ArrayList<EntityData> intendedSortOrder, HashMap<String, Float[]> entityPositions) { // for (EntityRelation entityRelation : currentNode.getVisiblyRelateNodes()) { // EntityData relatedEntity = entityRelation.getAlterNode(); public Rectangle getGraphSize(HashMap<UniqueIdentifier, float[]> entityPositions) { // get min positions // this should also take into account any graphics such as labels, although the border provided should be adequate, in other situations the page size could be set, in which case maybe an align option would be helpful int[] minPostion = null; int[] maxPostion = null; for (float[] currentPosition : entityPositions.values()) { if (minPostion == null) { minPostion = new int[]{Math.round(currentPosition[0]), Math.round(currentPosition[1])}; maxPostion = new int[]{Math.round(currentPosition[0]), Math.round(currentPosition[1])}; } else { minPostion[0] = Math.min(minPostion[0], Math.round(currentPosition[0])); minPostion[1] = Math.min(minPostion[1], Math.round(currentPosition[1])); maxPostion[0] = Math.max(maxPostion[0], Math.round(currentPosition[0])); maxPostion[1] = Math.max(maxPostion[1], Math.round(currentPosition[1])); } } if (minPostion == null) { // when there are no entities this could be null and must be corrected here minPostion = new int[]{0, 0}; maxPostion = new int[]{0, 0}; } int xOffset = minPostion[0] - xPadding; int yOffset = minPostion[1] - yPadding; int graphWidth = maxPostion[0] + xPadding; int graphHeight = maxPostion[1] + yPadding; return new Rectangle(xOffset, yOffset, graphWidth, graphHeight); } public void placeAllNodes(HashMap<UniqueIdentifier, float[]> entityPositions) { // make a has table of all entites // find the first ego node // place it and all its immediate relatives onto the graph, each time checking that the space is free // contine to the next nearest relatives // when all done search for any unrelated nodes and do it all again // remove any transent nodes that are not in this list anymore // and make sure that invisible nodes are ignored ArrayList<UniqueIdentifier> removeNodeIds = new ArrayList<UniqueIdentifier>(entityPositions.keySet()); for (EntityData currentNode : graphDataNodeArray) { removeNodeIds.remove(currentNode.getUniqueIdentifier()); // remove any invisible node from the position list, the entities in a loaded svg should still get here even if they are not visible anymore if (!currentNode.isVisible) { entityPositions.remove(currentNode.getUniqueIdentifier()); } } for (UniqueIdentifier currentRemoveId : removeNodeIds) { if (!(currentRemoveId.isGraphicsIdentifier())) { // remove the transent nodes making sure not to remove the positions of graphics such as labels entityPositions.remove(currentRemoveId); } } if (knownSortingEntities != null) { for (SortingEntity currentSorter : knownSortingEntities.values()) { Rectangle rectangle = getGraphSize(entityPositions); float[] defaultPosition = new float[]{rectangle.width, rectangle.height}; currentSorter.getPosition(entityPositions, defaultPosition); currentSorter.getRelatedPositions(entityPositions); } } // requiresRedraw = (yOffset != 0 || xOffset != 0); // todo: use a transalte rather than moving the nodes because the label position is important // if (yOffset < 0 || xOffset < 0) { // todo: use a transalte rather than moving the nodes because the label position is important // for (float[] currentPosition : entityPositions.values()) { // currentPosition[0] = currentPosition[0] + xOffset; // currentPosition[1] = currentPosition[1] + yOffset; // ArrayList<EntityData> intendedSortOrder = new ArrayList<EntityData>(); //// ArrayList<EntityData> placedEntities = new ArrayList<EntityData>(); // for (EntityData currentNode : allEntitys) { // if (currentNode.isVisible && entityPositions.containsKey(currentNode.getUniqueIdentifier())) { // // add all the placed entities first in the list // intendedSortOrder.add(currentNode); // boolean nodesNeedPlacement = false; // for (EntityData currentNode : allEntitys) { // if (currentNode.isVisible && !intendedSortOrder.contains(currentNode)) { // intendedSortOrder.add(currentNode); // nodesNeedPlacement = true; // if (!nodesNeedPlacement) { // return; // // store the max and min X Y so that the diagram size can be correctly specified // while (!intendedSortOrder.isEmpty()) { // EntityData currentNode = intendedSortOrder.remove(0); //// placedEntities.add(currentNode); // if (currentNode.isVisible) { // // loop through the filled locations and move to the right or left if not empty required //// // todo: check the related nodes and average their positions then check to see if it is free and insert the node there // boolean positionFree = false; // float preferedX = 0; // String currentIdentifier = currentNode.getUniqueIdentifier(); // Float[] storedPosition = entityPositions.get(currentIdentifier); //// if (storedPosition == null) { //// storedPosition = new Float[]{preferedX, 0.0f}; // while (!positionFree) { //// storedPosition = new Float[]{preferedX * hSpacing + hSpacing - symbolSize / 2.0f, //// currentNode.getyPos() * vSpacing + vSpacing - symbolSize / 2.0f}; //// if (entityPositions.isEmpty()) { //// break; // if (storedPosition != null) { // positionFree = true; // for (String comparedIdentifier : entityPositions.keySet()) { // if (!comparedIdentifier.equals(currentIdentifier)) { // Float[] currentPosition = entityPositions.get(comparedIdentifier); // positionFree = !currentPosition[0].equals(storedPosition[0]) || !currentPosition[1].equals(storedPosition[1]); // if (!positionFree) { // break; // preferedX++; // if (!positionFree) { // storedPosition = new Float[]{preferedX, 0.0f}; // entityPositions.put(currentIdentifier, storedPosition); } //// public int[] getEntityLocation(String entityId) { //// for (EntityData entityData : graphDataNodeArray) { //// if (entityData.getUniqueIdentifier().equals(entityId)) { //// return new int[]{entityData.xPos, entityData.yPos}; //// return null; //// public void setEntityLocation(String entityId, int xPos, int yPos) { //// for (EntityData entityData : graphDataNodeArray) { //// if (entityData.getUniqueIdentifier().equals(entityId)) { //// entityData.xPos = xPos; //// entityData.yPos = yPos; //// return; // // todo: and http://books.google.nl/books?id=diqHjRjMhW0C&pg=PA138&lpg=PA138&dq=SVGDOMImplementation+add+namespace&source=bl&ots=IuqzAz7dsz&sig=e5FW_B1bQbhnth6i2rifalv2LuQ&hl=nl&ei=zYpnTYD3E4KVOuPF2YoL&sa=X&oi=book_result&ct=result&resnum=3&ved=0CC0Q6AEwAg#v=onepage&q&f=false // // page 139 shows jgraph layout usage // // todo: lookinto: //// layouts.put("Hierarchical", new JGraphHierarchicalLayout()); //// layouts.put("Compound", new JGraphCompoundLayout()); //// layouts.put("CompactTree", new JGraphCompactTreeLayout()); //// layouts.put("Tree", new JGraphTreeLayout()); //// layouts.put("RadialTree", new JGraphRadialTreeLayout()); //// layouts.put("Organic", new JGraphOrganicLayout()); //// layouts.put("FastOrganic", new JGraphFastOrganicLayout()); //// layouts.put("SelfOrganizingOrganic", new JGraphSelfOrganizingOrganicLayout()); //// layouts.put("SimpleCircle", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_CIRCLE)); //// layouts.put("SimpleTilt", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_TILT)); //// layouts.put("SimpleRandom", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_RANDOM)); //// layouts.put("Spring", new JGraphSpringLayout()); //// layouts.put("Grid", new SimpleGridLayout()); // private void sanguineSubnodeSort(ArrayList<HashSet<EntityData>> generationRows, HashSet<EntityData> currentColumns, ArrayList<EntityData> inputNodes, EntityData currentNode) { // int currentRowIndex = generationRows.indexOf(currentColumns); // HashSet<EntityData> ancestorColumns; // HashSet<EntityData> descendentColumns; // if (currentRowIndex < generationRows.size() - 1) { // descendentColumns = generationRows.get(currentRowIndex + 1); // } else { // descendentColumns = new HashSet<EntityData>(); // generationRows.add(currentRowIndex + 1, descendentColumns); // if (currentRowIndex > 0) { // ancestorColumns = generationRows.get(currentRowIndex - 1); // } else { // ancestorColumns = new HashSet<EntityData>(); // generationRows.add(currentRowIndex, ancestorColumns); // for (EntityRelation relatedNode : currentNode.getVisiblyRelateNodes()) { // todo: here we are soriting only visible nodes, sorting invisible nodes as well might cause issues or might help the layout and this must be tested // // todo: what happens here if there are multiple relations specified? // if (/*relatedNode.getAlterNode().isVisible &&*/inputNodes.contains(relatedNode.getAlterNode())) { // HashSet<EntityData> targetColumns; // switch (relatedNode.relationType) { // case ancestor: // targetColumns = ancestorColumns; // break; // case sibling: // targetColumns = currentColumns; // break; // case descendant: // targetColumns = descendentColumns; // break; // case union: // targetColumns = currentColumns; // break; // case none: // // this would be a kin term or other so skip when sorting // targetColumns = null; // break; // default: // targetColumns = null; // if (targetColumns != null) { // inputNodes.remove(relatedNode.getAlterNode()); // targetColumns.add(relatedNode.getAlterNode()); //// System.out.println("sorted: " + relatedNode.getAlterNode().getLabel() + " : " + relatedNode.relationType + " of " + currentNode.getLabel()); // sanguineSubnodeSort(generationRows, targetColumns, inputNodes, relatedNode.getAlterNode()); // protected void sanguineSort() { // // todo: improve this sorting by adding a secondary row sort // System.out.println("calculateLocations"); // // create an array of rows // ArrayList<HashSet<EntityData>> generationRows = new ArrayList<HashSet<EntityData>>(); // ArrayList<EntityData> inputNodes = new ArrayList<EntityData>(); // inputNodes.addAll(Arrays.asList(graphDataNodeArray)); // // put an array of columns into the current row // HashSet<EntityData> currentColumns = new HashSet<EntityData>(); // generationRows.add(currentColumns); // while (inputNodes.size() > 0) { // this loop checks all nodes provided for display, but the sanguineSubnodeSort will remove any related nodes before we return to this loop, so this loop would only run once if all nodes are related // EntityData currentNode = inputNodes.remove(0); //// System.out.println("add as root node: " + currentNode.getLabel()); //// if (currentNode.isVisible) { // currentColumns.add(currentNode); // sanguineSubnodeSort(generationRows, currentColumns, inputNodes, currentNode); // gridWidth = 0; // int yPos = 0; // for (HashSet<EntityData> currentRow : generationRows) { // System.out.println("row: : " + yPos); // if (currentRow.isEmpty()) { // System.out.println("Skipping empty row"); // } else { // int xPos = 0; // if (gridWidth < currentRow.size()) { // gridWidth = currentRow.size(); // for (EntityData graphDataNode : currentRow) { //// System.out.println("updating: " + xPos + " : " + yPos + " : " + graphDataNode.getLabel()); // graphDataNode.yPos = yPos; // graphDataNode.xPos = xPos; // //graphDataNode.appendTempLabel("X:" + xPos + " Y:" + yPos); // xPos++; // yPos++; // gridHeight = yPos; // int maxRowWidth = 0; // // correct the grid width // for (HashSet<EntityData> currentRow : generationRows) { // if (maxRowWidth < currentRow.size()) { // maxRowWidth = currentRow.size(); // gridWidth = maxRowWidth; // System.out.println("gridWidth: " + gridWidth); //// sortRowsByAncestor(generationRows); // sortByLinkDistance(); // sortByLinkDistance(); // private void sortRowsByAncestor(ArrayList<HashSet<EntityData>> generationRows) { // // todo: handle reverse generations also // ArrayList<EntityData> sortedRow = new ArrayList<EntityData>(); // int startRow = 0; // while (generationRows.get(startRow).isEmpty()) { // startRow++; // HashSet<EntityData> firstRow = generationRows.get(startRow); // for (EntityData currentEntity : firstRow) { // if (!sortedRow.contains(currentEntity)) { // if the entity has been added then do not look into any further // sortedRow.add(currentEntity); // // if this node has children in common with any other on this row then place them next to each other // // todo: add sort by DOB // for (EntityData contemporariesEntity : findContemporariesWithCommonDescendant(currentEntity, 2)) { // if (!sortedRow.contains(contemporariesEntity)) { // sortedRow.add(contemporariesEntity); // while (sortedRow.size() > 0) { // assignRowOrder(sortedRow); // ArrayList<EntityData> nextRow = new ArrayList<EntityData>(); // for (EntityData currentEntity : sortedRow) { // for (EntityRelation childRelation : currentEntity.getDistinctRelateNodes()) { // if (childRelation.getAlterNode().yPos == currentEntity.yPos + 1) { // if (!nextRow.contains(childRelation.getAlterNode())) { // nextRow.add(childRelation.getAlterNode()); // sortedRow = nextRow; // private void assignRowOrder(ArrayList<EntityData> sortedRow) { // int columnCount = 0; // for (EntityData currentEntity : sortedRow) { // // todo: space the nodes // currentEntity.xPos = columnCount; // columnCount++; // System.out.println("sorted: " + currentEntity.getLabel()[0] + " : " + currentEntity.xPos + "," + currentEntity.yPos); // private HashSet<EntityData> findContemporariesWithCommonDescendant(EntityData currentEntity, int depth) { // HashSet<EntityData> foundContemporaries = new HashSet<EntityData>(); // for (EntityRelation childRelation : currentEntity.getDistinctRelateNodes()) { // if (childRelation.getAlterNode().yPos == currentEntity.yPos) { // foundContemporaries.add(childRelation.getAlterNode()); // } else { // depth--; // if (depth > 0) { // foundContemporaries.addAll(findContemporariesWithCommonDescendant(currentEntity, depth)); // return foundContemporaries; // private void sortByLinkDistance() { // // todo: correct the grid width, // // start at the top row and count the childeren of each parent and space accordingly // EntityData[][] graphGrid = new EntityData[gridHeight][gridWidth]; // for (EntityData graphDataNode : graphDataNodeArray) { // graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode; // for (EntityData graphDataNode : graphDataNodeArray) { // int relationCounter = 0; // int totalPositionCounter = 0; // for (EntityRelation graphLinkNode : graphDataNode.getVisiblyRelateNodes()) { // relationCounter++; // totalPositionCounter += graphLinkNode.getAlterNode().xPos; // //totalPositionCounter += Math.abs(graphLinkNode.linkedNode.xPos - graphLinkNode.sourceNode.xPos); //// totalPositionCounter += Math.abs(graphLinkNode.linkedNode.xPos - graphLinkNode.sourceNode.xPos); // System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().xPos); // System.out.println("totalPositionCounter: " + totalPositionCounter); // if (relationCounter > 0) { // int averagePosition = totalPositionCounter / relationCounter; // while (averagePosition < gridWidth - 1 && graphGrid[graphDataNode.yPos][averagePosition] != null) { // averagePosition++; // while (averagePosition > 0 && graphGrid[graphDataNode.yPos][averagePosition] != null) { // averagePosition--; // if (graphGrid[graphDataNode.yPos][averagePosition] == null) { // graphGrid[graphDataNode.yPos][graphDataNode.xPos] = null; // graphDataNode.xPos = averagePosition; // todo: swap what ever is aready there // graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode; // System.out.println("averagePosition: " + averagePosition); public EntityData[] getDataNodes() { return graphDataNodeArray; } // private void printLocations() { // System.out.println("printLocations"); // for (EntityData graphDataNode : graphDataNodeArray) { // System.out.println("node: " + graphDataNode.xPos + ":" + graphDataNode.yPos); // for (EntityRelation graphLinkNode : graphDataNode.getVisiblyRelateNodes()) { // System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos); }
package com.oracle.graal.hotspot.phases; import com.oracle.graal.api.code.*; import com.oracle.graal.debug.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.Node.Verbosity; import com.oracle.graal.graph.iterators.*; import com.oracle.graal.loop.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.extended.*; import com.oracle.graal.nodes.util.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.*; public class OnStackReplacementPhase extends Phase { @Override protected void run(StructuredGraph graph) { if (graph.getEntryBCI() == StructuredGraph.INVOCATION_ENTRY_BCI) { // This happens during inlining in a OSR method, because the same phase plan will be // used. return; } Debug.dump(graph, "OnStackReplacement initial"); EntryMarkerNode osr; do { NodeIterable<EntryMarkerNode> osrNodes = graph.getNodes(EntryMarkerNode.class); osr = osrNodes.first(); if (osr == null) { throw new BailoutException("No OnStackReplacementNode generated"); } if (osrNodes.count() > 1) { throw new GraalInternalError("Multiple OnStackReplacementNodes generated"); } if (osr.stateAfter().locksSize() != 0) { throw new BailoutException("OSR with locks not supported"); } if (osr.stateAfter().stackSize() != 0) { throw new BailoutException("OSR with stack entries not supported: " + osr.stateAfter().toString(Verbosity.Debugger)); } LoopEx osrLoop = null; LoopsData loops = new LoopsData(graph); for (LoopEx loop : loops.loops()) { if (loop.inside().contains(osr)) { osrLoop = loop; break; } } if (osrLoop == null) { break; } LoopTransformations.peel(osrLoop); for (Node usage : osr.usages().snapshot()) { ProxyNode proxy = (ProxyNode) usage; proxy.replaceAndDelete(proxy.value()); } GraphUtil.removeFixedWithUnusedInputs(osr); Debug.dump(graph, "OnStackReplacement loop peeling result"); } while (true); FrameState osrState = osr.stateAfter(); osr.setStateAfter(null); OSRStartNode osrStart = graph.add(new OSRStartNode()); StartNode start = graph.start(); FixedNode next = osr.next(); osr.setNext(null); osrStart.setNext(next); graph.setStart(osrStart); osrStart.setStateAfter(osrState); for (int i = 0; i < osrState.localsSize(); i++) { ValueNode value = osrState.localAt(i); if (value instanceof ProxyNode) { ProxyNode proxy = (ProxyNode) value; /* * we need to drop the stamp since the types we see during OSR may be too precise * (if a branch was not parsed for example). */ proxy.replaceAndDelete(graph.unique(new OSRLocalNode(i, proxy.stamp().unrestricted()))); } else { assert value == null || value instanceof OSRLocalNode; } } GraphUtil.killCFG(start); Debug.dump(graph, "OnStackReplacement result"); new DeadCodeEliminationPhase().apply(graph); } }
package nl.mpi.kinnate.svg; import java.awt.Point; import java.util.ArrayList; import java.util.HashSet; public class LineLookUpTable { // this hashset keeps one line record for line part for each pair of entities, the line segments might be updated when an entity is dragged // todo: there will probably be multiple line parts for each pari of entities: start segment, end segment, main line and maybe some zig zag bits, even if these zig zag bits are not ued they probably should always be there for simplicity HashSet<LineRecord> lineRecords = new HashSet<LineRecord>(); protected class LineRecord { public LineRecord(String lineIdString, ArrayList<Point> pointsList) { this.lineIdSring = lineIdString; this.pointsList = pointsList; } private String lineIdSring; private ArrayList<Point> pointsList; protected Point getIntersection(LineRecord lineRecord) { return null; //Point((lineRecord.startPoint.x + lineRecord.endPoint.x) / 2, (lineRecord.startPoint.y + lineRecord.endPoint.y) / 2); // todo: get the actual intersections and insert loops // todo: in RelationSVG on first load the lineLookUpTable is null and loops will not be drawn } private void insertLoop(int linePart) { // todo: this is test needs to be extended to place the loops in the correct locations and to produce pretty curved loops Point startPoint = this.pointsList.get(linePart); Point endPoint = this.pointsList.get(linePart + 1); int centerX = (startPoint.x + endPoint.x) / 2; int centerY = (startPoint.y + endPoint.y) / 2; int startOffset = -5; int endOffset = +5; int loopHeight = -10; if (startPoint.x == endPoint.x) { // horizontal lines if (startPoint.y < endPoint.y) { startOffset = +5; endOffset = -5; } this.pointsList.add(linePart + 1, new Point(centerX, centerY + startOffset)); this.pointsList.add(linePart + 1, new Point(centerX + loopHeight, centerY + startOffset)); this.pointsList.add(linePart + 1, new Point(centerX + loopHeight, centerY + endOffset)); this.pointsList.add(linePart + 1, new Point(centerX, centerY + endOffset)); } else { // vertical lines if (startPoint.x < endPoint.x) { startOffset = +5; endOffset = -5; } this.pointsList.add(linePart + 1, new Point(centerX + startOffset, centerY)); this.pointsList.add(linePart + 1, new Point(centerX + startOffset, centerY + loopHeight)); this.pointsList.add(linePart + 1, new Point(centerX + endOffset, centerY + loopHeight)); this.pointsList.add(linePart + 1, new Point(centerX + endOffset, centerY)); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LineRecord other = (LineRecord) obj; if ((this.lineIdSring == null) ? (other.lineIdSring != null) : !this.lineIdSring.equals(other.lineIdSring)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + (this.lineIdSring != null ? this.lineIdSring.hashCode() : 0); return hash; } } public void getIntersectsEntity() { } public void getOverlapsOtherLine() { } private Point[] getIntersections(LineRecord localLineRecord) { HashSet<Point> intersectionPoints = new HashSet<Point>(); for (LineRecord lineRecord : lineRecords) { Point intersectionPoint = localLineRecord.getIntersection(lineRecord); if (lineRecord != null) { intersectionPoints.add(intersectionPoint); } } return intersectionPoints.toArray(new Point[]{}); } public Point[] adjustLineToObstructions(String lineIdString, ArrayList<Point> pointsList) { LineRecord localLineRecord = new LineRecord(lineIdString, pointsList); getIntersections(localLineRecord); //localLineRecord.insertLoop(3); lineRecords.add(localLineRecord); return localLineRecord.pointsList.toArray(new Point[]{}); } }
package org.opennms.protocols.vmware; import com.vmware.vim25.*; import com.vmware.vim25.mo.*; import com.vmware.vim25.mo.util.MorUtil; import org.apache.commons.cli.*; import javax.net.ssl.*; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; public class VmwareConfigBuilder { private static class VMwareConfigMetric implements Comparable<VMwareConfigMetric> { private String humanReadableName, aliasName, groupName; private PerfCounterInfo perfCounterInfo; private boolean multiInstance = false; public VMwareConfigMetric(PerfCounterInfo perfCounterInfo, String humanReadableName, String aliasName, boolean multiInstance, String groupName) { this.perfCounterInfo = perfCounterInfo; this.humanReadableName = humanReadableName; this.aliasName = aliasName; this.multiInstance = multiInstance; this.groupName = groupName; } public String getDatacollectionEntry() { return " <attrib name=\"" + humanReadableName + "\" alias=\"" + aliasName + "\" type=\"Gauge\"/>\n"; } public String getGraphDefinition(String apiVersion) { String resourceType = (multiInstance ? "vmware" + apiVersion + groupName : "nodeSnmp"); String def = "report.vmware" + apiVersion + "." + aliasName + ".name=vmware" + apiVersion + "." + humanReadableName + "\n" + "report.vmware" + apiVersion + "." + aliasName + ".columns=" + aliasName + "\n"; if (multiInstance) { def += "report.vmware" + apiVersion + "." + aliasName + ".propertiesValues=vmware" + apiVersion + groupName + "Name\n"; } def += "report.vmware" + apiVersion + "." + aliasName + ".type=" + resourceType + "\n" + "report.vmware" + apiVersion + "." + aliasName + ".command=--title=\"VMWare" + apiVersion + " " + humanReadableName + (multiInstance ? " {" + resourceType + "Name}" : "") + "\" \\\n" + "--vertical-label=\"" + aliasName + "\" \\\n" + "DEF:xxx={rrd1}:" + aliasName + ":AVERAGE \\\n" + "LINE2:xxx#0000ff:\"" + aliasName + "\" \\\n" + "GPRINT:xxx:AVERAGE:\"Avg \\\\: %8.2lf %s\" \\\n" + "GPRINT:xxx:MIN:\"Min \\\\: %8.2lf %s\" \\\n" + "GPRINT:xxx:MAX:\"Max \\\\: %8.2lf %s\\\\n\" \n\n"; return def; } public String getInclude(String apiVersion) { return "vmware" + apiVersion + "." + getAliasName() + ", \\\n"; } public String getHumanReadableName() { return humanReadableName; } public String getAliasName() { return aliasName; } public PerfCounterInfo getPerfCounterInfo() { return perfCounterInfo; } public boolean isMultiInstance() { return multiInstance; } @Override public int compareTo(VMwareConfigMetric o) { return getAliasName().compareTo(o.getAliasName()); } } private String hostname, username, password; private ServiceInstance serviceInstance; private PerformanceManager performanceManager; private Map<String, Map<String, TreeSet<VMwareConfigMetric>>> collections = new HashMap<String, Map<String, TreeSet<VMwareConfigMetric>>>(); private Map<Integer, PerfCounterInfo> perfCounterInfoMap = new HashMap<Integer, PerfCounterInfo>(); private String versionInformation = "", apiVersion = ""; private static class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } } public VmwareConfigBuilder(String hostname, String username, String password) { this.hostname = hostname; this.username = username; this.password = password; } private String getHumanReadableName(PerfCounterInfo perfCounterInfo) { return perfCounterInfo.getGroupInfo().getKey() + "." + perfCounterInfo.getNameInfo().getKey() + "." + perfCounterInfo.getRollupType().toString(); } private String normalizeName(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } private String normalizeGroupName(String groupName) { String modifiedGroupName = groupName; String[] groupChunks = {"sys", "rescpu", "cpu", "net", "disk", "mem", "managementAgent", "virtualDisk", "datastore", "storageAdapter", "storagePath", "hbr", "power"}; String[] groupReplacements = {"Sys", "ResCpu", "Cpu", "Net", "Disk", "Mem", "MgtAgt", "VrtDisk", "DaSt", "StAdptr", "StPth", "Hbr", "Power"}; for (int i = 0; i < groupChunks.length; i++) { modifiedGroupName = modifiedGroupName.replace(groupChunks[i], groupReplacements[i]); } return modifiedGroupName; } private String condenseName(String text, String chunk) { String ignoreCaseChunk = "[" + chunk.substring(0, 1) + chunk.substring(0, 1).toUpperCase() + "]" + chunk.substring(1); String replacement = chunk.substring(0, 1).toUpperCase() + chunk.substring(chunk.length() - 1); return text.replaceAll(ignoreCaseChunk, replacement); } private String getAliasName(PerfCounterInfo perfCounterInfo) { String group = perfCounterInfo.getGroupInfo().getKey(); String name = perfCounterInfo.getNameInfo().getKey(); String rollup = perfCounterInfo.getRollupType().toString(); group = normalizeGroupName(group); String[] rollupChunks = {"summation", "average", "latest", "none", "minimum", "maximum", "total"}; String[] rollupReplacements = {"Sum", "Avg", "Lat", "Non", "Min", "Max", "Tot"}; for (int i = 0; i < rollupChunks.length; i++) { rollup = rollup.replace(rollupChunks[i], rollupReplacements[i]); } String[] nameChunks = {"unkown", "protos", "threshold", "datastore", "alloc", "utilization", "normalized", "normal", "shares", "depth", "resource", "overhead", "swap", "rate", "metric", "number", "averaged", "load", "decompression", "compression", "device", "latency", "capacity", "commands", "target", "aborted", "kernel", "unreserved", "reserved", "total", "read", "write", "queue", "limited", "sample", "count", "touched", "percentage", "seeks", "consumed", "medium", "small", "large", "active", "observed", "time"}; for (String chunk : nameChunks) { name = condenseName(name, chunk); } name = normalizeName(name); String full = group + name + rollup; if (full.length() >= 19) { System.out.println("******************************************"); System.out.println("Key '" + full + "' is " + full.length() + " characters long"); System.out.println("******************************************"); } return full; } private void lookupMetrics(String collectionName, String managedObjectId) throws Exception { ManagedObjectReference managedObjectReference = new ManagedObjectReference(); managedObjectReference.setType("ManagedEntity"); managedObjectReference.setVal(managedObjectId); ManagedEntity managedEntity = MorUtil.createExactManagedEntity(serviceInstance.getServerConnection(), managedObjectReference); int refreshRate = performanceManager.queryPerfProviderSummary(managedEntity).getRefreshRate(); PerfQuerySpec perfQuerySpec = new PerfQuerySpec(); perfQuerySpec.setEntity(managedEntity.getMOR()); perfQuerySpec.setMaxSample(Integer.valueOf(1)); perfQuerySpec.setIntervalId(refreshRate); PerfEntityMetricBase[] perfEntityMetricBases = performanceManager.queryPerf(new PerfQuerySpec[]{perfQuerySpec}); HashMap<String, TreeSet<VMwareConfigMetric>> groupMap = new HashMap<String, TreeSet<VMwareConfigMetric>>(); HashMap<String, Boolean> multiInstance = new HashMap<String, Boolean>(); if (perfEntityMetricBases != null) { for (int i = 0; i < perfEntityMetricBases.length; i++) { PerfMetricSeries[] perfMetricSeries = ((PerfEntityMetric) perfEntityMetricBases[i]).getValue(); for (int j = 0; perfMetricSeries != null && j < perfMetricSeries.length; j++) { if (perfMetricSeries[j] instanceof PerfMetricIntSeries) { long[] longs = ((PerfMetricIntSeries) perfMetricSeries[j]).getValue(); if (longs.length == 1) { PerfCounterInfo perfCounterInfo = perfCounterInfoMap.get(perfMetricSeries[j].getId().getCounterId()); String instanceName = perfMetricSeries[j].getId().getInstance(); String humanReadableName = getHumanReadableName(perfCounterInfo); String aliasName = getAliasName(perfCounterInfo); String groupName = perfCounterInfo.getGroupInfo().getKey(); String normalizedGroupName = normalizeGroupName(groupName); Boolean b = multiInstance.get(getHumanReadableName(perfCounterInfo)); if (b == null) { b = Boolean.valueOf(instanceName != null && !"".equals(instanceName)); } else { b = Boolean.valueOf(b.booleanValue() || (instanceName != null && !"".equals(instanceName))); } if (!b) { groupName = "Node"; normalizedGroupName = "Node"; } if (!groupMap.containsKey(normalizedGroupName)) { groupMap.put(normalizedGroupName, new TreeSet<VMwareConfigMetric>()); } TreeSet<VMwareConfigMetric> counterSet = groupMap.get(normalizedGroupName); multiInstance.put(getHumanReadableName(perfCounterInfo), b); counterSet.add(new VMwareConfigMetric(perfCounterInfo, humanReadableName, aliasName, b, normalizedGroupName)); } } } } } collections.put(collectionName, groupMap); } private void generateData(String rrdRepository) throws Exception { serviceInstance = new ServiceInstance(new URL("https://" + hostname + "/sdk"), username, password); performanceManager = serviceInstance.getPerformanceManager(); PerfCounterInfo[] perfCounterInfos = performanceManager.getPerfCounter(); for (PerfCounterInfo perfCounterInfo : perfCounterInfos) { perfCounterInfoMap.put(perfCounterInfo.getKey(), perfCounterInfo); } System.out.println("Generating configuration files for '" + serviceInstance.getAboutInfo().getFullName() + "' using rrdRepository '" + rrdRepository + "'..."); StringBuffer buffer = new StringBuffer(); buffer.append("Configuration file generated for:\n\n"); buffer.append("Full name.......: " + serviceInstance.getAboutInfo().getFullName() + "\n"); buffer.append("API type........: " + serviceInstance.getAboutInfo().getApiType() + "\n"); buffer.append("API version.....: " + serviceInstance.getAboutInfo().getApiVersion() + "\n"); buffer.append("Product name....: " + serviceInstance.getAboutInfo().getLicenseProductName() + "\n"); buffer.append("Product version.: " + serviceInstance.getAboutInfo().getLicenseProductVersion() + "\n"); buffer.append("OS type.........: " + serviceInstance.getAboutInfo().getOsType() + "\n"); versionInformation = buffer.toString(); String arr[] = serviceInstance.getAboutInfo().getApiVersion().split("\\."); if (arr.length > 1) { apiVersion = arr[0]; if (Integer.valueOf(apiVersion) < 4) { apiVersion = "3"; } } ManagedEntity[] hostSystems, virtualMachines; virtualMachines = new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntities("VirtualMachine"); if (virtualMachines != null) { if (virtualMachines.length > 0) { for (ManagedEntity managedEntity : virtualMachines) { if ("poweredOn".equals(((VirtualMachine) managedEntity).getRuntime().getPowerState().toString())) { lookupMetrics("default-VirtualMachine" + apiVersion, managedEntity.getMOR().getVal()); break; } } } else { System.err.println("No virtual machines found"); } } hostSystems = new InventoryNavigator(serviceInstance.getRootFolder()).searchManagedEntities("HostSystem"); if (hostSystems != null) { if (hostSystems.length > 0) { for (ManagedEntity managedEntity : hostSystems) { if ("poweredOn".equals(((HostSystem) managedEntity).getRuntime().getPowerState().toString())) { lookupMetrics("default-HostSystem" + apiVersion, managedEntity.getMOR().getVal()); break; } } } else { System.err.println("No host systems found!"); } } saveVMwareDatacollectionConfig(rrdRepository); saveVMwareDatacollectionInclude(); saveVMwareGraphProperties(); } private void saveVMwareGraphProperties() { StringBuffer buffer = new StringBuffer(); StringBuffer include = new StringBuffer(); HashMap<String, Boolean> generatedGraphs = new HashMap<String, Boolean>(); for (String collectionName : collections.keySet()) { Map<String, TreeSet<VMwareConfigMetric>> collection = collections.get(collectionName); for (String groupName : collection.keySet()) { TreeSet<VMwareConfigMetric> metrics = collection.get(groupName); for (VMwareConfigMetric vmwarePerformanceMetric : metrics) { Boolean generated = (generatedGraphs.get(vmwarePerformanceMetric.getAliasName()) == null ? false : generatedGraphs.get(vmwarePerformanceMetric.getAliasName())); if (!generated) { generatedGraphs.put(vmwarePerformanceMetric.getAliasName(), Boolean.TRUE); buffer.append(vmwarePerformanceMetric.getGraphDefinition(apiVersion)); include.append(vmwarePerformanceMetric.getInclude(apiVersion)); } } } } final String content = include.toString(); saveFile("vmware" + apiVersion + "-graph-simple.properties", "reports=" + content.subSequence(0, content.length() - 4) + "\n\n" + buffer.toString()); } private void saveFile(String filename, String contents) { System.out.println("Saving file '" + filename + "'..."); try { FileWriter f = new FileWriter(filename); f.write(contents); f.close(); } catch (IOException e) { e.printStackTrace(); } } private void saveVMwareDatacollectionInclude() { StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\"?>\n"); buffer.append("\n<! buffer.append(versionInformation); buffer.append(" buffer.append("<datacollection-group name=\"VMware" + apiVersion + "\">\n\n"); TreeSet<String> groupNames = new TreeSet<String>(); for (String collectionName : collections.keySet()) { Map<String, TreeSet<VMwareConfigMetric>> collection = collections.get(collectionName); groupNames.addAll(collection.keySet()); } for (String groupName : groupNames) { if (!"node".equalsIgnoreCase(groupName)) { buffer.append(" <resourceType name=\"vmware" + apiVersion + groupName + "\" label=\"VMware v" + apiVersion + " " + groupName + "\" resourceLabel=\"${vmware" + apiVersion + groupName + "Name}\">\n"); buffer.append(" <persistenceSelectorStrategy class=\"org.opennms.netmgt.collectd.PersistAllSelectorStrategy\"/>\n"); buffer.append(" <storageStrategy class=\"org.opennms.netmgt.dao.support.IndexStorageStrategy\"/>\n"); buffer.append(" </resourceType>\n\n"); } } buffer.append("</datacollection-group>"); saveFile("vmware" + apiVersion + ".xml", buffer.toString()); } private void saveVMwareDatacollectionConfig(String rrdRepository) { StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\"?>\n"); buffer.append("\n<! buffer.append(versionInformation); buffer.append(" buffer.append("<vmware-datacollection-config rrdRepository=\"" + rrdRepository + "\">\n"); for (String collectionName : collections.keySet()) { Map<String, TreeSet<VMwareConfigMetric>> collection = collections.get(collectionName); buffer.append(" <vmware-collection name=\"" + collectionName + "\">\n"); buffer.append(" <rrd step=\"300\">\n"); buffer.append(" <rra>RRA:AVERAGE:0.5:1:2016</rra>\n"); buffer.append(" <rra>RRA:AVERAGE:0.5:12:1488</rra>\n"); buffer.append(" <rra>RRA:AVERAGE:0.5:288:366</rra>\n"); buffer.append(" <rra>RRA:MAX:0.5:288:366</rra>\n"); buffer.append(" <rra>RRA:MIN:0.5:288:366</rra>\n"); buffer.append(" </rrd>\n"); buffer.append(" <vmware-groups>\n"); for (String groupName : collection.keySet()) { if ("node".equalsIgnoreCase(groupName)) { buffer.append(" <vmware-group name=\"vmware" + apiVersion + groupName + "\" resourceType=\"" + groupName + "\">\n"); } else { buffer.append(" <vmware-group name=\"vmware" + apiVersion + groupName + "\" resourceType=\"vmware" + apiVersion + groupName + "\">\n"); } TreeSet<VMwareConfigMetric> metrics = collection.get(groupName); for (VMwareConfigMetric vmwarePerformanceMetric : metrics) { buffer.append(vmwarePerformanceMetric.getDatacollectionEntry()); } buffer.append(" </vmware-group>\n"); } buffer.append(" </vmware-groups>\n"); buffer.append(" </vmware-collection>\n"); } buffer.append("</vmware-datacollection-config>\n"); saveFile("vmware" + apiVersion + "-datacollection-config.xml", buffer.toString()); } private static void usage(final Options options, final CommandLine cmd, final String error, final Exception e) { final HelpFormatter formatter = new HelpFormatter(); final PrintWriter pw = new PrintWriter(System.out); if (error != null) { pw.println("An error occurred: " + error + "\n"); } formatter.printHelp("Usage: VmwareConfigBuilder <hostname> <username> <password>", options); if (e != null) { pw.println(e.getMessage()); e.printStackTrace(pw); } pw.close(); } private static void usage(final Options options, final CommandLine cmd) { usage(options, cmd, null, null); } public static void main(String args[]) throws ParseException { String hostname = null; String username = null; String password = null; String rrdRepository = null; final Options options = new Options(); options.addOption("rrdRepository", true, "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'"); final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); @SuppressWarnings("unchecked") List<String> arguments = (List<String>) cmd.getArgList(); if (arguments.size() < 3) { usage(options, cmd); System.exit(1); } hostname = arguments.remove(0); username = arguments.remove(0); password = arguments.remove(0); if (cmd.hasOption("rrdRepository")) { rrdRepository = cmd.getOptionValue("rrdRepository"); } else { rrdRepository = "/opt/opennms/share/rrd/snmp/"; } TrustManager[] trustAllCerts = new TrustManager[1]; trustAllCerts[0] = new TrustAllManager(); SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); VmwareConfigBuilder vmwareConfigBuilder; vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password); try { vmwareConfigBuilder.generateData(rrdRepository); } catch (Exception e) { e.printStackTrace(); } } }
package com.tightdb.refdoc; import java.io.FileNotFoundException; import java.io.PrintWriter; import com.tightdb.*; public class DynTableExamples { public static void main(String[] args) throws FileNotFoundException { // Table methods: isValidExample(); sizeExample(); isEmptyExample(); clearExample(); //TODO getSortedViewExample(); //TODO optimizeExample(); //TODO setIndexExample(); //TODO hasIndexExample(); // Columns methods: addColumnExample(); removeColumnExample(); renameColumnExample(); getColumnCountExample(); getColumnNameExample(); getColumnIndexExample(); getColumnTypeExample(); // Rows methods: addAtExample(); addAtExample(); setRowExample(); removeExample(); removeLastExample(); addEmptyRowExample(); addEmptyRowsExample(); adjustExample(); // Cells methods: getExamples(); setExamples(); //TODO getSubtableSize(); //TODO clearSubtable // Searching methods: findFirstExamples(); findAllExample(); distinctExample(); whereExample(); // Aggregates methods: sumExample(); maximumExample(); minimumExample(); averageExample(); // Dump methods: toJsonExample(); } // Table methods public static void isValidExample(){ // @@Example: ex_java_dyn_table_is_valid @@ // @@Show@@ // Open a group from file Group fromFile = new Group( /* filepath.tightdb */); // Get table from group Table table = fromFile.getTable("peopleTable"); // Group is closed fromFile.close(); if( table.isValid()) { long size = table.size(); } else { System.out.println("Group has been closed, table is no longer valid"); } // @@EndShow@@ // @@EndExample@@ } public static void sizeExample(){ // @@Example: ex_java_dyn_table_size @@ // @@Show@@ // Creates table with 2 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); // Add data to the table table.add(100, "Washington"); table.add(200, "Los Angeles"); // 2 rows have been added Assert(table.size() == 2); // @@EndShow@@ // @@EndExample@@ } public static void isEmptyExample(){ // @@Example: ex_java_dyn_table_is_empty @@ // @@Show@@ // Creates table with 2 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); // No data has been added to the table // Table is empty Assert(table.isEmpty()); // Table.size is 0 Assert(table.size() == 0); // @@EndShow@@ // @@EndExample@@ } public static void clearExample(){ // @@Example: ex_java_dyn_table_clear @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); // Remove all rows in table table.clear(); // Table.size is now 0 Assert(table.size() == 0); // Table is empty Assert(table.isEmpty()); // @@EndShow@@ // @@EndExample@@ } // Columns methods public static void addColumnExample(){ // @@Example: ex_java_dyn_table_add_column @@ // @@Show@@ // Create new table Table table = new Table(); // Add column table.addColumn(ColumnType.BINARY, "binary"); table.addColumn(ColumnType.BOOLEAN, "boolean"); table.addColumn(ColumnType.DATE, "date"); table.addColumn(ColumnType.DOUBLE, "double"); table.addColumn(ColumnType.FLOAT, "float"); table.addColumn(ColumnType.INTEGER, "integer"); table.addColumn(ColumnType.MIXED, "mixed"); table.addColumn(ColumnType.STRING, "string"); table.addColumn(ColumnType.MIXED, "mixed"); // Column count should be 9 Assert(table.getColumnCount() == 9); // @@EndShow@@ // @@EndExample@@ } public static void removeColumnExample(){ // @@Example: ex_java_dyn_table_remove_column @@ // @@Show@@ // Create new table and add 3 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "id"); table.addColumn(ColumnType.STRING, "name"); table.addColumn(ColumnType.STRING, "extra"); // Remove column 'extra' table.removeColumn(2); // Column count should be 2 Assert(table.getColumnCount() == 2); // @@EndShow@@ // @@EndExample@@ } public static void renameColumnExample(){ // @@Example: ex_java_dyn_table_rename_column @@ // @@Show@@ // Create new table and add 3 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "id"); table.addColumn(ColumnType.STRING, "name"); table.addColumn(ColumnType.STRING, "extra"); // Rename column 2 table.renameColumn(2, "newName"); // Column name in column 2 should be 'newName' Assert(table.getColumnName(2).equals("newName")); // @@EndShow@@ // @@EndExample@@ } public static void getColumnCountExample(){ // @@Example: ex_java_dyn_table_get_column_count @@ // @@Show@@ // Create new table and add 3 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "id"); table.addColumn(ColumnType.STRING, "name"); table.addColumn(ColumnType.STRING, "extra"); // Column count should be 3 Assert(table.getColumnCount() == 3); // @@EndShow@@ // @@EndExample@@ } public static void getColumnNameExample(){ // @@Example: ex_java_dyn_table_get_column_name @@ // @@Show@@ // Create new table and add 3 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "id"); table.addColumn(ColumnType.STRING, "name"); table.addColumn(ColumnType.STRING, "extra"); // Column name in column 2 should be 'extra' Assert(table.getColumnName(2).equals("extra")); // @@EndShow@@ // @@EndExample@@ } public static void getColumnIndexExample(){ // @@Example: ex_java_dyn_table_get_column_index @@ // @@Show@@ // Create new table and add 3 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "id"); table.addColumn(ColumnType.STRING, "name"); table.addColumn(ColumnType.STRING, "extra"); // Column index of column 'name' is 1 Assert(table.getColumnIndex("name") == 1); // @@EndShow@@ // @@EndExample@@ } public static void getColumnTypeExample(){ // @@Example: ex_java_dyn_table_get_column_type @@ // @@Show@@ // Create new table and add 3 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "id"); table.addColumn(ColumnType.STRING, "name"); table.addColumn(ColumnType.BOOLEAN, "hidden"); // Column type of column 2 is boolean Assert(table.getColumnType(2).equals(ColumnType.BOOLEAN)); // @@EndShow@@ // @@EndExample@@ } // Rows methods public static void addExample(){ // @@Example: ex_java_dyn_table_add @@ // @@Show@@ // Create table with 2 columns Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); // Add data to the table table.add(100, "Washington"); table.add(200, "Los Angeles"); // @@EndShow@@ // @@EndExample@@ } public static void addEmptyRowExample(){ // @@Example: ex_java_dyn_table_add_empty_row @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); // Add an empty row with default values table.addEmptyRow(); // Table.size is now 3 Assert(table.size() == 3); //Default values check Assert(table.getLong(0, 2) == 0); Assert(table.getString(1, 2).equals("")); // @@EndShow@@ // @@EndExample@@ } public static void addEmptyRowsExample(){ // @@Example: ex_java_dyn_table_add_empty_rows @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); // Add 10 empty rows with default values table.addEmptyRows(10); // Table.size is now 12 Assert(table.size() == 12); //Default values check Assert(table.getLong(0, 11) == 0); Assert(table.getString(1, 11).equals("")); // @@EndShow@@ // @@EndExample@@ } public static void addAtExample(){ // @@Example: ex_java_dyn_table_add_at @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); table.add(300, "New York"); // Add a row at row index 2 and shift the subsequent rows one down table.addAt(2, 250, "Texas"); // @@EndShow@@ // @@EndExample@@ } public static void setRowExample(){ // @@Example: ex_java_dyn_table_set_row @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); // Replaces the the first row table.set(0, 100, "Washington DC"); Assert(table.getString(1, 0).equals("Washington DC")); // @@EndShow@@ // @@EndExample@@ } public static void removeExample(){ // @@Example: ex_java_dyn_table_remove @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); // Removes the the first row table.remove(0); // Table.size is now 1 Assert(table.size() == 1); // @@EndShow@@ // @@EndExample@@ } public static void removeLastExample(){ // @@Example: ex_java_dyn_table_remove_last_row @@ // @@Show@@ // Create table with 2 columns and add ata Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); table.add(300, "New York"); table.add(400, "Miami"); // Removes the the last row table.removeLast(); // Table.size is now 3 Assert(table.size() == 3); // @@EndShow@@ // @@EndExample@@ } public static void adjustExample(){ // @@Example: ex_java_dyn_table_adjust @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.add("user1", 420); table.add("user2", 770); // Reward all users 100 extra points using the adjust method table.adjust(1, 100); // Check that all scores are increased by 100 Assert(table.getLong(1, 0) == 520); Assert(table.getLong(1, 1) == 870); // @@EndShow@@ // @@EndExample@@ } // Cells methods public static void getExamples(){ // @@Example: ex_java_dyn_table_get @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.add("user1", 420); table.add("user2", 770); // Get String value of cell at position 0,0 String user1 = table.getString(0, 0); // Get long value value of cell at position 1,1 // NB! Column type in tightdb is INTEGER // In java it is accessed by getLong(col, row); long score2 = table.getLong(1, 1); // Check values Assert(user1.equals("user1")); Assert(score2 == 770); // Throws exception if column or row index is out of range try { long score = table.getLong(1, 3); } catch (ArrayIndexOutOfBoundsException e){ } // Throws exception if accessor method and column type do not match try { boolean bool = table.getBoolean(0, 0); } catch (IllegalArgumentException e){ } // @@EndShow@@ // @@EndExample@@ } public static void setExamples(){ // @@Example: ex_java_dyn_table_set @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.add("user1", 420); table.add("user2", 770); // Set a new username in cell at position 0,0 table.setString(0, 0, "Liquid Droid"); // Reset the users score to 0 in cell 1,1 // NB. Column type in tightdb is INTEGER // In java it is set by setLong(col, row, value); table.setLong(1, 1, 0); // Check values Assert(table.getString(0, 0).equals("Liquid Droid")); Assert(table.getLong(1,1) == 0); // Throws exception if column or row index is out of range try { table.setLong(1, 50, 200); } catch (ArrayIndexOutOfBoundsException e){ } // Throws exception if mutator method and column type do not match try { table.setBoolean(0, 0, true); } catch (IllegalArgumentException e){ } // @@EndShow@@ // @@EndExample@@ } /*public static void getSubtableSizeExample(){ }*/ /*public static void clearSubtableExample(){ }*/ // Searching methods public static void findFirstExamples(){ // @@Example: ex_java_dyn_table_find_first @@ // @@Show@@ // Create table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // Find first row index where column 2 is true long rowIndex = table.findFirstBoolean(2, true); Assert(table.getString(0, rowIndex).equals("user5")); // @@EndShow@@ // @@EndExample@@ } public static void findAllExample(){ // @@Example: ex_java_dyn_table_find_all @@ // @@Show@@ // Create table with 3 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // Find all rows where column 2 is true. Return a view TableView view = table.findAllBoolean(2, true); // Check that resulting view has 3 rows Assert(view.size() == 3); // @@EndShow@@ // @@EndExample@@ } public static void distinctExample(){ // @@Example: ex_java_dyn_table_distinct @@ // @@Show@@ // Create table with 1 column and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "country"); table.add("UK"); table.add("UK"); table.add("US"); table.add("US"); table.add("US"); table.add("US"); table.add("China"); table.add("China"); table.add("US"); table.add("US"); table.add("US"); table.add("China"); // Set index before using distinct table.setIndex(0); // Call distinct on column 0. Method return a table view TableView view = table.distinct(0); // Check that resulting view has 3 rows; China, UK and US Assert(view.size() == 3); // @@EndShow@@ // @@EndExample@@ } public static void whereExample(){ // @@Example: ex_java_dyn_table_where @@ // @@Show@@ // Create table with 3 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // Get a query from the table TableQuery query = table.where(); // USe the query object to query the table and get a table view with the results TableView view = query.equal(2, false).findAll(); // @@EndShow@@ // @@EndExample@@ } // Aggregates methods public static void sumExample(){ // @@Example: ex_java_dyn_table_sum @@ // @@Show@@ // Create table with 3 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // The sum of all values in column 1 long totalScore = table.sum(1); // @@EndShow@@ // @@EndExample@@ } public static void maximumExample(){ // @@Example: ex_java_dyn_table_maximum @@ // @@Show@@ // Create table with 3 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // The maximum score in column 1 long maxScore = table.maximum(1); // @@EndShow@@ // @@EndExample@@ } public static void minimumExample(){ // @@Example: ex_java_dyn_table_minimum @@ // @@Show@@ // Create table with 3 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // The minimum score in column 1 long minScore = table.minimum(1); // @@EndShow@@ // @@EndExample@@ } public static void averageExample(){ // @@Example: ex_java_dyn_table_average @@ // @@Show@@ // Create table with 3 columns and add data Table table = new Table(); table.addColumn(ColumnType.STRING, "username"); table.addColumn(ColumnType.INTEGER, "score"); table.addColumn(ColumnType.BOOLEAN, "completed"); table.add("user1", 420, false); table.add("user2", 770, false); table.add("user3", 327, false); table.add("user4", 770, false); table.add("user5", 564, true); table.add("user6", 875, false); table.add("user7", 420, true); table.add("user8", 770, true); // The average score in column 1 double avgScore = table.average(1); // Returns a double // @@EndShow@@ // @@EndExample@@ } // Dump methods public static void toJsonExample() throws FileNotFoundException{ // @@Example: ex_java_dyn_table_to_json @@ // @@Show@@ // Creates table with 2 columns and add data Table table = new Table(); table.addColumn(ColumnType.INTEGER, "ID"); table.addColumn(ColumnType.STRING, "City"); table.add(100, "Washington"); table.add(200, "Los Angeles"); String json = table.toJson(); // Print json e.g. using a printbwriter PrintWriter out = new PrintWriter("fromServlet"); out.print(json); out.close(); Assert(json.equals("[{\"ID\":100,\"City\":\"Washington\"},{\"ID\":200,\"City\":\"Los Angeles\"}]")); // @@EndShow@@ // @@EndExample@@ } static void Assert(boolean check) { if (!check) { throw new RuntimeException(); } } }
package org.pale.gorm.roomutils; import org.bukkit.Material; import org.pale.gorm.Castle; import org.pale.gorm.Direction; import org.pale.gorm.Extent; import org.pale.gorm.GormPlugin; import org.pale.gorm.IntVector; import org.pale.gorm.MaterialManager; import org.pale.gorm.Room; import org.pale.gorm.Util; /** * Class for making and decorating windows. Beware the old grey windowmaker! * * @author white * */ public class WindowMaker { private static final float WINDOW_CHANCE = 0.3f; /** * Build a window covering the given extent. The key is a random value used * to make sure windows built at the same time look the same. * * @param mgr * @param e * extent of window * @param re * extent of containing room * @param out * @param key */ public static void window(MaterialManager mgr, Extent e, Extent re, Direction out, int key) { // first blow the hole itself Castle c = Castle.getInstance(); c.fill(e, Material.AIR, 0); // the window is glazed if it is above the floor or one unit in height. boolean glazed = (re.miny + 1) < e.miny || (e.ysize() == 1); // sometimes, glazing becomes iron bars. boolean ironNotGlass = ((key & 1) == 0); // so let's fill it if (glazed) //If not iron, get material and data of window material c.fill(e, ironNotGlass ? Material.IRON_FENCE : mgr.getWindow().m , ironNotGlass ? 0 : mgr.getWindow().d); else { // this window isn't going to get filled, lets put some bars in c.fill(e, Material.IRON_FENCE, 0); } } /** * Given a material manager and room extent, make a set of windows. * * @param mgr * @param e */ public static void buildWindows(MaterialManager mgr, Room r) { Castle c = Castle.getInstance(); int key = c.r.nextInt(); Extent roomExt = r.getExtent(); int y; // base of window within the wall // window heights are more common at certain fixed positions switch (c.r.nextInt(5)) { case 0: y = 1; break; // windows on the floor case 1: y = 2; break; // windows at eye level case 2: y = roomExt.ysize() - 3; break; // windows near ceiling default: y = c.r.nextInt(roomExt.ysize() - 4) + 1; break; // random } int height = c.r.nextInt(roomExt.ysize() - y); if (y == 1 && height < 2) height = 2; // deal with silly windows. GormPlugin.log(String.format("Room extent: %s, height=%d, y=%d", roomExt.toString(), height, y)); // for each wall, build windows! for (Direction d : Direction.values()) { if (d.vec.y == 0 && c.r.nextFloat() < WINDOW_CHANCE) { // don't put windows on // every wall, and // only vertical // walls! GormPlugin.log("Windows for direction " + d.toString()); Extent wallExtent = roomExt.getWall(d); // the wall on that side int width = 1 + Util.randomExp(c.r, 2); int len = wallExtent.getLengthOfAxis(Extent.LONGESTXZ); int step = c.r.nextInt(Math.min(len / 3,1)) + width + 1; int offset = (len % step + (step - width)) / 2; // pull the wall in by 2 to avoid putting windows in the corner. // Nobody puts windows in the corner. wallExtent = wallExtent.expand(-2, Extent.LONGESTXZ); for (IntVector pos : wallExtent.getVectorIterable(step, offset, true)) { Extent window = new Extent(); window = window.union(pos.add(0, y, 0)).union( pos.add(0, y + height - 1, 0)); if (wallExtent.contains(window) // avoid wide window // overrun && !r.exitIntersects(window.expand(2, Extent.X | Extent.Z))) {// avoid overwriting // exits window(mgr,window,roomExt,d,key); r.addWindow(window); } } } } } }
package org.kuali.kfs.sys.service.impl; import junit.framework.Assert; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.kuali.kfs.sys.exception.FileStorageException; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; /** * Test the File system implementation of the File Storage Service */ public class FileSystemFileStorageServiceImplTest { private final static String FILE_DATA = "line 1\nline 2\n"; private FileSystemFileStorageServiceImpl service; private String tempFolder; private boolean fileExists(String filename) { File f = new File(tempFolder + filename); return f.exists(); } private String getUniqueFilename(String extension) { String filename; do { filename = RandomStringUtils.randomAlphanumeric(8); } while ((new File( tempFolder + filename + (extension != null ? "." + extension : "") )).exists()); return filename; } private String getUniqueFilename() { return getUniqueFilename(null); } private void createFile(String filename) throws IOException { File f = new File(tempFolder + filename); FileUtils.writeStringToFile(f, FILE_DATA); } private void deleteFile(String filename) { File f = new File(tempFolder + filename); f.delete(); } private void makeDirectory(String directory) { File f = new File(tempFolder + directory); if ( ! f.mkdir() ) { System.out.println("WTF?"); } } @Before public void setup() { tempFolder = System.getProperty("java.io.tmpdir"); service = new FileSystemFileStorageServiceImpl(); service.setPathPrefix(tempFolder); } @Test public void testSeparatorReturnsOperatingSystemSeparator() { FileSystemFileStorageServiceImpl service = new FileSystemFileStorageServiceImpl(); Assert.assertEquals("Should return operating system separator", File.separator, service.separator()); } @Test public void testSavesToFile() throws IOException { String filename = getUniqueFilename("txt"); service.open(filename,(outputFile) -> { PrintWriter pw = new PrintWriter(outputFile.getOutputStream()); pw.print("test"); pw.flush(); }); String data = FileUtils.readFileToString(new File(tempFolder + filename)); (new File(tempFolder + filename)).delete(); Assert.assertEquals("File should have been written", "test", data); } @Test public void testSavesFail() { String filename = getUniqueFilename("txt"); makeDirectory(filename); try { service.open(filename, (outputFile) -> { PrintWriter pw = new PrintWriter(outputFile.getOutputStream()); pw.print("test"); pw.flush(); }); Assert.fail("Should have thrown exception"); } catch (FileStorageException e) { // This is expected } deleteFile(filename); } @Test public void testFileExists() throws IOException { String filename = getUniqueFilename("txt"); createFile(filename); Assert.assertEquals("File should exist", true, service.fileExists(filename)); deleteFile(filename); } @Test public void testFileExistsDirectory() { String filename = getUniqueFilename("txt"); makeDirectory(filename); Assert.assertEquals("File should not exist", false, service.fileExists(filename)); deleteFile(filename); } @Test public void testFileExistsNoFile() { String filename = getUniqueFilename("txt"); Assert.assertEquals("File should not exist", false, service.fileExists(filename)); } @Test public void testGetFileGoodFile() throws IOException { String filename = getUniqueFilename("txt"); createFile(filename); InputStream is = service.getFileStream(filename); InputStreamReader isr = new InputStreamReader(is, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); Assert.assertEquals("Should have read data from file", "line 1", line); deleteFile(filename); } @Test public void testGetFileNotGoodFile() { String filename = getUniqueFilename("txt"); try { service.getFileStream(filename); Assert.fail("Method should have thrown exception"); } catch (FileStorageException e) { // This is expected } } @Test public void testReadFileContents() throws IOException { String filename = getUniqueFilename("txt"); createFile(filename); List<String> lines = service.getFileContents(filename); Assert.assertEquals("Line 1 should be read", "line 1", lines.get(0)); Assert.assertEquals("Line 2 should be read", "line 2", lines.get(1)); deleteFile(filename); } @Test public void testReadFileContentsFileNotExist() { String filename = getUniqueFilename("txt"); try { service.getFileContents(filename); Assert.fail("Method should have thrown exception"); } catch (FileStorageException e) { // This is expected } } @Test public void testDeleteFile() throws IOException { String filename = getUniqueFilename("txt"); createFile(filename); service.delete(filename); File f = new File(tempFolder + filename); Assert.assertEquals("File should not exist", false, f.exists()); } @Test public void testDeleteFileDirectory() { String filename = getUniqueFilename("txt"); makeDirectory(filename); try { service.delete(filename); Assert.fail("Method should have thrown exception"); } catch (Exception e) { // This is expected } deleteFile(filename); } @Test public void testDeleteFileNotExist() { String filename = getUniqueFilename("txt"); try { service.delete(filename); Assert.fail("Method should have thrown exception"); } catch (Exception e) { // This is expected } } @Test public void testGetMatchingFiles() throws IOException { String dir1 = getUniqueFilename(); String dir2 = getUniqueFilename(); makeDirectory(dir1); makeDirectory(dir2); createFile(dir1 + File.separator + "data1.data"); createFile(dir1 + File.separator + "data2.data"); createFile(dir1 + File.separator + "data3.done"); createFile(dir2 + File.separator + "data3.done"); // Some results List<String> matches = service.getFilesMatching(dir1,"data"); Assert.assertEquals("Should have found 2 files", 2, matches.size()); // No results matches = service.getFilesMatching(dir2,"data"); Assert.assertEquals("Should have found 0 files",0,matches.size()); // No extensions specified some results matches = service.getFilesMatching(dir1); Assert.assertEquals("Should have found 3 files", 3, matches.size()); // No extensions specified no results matches = service.getFilesMatching(dir2); Assert.assertEquals("Should have found 1 file", 1, matches.size()); deleteFile(dir1 + File.separator + "data1.data"); deleteFile(dir1 + File.separator + "data2.data"); deleteFile(dir1 + File.separator + "data3.done"); deleteFile(dir2 + File.separator + "data3.done"); deleteFile(dir1); deleteFile(dir2); } @Test public void testMakeDirectorySuccess() { String dirname = getUniqueFilename(); service.mkdir(dirname); File d = new File(tempFolder + dirname); Assert.assertEquals("Directory should exist",true,d.exists()); Assert.assertEquals("Should be a directory", true, d.isDirectory()); deleteFile(dirname); } @Test public void testMakeDirectoryFail() { String dirname = getUniqueFilename(); makeDirectory(dirname); try { service.mkdir(dirname); Assert.fail("Should have thrown exception"); } catch (FileStorageException e) { // This is expected } deleteFile(dirname); } @Test public void testEmptyDirectory() throws IOException { String dir1 = getUniqueFilename(); makeDirectory(dir1); createFile(dir1 + File.separator + "data1.data"); createFile(dir1 + File.separator + "data2.data"); createFile(dir1 + File.separator + "data3.done"); service.emptyDirectory(dir1); File f = new File(tempFolder + dir1); Assert.assertEquals("Folder not empty", true, f.delete()); } @Test public void testEmptyDirectoryError() throws IOException { String filename = getUniqueFilename(); createFile(filename); try { service.emptyDirectory(filename); Assert.fail("The method should have thrown an exception"); } catch (FileStorageException e) { // This is expected } deleteFile(filename); } @Test public void testRmdir() { String dirname = getUniqueFilename(); makeDirectory(dirname); service.rmdir(dirname); File f = new File(tempFolder + dirname); Assert.assertEquals("Directory should not exist", false, f.exists()); } @Test public void testRmdirFail() throws IOException { String filename = getUniqueFilename(); createFile(filename); try { service.rmdir(filename); Assert.fail("The method should have thrown an exception"); } catch (FileStorageException e) { // This is expected } deleteFile(filename); } @Test public void testDirectoryExists() throws IOException { String dirname = getUniqueFilename(); makeDirectory(dirname); String dirname2 = getUniqueFilename(); String filename = getUniqueFilename(); createFile(filename); Assert.assertEquals("Directory exists",true,service.directoryExists(dirname)); Assert.assertEquals("Directory should not exist",false,service.directoryExists(dirname2)); Assert.assertEquals("File is not a directory",false,service.directoryExists(filename)); deleteFile(dirname); deleteFile(filename); } @Test public void testCreateDoneFile() { String filename = getUniqueFilename(); service.createDoneFile(filename + ".data"); File f = new File(tempFolder + filename + ".done"); Assert.assertEquals("Done file should exist", true, f.exists()); deleteFile(filename + ".done"); } @Test public void testCreateDoneFileFail() { String filename = getUniqueFilename(); makeDirectory(filename + ".done"); try { service.createDoneFile(filename + ".data"); Assert.fail("method should have thrown exception"); } catch (FileStorageException e) { // This is expected } deleteFile(filename + ".done"); } @Test public void testRemoveDoneFiles() throws IOException { String filename1 = getUniqueFilename(); String filename2 = getUniqueFilename(); String filename3 = getUniqueFilename(); createFile(filename1 + ".done"); createFile(filename2 + ".done"); List<String> dataFiles = new ArrayList<>(); dataFiles.add(filename1 + ".data"); dataFiles.add(filename2 + ".data"); dataFiles.add(filename3 + ".data"); service.removeDoneFiles(dataFiles); Assert.assertEquals("file 1 should not exist", false, fileExists(filename1 + ".done")); Assert.assertEquals("file 2 should not exist", false, fileExists(filename2 + ".done")); } }
package com.elastisys.scale.cloudpool.kubernetes.client.impl; import java.util.function.Function; import org.joda.time.DateTime; import com.elastisys.scale.cloudpool.api.types.Machine; import com.elastisys.scale.cloudpool.api.types.MachineState; import com.elastisys.scale.commons.util.time.UtcTime; import com.google.gson.JsonObject; /** * A {@link Function} that takes a pod status JSON document (one * <code>item</code> of the output from * <code>kubectl get pods --selector="app=nginx" --output=json</code>) and * converts it to a {@link Machine} instance. * */ public class PodToMachine implements Function<JsonObject, Machine> { /** * Takes a pod status JSON document (one <code>item</code> of the output * from <code>kubectl get pods --selector="app=nginx" --output=json</code>) * and converts it to a {@link Machine} instance. */ @Override public Machine apply(JsonObject pod) { JsonObject status = pod.get("status").getAsJsonObject(); JsonObject metadata = pod.get("metadata").getAsJsonObject(); String id = metadata.get("name").getAsString(); MachineState machineState = new PodStateToMachineState() .apply(status.get("phase").getAsString()); String cloudProvider = "Kubernetes"; String region = "N/A"; String machineSize = "N/A"; DateTime requestTime = UtcTime .parse(metadata.get("creationTimestamp").getAsString()); // if pod isn't running, no startTime will be available String launchTimeValue = getWithDefault(status, "startTime", null); DateTime launchTime = launchTimeValue != null ? UtcTime.parse(launchTimeValue) : null; // if pod isn't running, no IPs will be available String publicIp = getWithDefault(status, "hostIP", "N/A"); String privateIp = getWithDefault(status, "podIP", "N/A"); return Machine.builder().id(id).machineState(machineState) .cloudProvider(cloudProvider).region(region) .machineSize(machineSize).launchTime(launchTime) .requestTime(requestTime).publicIp(publicIp) .privateIp(privateIp).metadata(pod).build(); } /** * Returns a given property field from a JSON object or returns a default * value in case the property is missing. * * @param object * @param property * @param defaultValue * @return */ private String getWithDefault(JsonObject object, String property, String defaultValue) { if (object.has(property)) { return object.get(property).getAsString(); } return defaultValue; } }
package tarski; import scala.Function0; import scala.Function1; import scala.Function2; import scala.collection.immutable.$colon$colon$; import scala.collection.immutable.List; import scala.collection.immutable.Nil$; import tarski.Scores.*; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import static java.lang.Math.max; import static tarski.Scores.oneError; import static tarski.Scores.nestError; public class JavaScores { // If true, failure causes are tracked via Bad. If false, only Empty and Best are used. static final boolean trackErrors = false; // To enable probability tracking, swap the comment blocks below and make the substitution // double /*Prob*/ -> DebugProb // except without the space. Also swap the definition of Prob in Scores, and fix the compile error in JavaTrie. // Divide two probabilities, turning infinity into 2 static double pdiv(double x, double y) { return y == 0 ? 2 : x/y; } // Indirection functions so that we can swap in DebugProb for debugging static final boolean trackProbabilities = false; static double pp(double x) { return x; } static double pmul(double x, double y) { return x*y; } static final double pzero = 0; static double padd(double x, double y) { return x+y; } static double pcomp(double x) { return 1-x; } static public Scores.Error ppretty(double x) { return new OneError(""+x); } // Named probabilities. Very expensive, so enable only for debugging. final double/*Prob*/ q; Biased(double/*Prob*/ q, Scored<B> s) { static public <A> Scored<A> uniformThen(double/*Prob*/ p, A[] xs, Scored<A> then) { static public <A> Scored<A> uniformThen(double/*Prob*/ p, List<A> xs, Scored<A> then) { private final double/*Prob*/ q; public LazyBias(LazyScored<A> x, double/*Prob*/ q) { abstract protected Best<B> map(double/*Prob*/ p, A x, Scored<B> r); // Apply the map protected Best<B> map(double/*Prob*/ p, A x, Scored<B> r) { return new Best<B>(p,f.apply(x),r); } private final double/*Prob*/ px; FX(double/*Prob*/ px, A x, Scored<B> y, Function2<A,B,C> f) { super(y,pp(px)*y.p()); this.px = px; this.x = x; this.f = f; } protected Best<C> map(double/*Prob*/ py, B y, Scored<C> r) { return new Best<C>(pmul(px,py),f.apply(x,y),r); } private final double/*Prob*/ py; FY(double/*Prob*/ py, Scored<A> x, B y, Function2<A,B,C> f) { super(x,x.p()*pp(py)); this.py = py; this.y = y; this.f = f; } protected Best<C> map(double/*Prob*/ px, A x, Scored<C> r) { return new Best<C>(pmul(px,py),f.apply(x,y),r); } final double/*Prob*/ xdp = _x.dp(); final double/*Prob*/ ydp = _y.dp(); private final double/*Prob*/ _p; LazyBiased(double/*Prob*/ p, Function0<Scored<A>> f) {
package com.javarush.test; public class Solution { public static void main(String[] args) { Integer i = 5; int x = transformValue(i); System.out.println(x); } public static int transformValue(int i) { return i*i; } }
package com.javarush.test; import java.awt.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Person person = null; String key; while (!(key = reader.readLine()).equals("exit")) { if ("player".equals(key)) { person = new Player(); } else if ("dancer".equals(key)) { person = new Dancer(); } haveRest(person); } } public static void haveRest(Person person) { //Add your code here } interface Person { } static class Player implements Person { void play() { System.out.println("playing"); } } static class Dancer implements Person { void dance() { System.out.println("dancing"); } } }
package com.javarush.test; import java.awt.*; public class Solution { public static void main(String[] args) { Object obj = //Add your code here Mouse mouse = (Mouse) obj; GreyMouse greyMouse = (GreyMouse) mouse; Jerry jerry = (Jerry) greyMouse; printClasses(obj, mouse, greyMouse, jerry); } public static void printClasses(Object obj, Mouse mouse, GreyMouse greyMouse, Jerry jerry) { System.out.println(jerry.getClass().getSimpleName()); System.out.println(greyMouse.getClass().getSimpleName()); System.out.println(mouse.getClass().getSimpleName()); System.out.println(obj.getClass().getSimpleName()); } static class Mouse { } static class GreyMouse extends Mouse { } static class Jerry extends GreyMouse { } }
package com.mindoo.domino.jna; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.nio.ByteBuffer; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TimeZone; import com.mindoo.domino.jna.NotesItem.ICompositeCallbackDirect; import com.mindoo.domino.jna.NotesNote.IItemCallback.Action; import com.mindoo.domino.jna.constants.CDRecordType; import com.mindoo.domino.jna.constants.Compression; import com.mindoo.domino.jna.constants.ItemType; import com.mindoo.domino.jna.constants.NoteClass; import com.mindoo.domino.jna.constants.OpenNote; import com.mindoo.domino.jna.constants.UpdateNote; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.LotusScriptCompilationError; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.errors.UnsupportedItemValueError; import com.mindoo.domino.jna.formula.FormulaExecution; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.html.CommandId; import com.mindoo.domino.jna.html.IHtmlApiReference; import com.mindoo.domino.jna.html.IHtmlApiUrlTargetComponent; import com.mindoo.domino.jna.html.IHtmlConversionResult; import com.mindoo.domino.jna.html.IHtmlImageRef; import com.mindoo.domino.jna.html.ReferenceType; import com.mindoo.domino.jna.html.TargetType; import com.mindoo.domino.jna.internal.CalNoteOpenData32; import com.mindoo.domino.jna.internal.CalNoteOpenData64; import com.mindoo.domino.jna.internal.CollationDecoder; import com.mindoo.domino.jna.internal.CompoundTextWriter; import com.mindoo.domino.jna.internal.DisposableMemory; import com.mindoo.domino.jna.internal.ItemDecoder; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesCallbacks; import com.mindoo.domino.jna.internal.NotesConstants; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.ReadOnlyMemory; import com.mindoo.domino.jna.internal.ViewFormatDecoder; import com.mindoo.domino.jna.internal.Win32NotesCallbacks; import com.mindoo.domino.jna.internal.structs.NoteIdStruct; import com.mindoo.domino.jna.internal.structs.NotesBlockIdStruct; import com.mindoo.domino.jna.internal.structs.NotesCDFieldStruct; import com.mindoo.domino.jna.internal.structs.NotesFileObjectStruct; import com.mindoo.domino.jna.internal.structs.NotesLSCompileErrorInfoStruct; import com.mindoo.domino.jna.internal.structs.NotesNumberPairStruct; import com.mindoo.domino.jna.internal.structs.NotesObjectDescriptorStruct; import com.mindoo.domino.jna.internal.structs.NotesOriginatorIdStruct; import com.mindoo.domino.jna.internal.structs.NotesRangeStruct; import com.mindoo.domino.jna.internal.structs.NotesTimeDatePairStruct; import com.mindoo.domino.jna.internal.structs.NotesTimeDateStruct; import com.mindoo.domino.jna.internal.structs.NotesUniversalNoteIdStruct; import com.mindoo.domino.jna.internal.structs.html.HTMLAPIReference32Struct; import com.mindoo.domino.jna.internal.structs.html.HTMLAPIReference64Struct; import com.mindoo.domino.jna.internal.structs.html.HtmlApi_UrlTargetComponentStruct; import com.mindoo.domino.jna.richtext.ICompoundText; import com.mindoo.domino.jna.richtext.IRichTextNavigator; import com.mindoo.domino.jna.richtext.IRichTextNavigator.RichTextNavPosition; import com.mindoo.domino.jna.richtext.RichTextBuilder; import com.mindoo.domino.jna.richtext.StandaloneRichText; import com.mindoo.domino.jna.richtext.conversion.IRichTextConversion; import com.mindoo.domino.jna.utils.LegacyAPIUtils; import com.mindoo.domino.jna.utils.NotesDateTimeUtils; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.PlatformUtils; import com.mindoo.domino.jna.utils.Ref; import com.mindoo.domino.jna.utils.StringUtil; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.StringArray; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.DoubleByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; import lotus.domino.Database; import lotus.domino.Document; import lotus.domino.NotesException; /** * Object wrapping a Notes document / note * * @author Karsten Lehmann */ public class NotesNote implements IRecyclableNotesObject { private int m_hNote32; private long m_hNote64; private boolean m_noRecycle; private NotesDatabase m_parentDb; private Document m_legacyDocRef; private EnumSet<NoteClass> m_noteClass; private boolean m_preferNotesTimeDates; /** * Creates a new instance * * @param parentDb parent database * @param hNote handle */ NotesNote(NotesDatabase parentDb, int hNote) { if (PlatformUtils.is64Bit()) throw new IllegalStateException("Constructor is 32bit only"); m_parentDb = parentDb; m_hNote32 = hNote; } /** * Creates a new instance * * @param parentDb parent database * @param hNote handle */ NotesNote(NotesDatabase parentDb, long hNote) { if (!PlatformUtils.is64Bit()) throw new IllegalStateException("Constructor is 64bit only"); m_parentDb = parentDb; m_hNote64 = hNote; } /** * Creates a new NotesNote * * @param adaptable adaptable providing enough information to create the database */ public NotesNote(IAdaptable adaptable) { Document legacyDoc = adaptable.getAdapter(Document.class); if (legacyDoc!=null) { if (isRecycled(legacyDoc)) throw new NotesError(0, "Legacy database already recycled"); long docHandle = LegacyAPIUtils.getDocHandle(legacyDoc); if (docHandle==0) throw new NotesError(0, "Could not read db handle"); if (PlatformUtils.is64Bit()) { m_hNote64 = docHandle; } else { m_hNote32 = (int) docHandle; } NotesGC.__objectCreated(NotesNote.class, this); setNoRecycle(); m_legacyDocRef = legacyDoc; Database legacyDb; try { legacyDb = legacyDoc.getParentDatabase(); } catch (NotesException e1) { throw new NotesError(0, "Could not read parent legacy db from document", e1); } long dbHandle = LegacyAPIUtils.getDBHandle(legacyDb); try { if (PlatformUtils.is64Bit()) { m_parentDb = (NotesDatabase) NotesGC.__b64_checkValidObjectHandle(NotesDatabase.class, dbHandle); } else { m_parentDb = (NotesDatabase) NotesGC.__b32_checkValidObjectHandle(NotesDatabase.class, (int) dbHandle); } } catch (NotesError e) { m_parentDb = LegacyAPIUtils.toNotesDatabase(legacyDb); } return; } if (PlatformUtils.is64Bit()) { CalNoteOpenData64 calOpenNote = adaptable.getAdapter(CalNoteOpenData64.class); if (calOpenNote!=null) { m_parentDb = calOpenNote.getDb(); m_hNote64 = calOpenNote.getNoteHandle(); return; } } else { CalNoteOpenData32 calOpenNote = adaptable.getAdapter(CalNoteOpenData32.class); if (calOpenNote!=null) { m_parentDb = calOpenNote.getDb(); m_hNote32 = calOpenNote.getNoteHandle(); return; } } throw new NotesError(0, "Unsupported adaptable parameter"); } private boolean isRecycled(Document doc) { try { //call any method to check recycled state doc.hasItem("~-~-~-~-~-~"); } catch (NotesException e) { if (e.id==4376 || e.id==4466) return true; } return false; } /** * Converts a legacy {@link lotus.domino.Document} to a * {@link NotesNote}. * * @param parentDb parent database * @param doc document to convert * @return note */ public static NotesNote toNote(NotesDatabase parentDb, Document doc) { long handle = LegacyAPIUtils.getDocHandle(doc); NotesNote note; if (PlatformUtils.is64Bit()) { note = new NotesNote(parentDb, handle); } else { note = new NotesNote(parentDb, (int) handle); } note.setNoRecycle(); return note; } /** * Converts this note to a legacy {@link Document} * * @param db parent database * @return document */ public Document toDocument(Database db) { if (PlatformUtils.is64Bit()) { return LegacyAPIUtils.createDocument(db, m_hNote64); } else { return LegacyAPIUtils.createDocument(db, m_hNote32); } } /** * Returns the parent database * * @return database */ public NotesDatabase getParent() { return m_parentDb; } /** * Returns the note id of the note * * @return note id */ public int getNoteId() { checkHandle(); Memory retNoteId = new Memory(4); retNoteId.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_ID, retNoteId); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_ID, retNoteId); } return retNoteId.getInt(0); } /** * Method to check whether a note has already been saved * * @return true if yet unsaved */ public boolean isNewNote() { return getNoteId() == 0; } /** * Returns the note class of the note * * @return note class */ public EnumSet<NoteClass> getNoteClass() { if (m_noteClass==null) { checkHandle(); Memory retNoteClass = new Memory(2); retNoteClass.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_CLASS, retNoteClass); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_CLASS, retNoteClass); } int noteClassMask = retNoteClass.getShort(0); m_noteClass = NoteClass.toNoteClasses(noteClassMask); } return m_noteClass; } /** * Converts the value of {@link #getNoteId()} to a hex string in uppercase * format * * @return note id as hex string */ public String getNoteIdAsString() { return Integer.toString(getNoteId(), 16).toUpperCase(); } @Override public String toString() { if (isRecycled()) { return "NotesNote [recycled]"; } else { return "NotesNote [handle="+(PlatformUtils.is64Bit() ? m_hNote64 : m_hNote32)+", noteid="+getNoteId()+"]"; } } /** * Returns the UNID of the note * * @return UNID */ public String getUNID() { NotesOriginatorIdStruct oid = getOIDStruct(); String unid = oid.getUNIDAsString(); return unid; } /** * Internal method to get the populated {@link NotesOriginatorIdStruct} object * for this note * * @return oid structure */ private NotesOriginatorIdStruct getOIDStruct() { checkHandle(); Memory retOid = new Memory(NotesConstants.oidSize); retOid.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_OID, retOid); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_OID, retOid); } NotesOriginatorIdStruct oidStruct = NotesOriginatorIdStruct.newInstance(retOid); oidStruct.read(); return oidStruct; } /** * Returns the {@link NotesOriginatorId} for this note * * @return oid */ public NotesOriginatorId getOID() { NotesOriginatorIdStruct oidStruct = getOIDStruct(); NotesOriginatorId oid = new NotesOriginatorId(oidStruct); return oid; } /** * Sets a new UNID in the {@link NotesOriginatorId} for this note * * @param newUnid new universal id */ public void setUNID(String newUnid) { checkHandle(); Memory retOid = new Memory(NotesConstants.oidSize); retOid.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_OID, retOid); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_OID, retOid); } NotesOriginatorIdStruct oidStruct = NotesOriginatorIdStruct.newInstance(retOid); oidStruct.read(); oidStruct.setUNID(newUnid); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteSetInfo(m_hNote64, NotesConstants._NOTE_OID, retOid); } else { NotesNativeAPI32.get().NSFNoteSetInfo(m_hNote32, NotesConstants._NOTE_OID, retOid); } } /** * Returns the last modified date of the note * * @return last modified date */ public Calendar getLastModified() { checkHandle(); Memory retModified = new Memory(NotesConstants.timeDateSize); retModified.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_MODIFIED, retModified); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_MODIFIED, retModified); } NotesTimeDateStruct td = NotesTimeDateStruct.newInstance(retModified); td.read(); Calendar cal = td.toCalendar(); return cal; } /** * Returns the creation date of this note * * @return creation date */ public Calendar getCreationDate() { checkHandle(); Calendar creationDate = getItemValueDateTime("$CREATED"); if (creationDate!=null) { return creationDate; } NotesOriginatorIdStruct oidStruct = getOIDStruct(); NotesTimeDateStruct creationDateStruct = oidStruct.Note; return creationDateStruct.toCalendar(); } /** * Returns the creation date of this note * * @return creation date as {@link NotesTimeDate} */ public NotesTimeDate getCreationDateAsTimeDate() { checkHandle(); NotesTimeDate creationDate = getItemValueAsTimeDate("$CREATED"); if (creationDate!=null) { return creationDate; } NotesOriginatorIdStruct oidStruct = getOIDStruct(); NotesTimeDateStruct creationDateStruct = oidStruct.Note; return new NotesTimeDate(creationDateStruct.Innards); } /** * Returns the last access date of the note * * @return last access date */ public Calendar getLastAccessed() { checkHandle(); Memory retModified = new Memory(NotesConstants.timeDateSize); retModified.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_ACCESSED, retModified); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_ACCESSED, retModified); } NotesTimeDateStruct td = NotesTimeDateStruct.newInstance(retModified); td.read(); Calendar cal = td.toCalendar(); return cal; } /** * Returns the last access date of the note * * @return last access date */ public Calendar getAddedToFileTime() { checkHandle(); Memory retModified = new Memory(NotesConstants.timeDateSize); retModified.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_ADDED_TO_FILE, retModified); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_ADDED_TO_FILE, retModified); } NotesTimeDateStruct td = NotesTimeDateStruct.newInstance(retModified); td.read(); Calendar cal = td.toCalendar(); return cal; } /** * The NOTE_FLAG_READONLY bit indicates that the note is Read-Only for the current user.<br> * If a note contains an author names field, and the name of the user opening the * document is not included in the author names field list, then the NOTE_FLAG_READONLY * bit is set in the note header data when that user opens the note. * * @return TRUE if document cannot be updated */ public boolean isReadOnly() { int flags = getFlags(); return (flags & NotesConstants.NOTE_FLAG_READONLY) == NotesConstants.NOTE_FLAG_READONLY; } /** * The NOTE_FLAG_ABSTRACTED bit indicates that the note has been abstracted (truncated).<br> * This bit may be set if the database containing the note has replication settings set to * "Truncate large documents and remove attachments". * * @return true if truncated */ public boolean isTruncated() { int flags = getFlags(); return (flags & NotesConstants.NOTE_FLAG_ABSTRACTED) == NotesConstants.NOTE_FLAG_ABSTRACTED; } /** * Examines the items in the note and determines if they are correctly formed. * * @throws NotesError if items contain errors like the overall lengths does not match the data type ({@link INotesErrorConstants#ERR_INVALID_ITEMLEN}) or an item's type is not recognized ({@link INotesErrorConstants#ERR_INVALID_ITEMTYPE}) */ public void check() { checkHandle(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteCheck(getHandle64()); } else { result = NotesNativeAPI32.get().NSFNoteCheck(getHandle32()); } NotesErrorUtils.checkResult(result); } /** * Reads the note flags (e.g. {@link NotesConstants#NOTE_FLAG_READONLY}) * * @return flags */ private short getFlags() { checkHandle(); Memory retFlags = new Memory(2); retFlags.clear(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteGetInfo(m_hNote64, NotesConstants._NOTE_FLAGS, retFlags); } else { NotesNativeAPI32.get().NSFNoteGetInfo(m_hNote32, NotesConstants._NOTE_FLAGS, retFlags); } short flags = retFlags.getShort(0); return flags; } public void setNoRecycle() { m_noRecycle=true; } @Override public boolean isNoRecycle() { return m_noRecycle; } @Override public void recycle() { if (m_noRecycle || isRecycled()) return; short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteClose(m_hNote64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(NotesNote.class, this); m_hNote64=0; DisposableMemory retStrBufMem = stringretBuffer.get(); if (retStrBufMem!=null) { if (!retStrBufMem.isDisposed()) { retStrBufMem.dispose(); } stringretBuffer.set(null); } } else { result = NotesNativeAPI32.get().NSFNoteClose(m_hNote32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(NotesNote.class, this); m_hNote32=0; DisposableMemory retStrBufMem = stringretBuffer.get(); if (retStrBufMem!=null) { if (!retStrBufMem.isDisposed()) { retStrBufMem.dispose(); } stringretBuffer.set(null); } } } @Override public boolean isRecycled() { if (PlatformUtils.is64Bit()) { return m_hNote64==0; } else { return m_hNote32==0; } } @Override public int getHandle32() { return m_hNote32; } @Override public long getHandle64() { return m_hNote64; } void checkHandle() { if (m_legacyDocRef!=null && isRecycled(m_legacyDocRef)) throw new NotesError(0, "Wrapped legacy document already recycled"); if (PlatformUtils.is64Bit()) { if (m_hNote64==0) throw new NotesError(0, "Note already recycled"); NotesGC.__b64_checkValidObjectHandle(NotesNote.class, m_hNote64); } else { if (m_hNote32==0) throw new NotesError(0, "Note already recycled"); NotesGC.__b32_checkValidObjectHandle(NotesNote.class, m_hNote32); } } /** * Unsigns the note. This function removes the $Signature item from the note. */ public void unsign() { checkHandle(); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NSFNoteUnsign(m_hNote64); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NSFNoteUnsign(m_hNote32); NotesErrorUtils.checkResult(result); } } /** * This function writes the in-memory version of a note to its database.<br> * <br> * Prior to issuing this call, a new note (or changes to a note) are not a part * of the on-disk database.<br> * <br> * This function allows using extended 32-bit DWORD update options, as described * in the entry {@link UpdateNote}.<br> * <br> * You should also consider updating the collections associated with other Views * in a database via the function {@link NotesCollection#update()}, * if you have added and/or deleted a substantial number of documents.<br> * <br> * If the Server's Indexer Task does not rebuild the collections associated with the database's Views, * the first user to access a View in the modified database might experience an inordinant * delay, while the collection is rebuilt by the Notes Workstation (locally) or * Server Application (remotely). * @param updateFlags flags */ public void update(EnumSet<UpdateNote> updateFlags) { checkHandle(); int updateFlagsBitmask = UpdateNote.toBitMaskForUpdateExt(updateFlags); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NSFNoteUpdateExtended(m_hNote64, updateFlagsBitmask); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NSFNoteUpdateExtended(m_hNote32, updateFlagsBitmask); NotesErrorUtils.checkResult(result); } } /** * This function writes the in-memory version of a note to its database.<br> * Prior to issuing this call, a new note (or changes to a note) are not a part of * the on-disk database.<br> * <br> * You should also consider updating the collections associated with other Views in a database * via the function * {@link NotesCollection#update()}, if you have added and/or deleted a substantial number of documents.<br> * If the Server's Indexer Task does not rebuild the collections associated with * the database's Views, the first user to access a View in the modified database * might experience an inordinant delay, while the collection is rebuilt by the * Notes Workstation (locally) or Server Application (remotely).<br> * <br> * Do not update notes to disk that contain invalid items.<br> * An example of an invalid item is a view design note that has a $Collation item * whose BufferSize member is set to zero.<br> * This update method may return an error for an invalid item that was not caught * in a previous release of Domino or Notes.<br> * Note: if you have enabled IMAP on a database, in the case of the * special NoteID "NOTEID_ADD_OR_REPLACE", a new note is always created. * */ public void update() { update(EnumSet.noneOf(UpdateNote.class)); } /** * The method checks whether an item exists * * @param itemName item name * @return true if the item exists */ public boolean hasItem(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFItemInfo(m_hNote64, itemNameMem, (short) (itemNameMem.size() & 0xffff), null, null, null, null); } else { result = NotesNativeAPI32.get().NSFItemInfo(m_hNote32, itemNameMem, (short) (itemNameMem.size() & 0xffff), null, null, null, null); } return result == 0; } /** * The function NSFNoteHasComposite returns TRUE if the given note contains any TYPE_COMPOSITE items. * * @return true if composite */ public boolean hasComposite() { checkHandle(); if (PlatformUtils.is64Bit()) { return NotesNativeAPI64.get().NSFNoteHasComposite(m_hNote64) == 1; } else { return NotesNativeAPI32.get().NSFNoteHasComposite(m_hNote32) == 1; } } /** * The function NSFNoteHasMIME returns TRUE if the given note contains either TYPE_RFC822_TEXT * items or TYPE_MIME_PART items. * * @return true if mime */ public boolean hasMIME() { checkHandle(); if (PlatformUtils.is64Bit()) { return NotesNativeAPI64.get().NSFNoteHasMIME(m_hNote64) == 1; } else { return NotesNativeAPI32.get().NSFNoteHasMIME(m_hNote32) == 1; } } /** * The function returns TRUE if the given note contains any {@link NotesItem#TYPE_MIME_PART} items. * * @return true if mime part */ public boolean hasMIMEPart() { checkHandle(); if (PlatformUtils.is64Bit()) { return NotesNativeAPI64.get().NSFNoteHasMIMEPart(m_hNote64) == 1; } else { return NotesNativeAPI32.get().NSFNoteHasMIMEPart(m_hNote32) == 1; } } /** * The function returns TRUE if the given note contains any items with reader access flag * * @return true if readers field */ public boolean hasReadersField() { checkHandle(); NotesBlockIdStruct blockId = NotesBlockIdStruct.newInstance(); boolean hasReaders; //use an optimized call to search for reader fields if (PlatformUtils.is64Bit()) { hasReaders = NotesNativeAPI64.get().NSFNoteHasReadersField(m_hNote64, blockId) == 1; } else { hasReaders = NotesNativeAPI32.get().NSFNoteHasReadersField(m_hNote32, blockId) == 1; } return hasReaders; } /** * The function returns all the readers items of the note * * @return array with readers fields */ public List<NotesItem> getReadersFields() { checkHandle(); NotesBlockIdStruct blockId = NotesBlockIdStruct.newInstance(); boolean hasReaders; //use an optimized call to find the first readers field if (PlatformUtils.is64Bit()) { hasReaders = NotesNativeAPI64.get().NSFNoteHasReadersField(m_hNote64, blockId) == 1; } else { hasReaders = NotesNativeAPI32.get().NSFNoteHasReadersField(m_hNote32, blockId) == 1; } if (!hasReaders) return Collections.emptyList(); List<NotesItem> readerFields = new ArrayList<NotesItem>(); NotesBlockIdStruct.ByValue itemBlockIdByVal = NotesBlockIdStruct.ByValue.newInstance(); itemBlockIdByVal.pool = blockId.pool; itemBlockIdByVal.block = blockId.block; ByteByReference retSeqByte = new ByteByReference(); ByteByReference retDupItemID = new ByteByReference(); Memory item_name = new Memory(NotesConstants.MAXUSERNAME); ShortByReference retName_len = new ShortByReference(); ShortByReference retItem_flags = new ShortByReference(); ShortByReference retDataType = new ShortByReference(); IntByReference retValueLen = new IntByReference(); NotesBlockIdStruct retValueBid = NotesBlockIdStruct.newInstance(); short result; if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFItemQueryEx(m_hNote64, itemBlockIdByVal, item_name, (short) (item_name.size() & 0xffff), retName_len, retItem_flags, retDataType, retValueBid, retValueLen, retSeqByte, retDupItemID); } else { NotesNativeAPI32.get().NSFItemQueryEx(m_hNote32, itemBlockIdByVal, item_name, (short) (item_name.size() & 0xffff), retName_len, retItem_flags, retDataType, retValueBid, retValueLen, retSeqByte, retDupItemID); } NotesBlockIdStruct itemBlockIdForItemCreation = NotesBlockIdStruct.newInstance(); itemBlockIdForItemCreation.pool = itemBlockIdByVal.pool; itemBlockIdForItemCreation.block = itemBlockIdByVal.block; itemBlockIdForItemCreation.write(); if ((retItem_flags.getValue() & NotesConstants.ITEM_READERS) == NotesConstants.ITEM_READERS) { NotesItem firstItem = new NotesItem(this, itemBlockIdForItemCreation, (int) (retDataType.getValue() & 0xffff), retValueBid); readerFields.add(firstItem); } //now search for more items with readers flag while (true) { IntByReference retNextValueLen = new IntByReference(); NotesBlockIdStruct retItemBlockId = NotesBlockIdStruct.newInstance(); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFItemInfoNext(m_hNote64, itemBlockIdByVal, null, (short) 0, retItemBlockId, retDataType, retValueBid, retNextValueLen); } else { result = NotesNativeAPI32.get().NSFItemInfoNext(m_hNote32, itemBlockIdByVal, null, (short) 0, retItemBlockId, retDataType, retValueBid, retNextValueLen); } if (result == INotesErrorConstants.ERR_ITEM_NOT_FOUND) { return readerFields; } NotesErrorUtils.checkResult(result); itemBlockIdForItemCreation = NotesBlockIdStruct.newInstance(); itemBlockIdForItemCreation.pool = retItemBlockId.pool; itemBlockIdForItemCreation.block = retItemBlockId.block; itemBlockIdForItemCreation.write(); NotesBlockIdStruct valueBlockIdClone = NotesBlockIdStruct.newInstance(); valueBlockIdClone.pool = retValueBid.pool; valueBlockIdClone.block = retValueBid.block; valueBlockIdClone.write(); short dataType = retDataType.getValue(); NotesItem newItem = new NotesItem(this, itemBlockIdForItemCreation, dataType, valueBlockIdClone); if (newItem.isReaders()) { readerFields.add(newItem); } itemBlockIdByVal.pool = retItemBlockId.pool; itemBlockIdByVal.block = retItemBlockId.block; itemBlockIdByVal.write(); } } /** * This function deletes this note from the specified database with default flags (0).<br> * <br> * This function allows using extended 32-bit DWORD update options, as described in the entry {@link UpdateNote}.<br> * <br> * It deletes the specified note by updating it with a nil body, and marking the note as a deletion stub.<br> * The deletion stub identifies the deleted note to other replica copies of the database.<br> * This allows the replicator to delete copies of the note from replica databases. * <br> * The deleted note may be of any NOTE_CLASS_xxx. The active user ID must have sufficient user access * in the databases's Access Control List (ACL) to carry out a deletion on the note or the function * will return an error code. */ public void delete() { delete(EnumSet.noneOf(UpdateNote.class)); } /** * This function deletes this note from the specified database.<br> * <br> * This function allows using extended 32-bit DWORD update options, as described in the entry {@link UpdateNote}.<br> * <br> * It deletes the specified note by updating it with a nil body, and marking the note as a deletion stub.<br> * The deletion stub identifies the deleted note to other replica copies of the database.<br> * This allows the replicator to delete copies of the note from replica databases. * <br> * The deleted note may be of any NOTE_CLASS_xxx. The active user ID must have sufficient user access * in the databases's Access Control List (ACL) to carry out a deletion on the note or the function * will return an error code. * * @param flags flags */ public void delete(EnumSet<UpdateNote> flags) { checkHandle(); if (m_parentDb.isRecycled()) throw new NotesError(0, "Parent database already recycled"); int flagsAsInt = UpdateNote.toBitMaskForUpdateExt(flags); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteDeleteExtended(m_parentDb.getHandle64(), getNoteId(), flagsAsInt); } else { result = NotesNativeAPI32.get().NSFNoteDeleteExtended(m_parentDb.getHandle32(), getNoteId(), flagsAsInt); } NotesErrorUtils.checkResult(result); } /** * Method to remove an item from a note * * @param itemName item name */ public void removeItem(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFItemDelete(m_hNote64, itemNameMem, (short) (itemNameMem.size() & 0xffff)); } else { result = NotesNativeAPI32.get().NSFItemDelete(m_hNote32, itemNameMem, (short) (itemNameMem.size() & 0xffff)); } if (result==INotesErrorConstants.ERR_ITEM_NOT_FOUND) { return; } NotesErrorUtils.checkResult(result); } /** default size of return buffer for operations returning strings like NSFItemGetText */ private final int DEFAULT_STRINGRETVALUE_LENGTH = 16384; /** max size of return buffer for operations returning strings like NSFItemGetText */ private final int MAX_STRINGRETVALUE_LENGTH = 65535; private ThreadLocal<DisposableMemory> stringretBuffer = new ThreadLocal<DisposableMemory>(); /** * Use this function to read the value of a text item.<br> * <br> * If the item does not exist, the method returns an empty string. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return text value */ public String getItemValueString(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); DisposableMemory retItemValueMem = stringretBuffer.get(); if (retItemValueMem==null || retItemValueMem.isDisposed()) { retItemValueMem = new DisposableMemory(DEFAULT_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); } short length; if (PlatformUtils.is64Bit()) { length = NotesNativeAPI64.get().NSFItemGetText(m_hNote64, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); if (length == (retItemValueMem.size()-1)) { retItemValueMem.dispose(); retItemValueMem = new DisposableMemory(MAX_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); length = NotesNativeAPI64.get().NSFItemGetText(m_hNote64, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); } } else { length = NotesNativeAPI32.get().NSFItemGetText(m_hNote32, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); if (length == (retItemValueMem.size()-1)) { retItemValueMem.dispose(); retItemValueMem = new DisposableMemory(MAX_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); length = NotesNativeAPI32.get().NSFItemGetText(m_hNote32, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); } } int lengthAsInt = (int) length & 0xffff; if (lengthAsInt==0) { return ""; } String strVal = NotesStringUtils.fromLMBCS(retItemValueMem, lengthAsInt); return strVal; } /** * This function writes an item of type TEXT to the note.<br> * If an item of that name already exists, it deletes the existing item first, * then appends the new item.<br> * <br> * Note 1: Use \n as line break in your string. The method internally converts these line breaks * to null characters ('\0'), because that's what the Notes API expects as line break delimiter.<br> * <br> * Note 2: If the Summary parameter of is set to TRUE, the ITEM_SUMMARY flag in the item will be set. * Items with the ITEM_SUMMARY flag set are stored in the note's summary buffer. These items may * be used in view columns, selection formulas, and @-functions. The maximum size of the summary * buffer is 32K per note.<br> * If you append more than 32K bytes of data in items that have the ITEM_SUMMARY flag set, * this method call will succeed, but {@link #update(EnumSet)} will return ERR_SUMMARY_TOO_BIG (ERR 561). * To avoid this, decide which fields are not used in view columns, selection formulas, * or @-functions. For these "non-computed" fields, use this method with the Summary parameter set to FALSE.<br> * <br> * API program may read, modify, and write items that do not have the summary flag set, but they * must open the note first. Items that do not have the summary flag set can not be accessed * in the summary buffer.<br> * * @param itemName item name * @param itemValue item value * @param isSummary true to set summary flag */ public void setItemValueString(String itemName, String itemValue, boolean isSummary) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); Memory itemValueMem = NotesStringUtils.toLMBCS(itemValue, false); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NSFItemSetTextSummary(m_hNote64, itemNameMem, itemValueMem, itemValueMem==null ? 0 : ((short) (itemValueMem.size() & 0xffff)), isSummary); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NSFItemSetTextSummary(m_hNote32, itemNameMem, itemValueMem, itemValueMem==null ? 0 : ((short) (itemValueMem.size() & 0xffff)), isSummary); NotesErrorUtils.checkResult(result); } } /** * This function writes a number to an item in the note. * * @param itemName item name * @param value new value */ public void setItemValueDouble(String itemName, double value) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); Memory doubleMem = new Memory(Native.getNativeSize(Double.TYPE)); doubleMem.setDouble(0, value); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NSFItemSetNumber(m_hNote64, itemNameMem, doubleMem); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NSFItemSetNumber(m_hNote32, itemNameMem, doubleMem); NotesErrorUtils.checkResult(result); } } /** * Writes a {@link Calendar} value in an item * * @param itemName item name * @param cal new value */ public void setItemValueDateTime(String itemName, Calendar cal) { if (cal==null) { removeItem(itemName); return; } checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); NotesTimeDate timeDate = NotesDateTimeUtils.calendarToTimeDate(cal); NotesTimeDateStruct timeDateStruct = timeDate==null ? null : NotesTimeDateStruct.newInstance(timeDate.getInnards()); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NSFItemSetTime(m_hNote64, itemNameMem, timeDateStruct); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NSFItemSetTime(m_hNote32, itemNameMem, timeDateStruct); NotesErrorUtils.checkResult(result); } } /** * Writes a {@link Date} value in an item * * @param itemName item name * @param dt new value * @param hasDate true to save the date of the specified {@link Date} object * @param hasTime true to save the time of the specified {@link Date} object */ public void setItemValueDateTime(String itemName, Date dt, boolean hasDate, boolean hasTime) { if (dt==null) { removeItem(itemName); return; } Calendar cal = Calendar.getInstance(); cal.setTime(dt); if (!hasDate) { NotesDateTimeUtils.setAnyDate(cal); } if (!hasTime) { NotesDateTimeUtils.setAnyTime(cal); } setItemValueDateTime(itemName, cal); } /** * Reads the value of a text list item * * @param itemName item name * @return list of strings; empty if item does not exist */ public List<String> getItemValueStringList(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); short nrOfValues; if (PlatformUtils.is64Bit()) { nrOfValues = NotesNativeAPI64.get().NSFItemGetTextListEntries(m_hNote64, itemNameMem); } else { nrOfValues = NotesNativeAPI32.get().NSFItemGetTextListEntries(m_hNote32, itemNameMem); } int nrOfValuesAsInt = (int) (nrOfValues & 0xffff); if (nrOfValuesAsInt==0) { return Collections.emptyList(); } List<String> strList = new ArrayList<String>(nrOfValuesAsInt); DisposableMemory retItemValueMem = stringretBuffer.get(); if (retItemValueMem==null || retItemValueMem.isDisposed()) { retItemValueMem = new DisposableMemory(DEFAULT_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); } for (int i=0; i<nrOfValuesAsInt; i++) { short length; if (PlatformUtils.is64Bit()) { length = NotesNativeAPI64.get().NSFItemGetTextListEntry(m_hNote64, itemNameMem, (short) (i & 0xffff), retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); if (length == (retItemValueMem.size()-1)) { retItemValueMem.dispose(); retItemValueMem = new DisposableMemory(MAX_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); length = NotesNativeAPI64.get().NSFItemGetTextListEntry(m_hNote64, itemNameMem, (short) (i & 0xffff), retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); } } else { length = NotesNativeAPI32.get().NSFItemGetTextListEntry(m_hNote32, itemNameMem, (short) (i & 0xffff), retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); if (length == (retItemValueMem.size()-1)) { retItemValueMem.dispose(); retItemValueMem = new DisposableMemory(MAX_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); length = NotesNativeAPI32.get().NSFItemGetTextListEntry(m_hNote32, itemNameMem, (short) (i & 0xffff), retItemValueMem, (short) (retItemValueMem.size() & 0xffff)); } } int lengthAsInt = (int) length & 0xffff; if (lengthAsInt==0) { strList.add(""); } String strVal = NotesStringUtils.fromLMBCS(retItemValueMem, lengthAsInt); strList.add(strVal); } return strList; } /** * This is a very powerful function that converts many kinds of Domino fields (items) into * text strings.<br> * * If there is more than one item with the same name, this function will always return the first of these. * This function, therefore, is not useful if you want to retrieve multiple instances of the same * field name. For these situations, use NSFItemConvertValueToText.<br> * <br> * The item value may be any one of these supported Domino data types:<br> * <ul> * <li>TYPE_TEXT - Text is returned unmodified.</li> * <li>TYPE_TEXT_LIST - A text list items will merged into a single text string, with the separator between them.</li> * <li>TYPE_NUMBER - the FLOAT number will be converted to text.</li> * <li>TYPE_NUMBER_RANGE -- the FLOAT numbers will be converted to text, with the separator between them.</li> * <li>TYPE_TIME - the binary Time/Date will be converted to text.</li> * <li>TYPE_TIME_RANGE -- the binary Time/Date values will be converted to text, with the separator between them.</li> * <li>TYPE_COMPOSITE - The text portion of the rich text field will be returned.</li> * <li>TYPE_USERID - The user name portion will be converted to text.</li> * <li>TYPE_ERROR - the binary Error value will be converted to "ERROR: ".</li> * <li>TYPE_UNAVAILABLE - the binary Unavailable value will be converted to "UNAVAILABLE: ".</li> * </ul> * * @param itemName item name * @param multiValueDelimiter delimiter character for value lists; should be an ASCII character, since no encoding is done * @return string value */ public String getItemValueAsText(String itemName, char multiValueDelimiter) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); DisposableMemory retItemValueMem = stringretBuffer.get(); if (retItemValueMem==null || retItemValueMem.isDisposed()) { retItemValueMem = new DisposableMemory(DEFAULT_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); } short length; if (PlatformUtils.is64Bit()) { length = NotesNativeAPI64.get().NSFItemConvertToText(m_hNote64, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff), multiValueDelimiter); if (length == (retItemValueMem.size()-1)) { retItemValueMem.dispose(); retItemValueMem = new DisposableMemory(MAX_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); length = NotesNativeAPI64.get().NSFItemConvertToText(m_hNote64, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff), multiValueDelimiter); } } else { length = NotesNativeAPI32.get().NSFItemConvertToText(m_hNote32, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff), multiValueDelimiter); if (length == (retItemValueMem.size()-1)) { retItemValueMem.dispose(); retItemValueMem = new DisposableMemory(MAX_STRINGRETVALUE_LENGTH); stringretBuffer.set(retItemValueMem); length = NotesNativeAPI32.get().NSFItemConvertToText(m_hNote32, itemNameMem, retItemValueMem, (short) (retItemValueMem.size() & 0xffff), multiValueDelimiter); } } int lengthAsInt = (int) length & 0xffff; if (lengthAsInt==0) { return ""; } String strVal = NotesStringUtils.fromLMBCS(retItemValueMem, lengthAsInt); return strVal; } /** * Use this function to read the value of a number item as double.<br> * <br> * If the item does not exist, the method returns 0. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return double value */ public double getItemValueDouble(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); DoubleByReference retNumber = new DoubleByReference(); if (PlatformUtils.is64Bit()) { boolean exists = NotesNativeAPI64.get().NSFItemGetNumber(m_hNote64, itemNameMem, retNumber); if (!exists) { return 0; } } else { boolean exists = NotesNativeAPI32.get().NSFItemGetNumber(m_hNote32, itemNameMem, retNumber); if (!exists) { return 0; } } return retNumber.getValue(); } /** * Use this function to read the value of a number item as long.<br> * <br> * If the item does not exist, the method returns 0. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return long value */ public long getItemValueLong(String itemName) { List<?> values = getItemValue(itemName); if (values.size()==0) return 0; Object firstVal = values.get(0); if (firstVal instanceof Number) { return ((Number)firstVal).longValue(); } return 0; } /** * Use this function to read the value of a number item as integer.<br> * <br> * If the item does not exist, the method returns 0. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return int value */ public int getItemValueInteger(String itemName) { List<?> values = getItemValue(itemName); if (values.size()==0) return 0; Object firstVal = values.get(0); if (firstVal instanceof Number) { return ((Number)firstVal).intValue(); } return 0; } /** * Use this function to read the value of a timedate item as {@link Calendar}.<br> * <br> * If the item does not exist, the method returns null. * * @param itemName item name * @return time date value or null */ public Calendar getItemValueDateTime(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); NotesTimeDateStruct td_item_value = NotesTimeDateStruct.newInstance(); if (PlatformUtils.is64Bit()) { boolean exists = NotesNativeAPI64.get().NSFItemGetTime(m_hNote64, itemNameMem, td_item_value); if (!exists) { return null; } } else { boolean exists = NotesNativeAPI32.get().NSFItemGetTime(m_hNote32, itemNameMem, td_item_value); if (!exists) { return null; } } return td_item_value.toCalendar(); } /** * Use this function to read the value of a timedate item as {@link NotesTimeDate}.<br> * <br> * If the item does not exist, the method returns null. * * @param itemName item name * @return time date value or null if not found */ public NotesTimeDate getItemValueAsTimeDate(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); NotesTimeDateStruct td_item_value = NotesTimeDateStruct.newInstance(); if (PlatformUtils.is64Bit()) { boolean exists = NotesNativeAPI64.get().NSFItemGetTime(m_hNote64, itemNameMem, td_item_value); if (!exists) { return null; } } else { boolean exists = NotesNativeAPI32.get().NSFItemGetTime(m_hNote32, itemNameMem, td_item_value); if (!exists) { return null; } } td_item_value.read(); int[] innards = td_item_value.Innards; return new NotesTimeDate(innards); } /** * Decodes an item value * * @param itemName item name (for logging purpose) * @param valueBlockId value block id * @param valueLength item value length plus 2 bytes for the data type WORD * @return item value as list */ List<Object> getItemValue(String itemName, NotesBlockIdStruct itemBlockId, NotesBlockIdStruct valueBlockId, int valueLength) { Pointer poolPtr; if (PlatformUtils.is64Bit()) { poolPtr = Mem64.OSLockObject((long) valueBlockId.pool); } else { poolPtr = Mem32.OSLockObject(valueBlockId.pool); } int block = (valueBlockId.block & 0xffff); long poolPtrLong = Pointer.nativeValue(poolPtr) + block; Pointer valuePtr = new Pointer(poolPtrLong); try { List<Object> values = getItemValue(itemName, itemBlockId, valuePtr, valueLength); return values; } finally { if (PlatformUtils.is64Bit()) { Mem64.OSUnlockObject((long) valueBlockId.pool); } else { Mem32.OSUnlockObject(valueBlockId.pool); } } } /** * Sets whether methods like {@link #getItemValue(String)} should return {@link NotesTimeDate} * instead of {@link Calendar}. * * @param b true to prefer NotesTimeDate (false by default) */ public void setPreferNotesTimeDates(boolean b) { m_preferNotesTimeDates = b; } /** * Returns whether methods like {@link #getItemValue(String)} should return {@link NotesTimeDate} * instead of {@link Calendar}. * * @return true to prefer NotesTimeDate */ public boolean isPreferNotesTimeDates() { return m_preferNotesTimeDates; } /** * Decodes an item value * * @param notesAPI Notes API * @param itemName item name (for logging purpose) * @param NotesBlockIdStruct itemBlockId item block id * @param valuePtr pointer to the item value * @param valueLength item value length plus 2 bytes for the data type WORD * @return item value as list */ List<Object> getItemValue(String itemName, NotesBlockIdStruct itemBlockId, Pointer valuePtr, int valueLength) { short dataType = valuePtr.getShort(0); int dataTypeAsInt = (int) (dataType & 0xffff); boolean supportedType = false; if (dataTypeAsInt == NotesItem.TYPE_TEXT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_OBJECT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NOTEREF_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_COLLATION) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_VIEW_FORMAT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_FORMULA) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { supportedType = true; } if (!supportedType) { throw new UnsupportedItemValueError("Data type for value of item "+itemName+" is currently unsupported: "+dataTypeAsInt); } int checkDataType = valuePtr.getShort(0) & 0xffff; Pointer valueDataPtr = valuePtr.share(2); int valueDataLength = valueLength - 2; if (checkDataType!=dataTypeAsInt) { throw new IllegalStateException("Value data type does not meet expected date type: found "+checkDataType+", expected "+dataTypeAsInt); } if (dataTypeAsInt == NotesItem.TYPE_TEXT) { String txtVal = (String) ItemDecoder.decodeTextValue(valueDataPtr, valueDataLength, false); return txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal); } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { List<Object> textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(valueDataPtr, false); return textList==null ? Collections.emptyList() : textList; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { double numVal = ItemDecoder.decodeNumber(valueDataPtr, valueDataLength); return Arrays.asList((Object) Double.valueOf(numVal)); } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { List<Object> numberList = ItemDecoder.decodeNumberList(valueDataPtr, valueDataLength); return numberList==null ? Collections.emptyList() : numberList; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { if (isPreferNotesTimeDates()) { NotesTimeDate td = ItemDecoder.decodeTimeDateAsNotesTimeDate(valueDataPtr, valueDataLength); return Arrays.asList((Object) td); } else { Calendar cal = ItemDecoder.decodeTimeDate(valueDataPtr, valueDataLength); if (cal==null) { Calendar nullCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); nullCal.set(Calendar.YEAR, 1); nullCal.set(Calendar.MONTH, 1); nullCal.set(Calendar.DAY_OF_MONTH, 1); nullCal.set(Calendar.HOUR, 0); nullCal.set(Calendar.MINUTE, 0); nullCal.set(Calendar.SECOND, 0); nullCal.set(Calendar.MILLISECOND, 0); return Arrays.asList((Object) nullCal); } else { return Arrays.asList((Object) cal); } } } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { if (isPreferNotesTimeDates()) { List<Object> tdValues = ItemDecoder.decodeTimeDateListAsNotesTimeDate(valueDataPtr); return tdValues==null ? Collections.emptyList() : tdValues; } else { List<Object> calendarValues = ItemDecoder.decodeTimeDateList(valueDataPtr); return calendarValues==null ? Collections.emptyList() : calendarValues; } } else if (dataTypeAsInt == NotesItem.TYPE_OBJECT) { NotesObjectDescriptorStruct objDescriptor = NotesObjectDescriptorStruct.newInstance(valueDataPtr); objDescriptor.read(); int rrv = objDescriptor.RRV; if (objDescriptor.ObjectType == NotesConstants.OBJECT_FILE) { Pointer fileObjectPtr = valueDataPtr; NotesFileObjectStruct fileObject = NotesFileObjectStruct.newInstance(fileObjectPtr); fileObject.read(); short compressionType = fileObject.CompressionType; NotesTimeDateStruct fileCreated = fileObject.FileCreated; NotesTimeDateStruct fileModified = fileObject.FileModified; NotesTimeDate fileCreatedWrap = fileCreated==null ? null : new NotesTimeDate(fileCreated.Innards); NotesTimeDate fileModifiedWrap = fileModified==null ? null : new NotesTimeDate(fileModified.Innards); short fileNameLength = fileObject.FileNameLength; int fileSize = fileObject.FileSize; short flags = fileObject.Flags; Compression compression = null; for (Compression currComp : Compression.values()) { if (compressionType == currComp.getValue()) { compression = currComp; break; } } Pointer fileNamePtr = fileObjectPtr.share(NotesConstants.fileObjectSize); String fileName = NotesStringUtils.fromLMBCS(fileNamePtr, fileNameLength); NotesAttachment attInfo = new NotesAttachment(fileName, compression, flags, fileSize, fileCreatedWrap, fileModifiedWrap, this, itemBlockId, rrv); return Arrays.asList((Object) attInfo); } //TODO add support for other object types //clone values because value data gets unlocked, preventing invalid memory access NotesObjectDescriptorStruct clonedObjDescriptor = NotesObjectDescriptorStruct.newInstance(); clonedObjDescriptor.ObjectType = objDescriptor.ObjectType; clonedObjDescriptor.RRV = objDescriptor.RRV; return Arrays.asList((Object) clonedObjDescriptor); } else if (dataTypeAsInt == NotesItem.TYPE_NOTEREF_LIST) { //skip LIST structure, clone data to prevent invalid memory access when buffer gets disposed byte[] unidBytes = valueDataPtr.share(2).getByteArray(0, NotesConstants.notesUniversalNoteIdSize); Memory unidMem = new Memory(NotesConstants.notesUniversalNoteIdSize); unidMem.write(0, unidBytes, 0, unidBytes.length); NotesUniversalNoteIdStruct unidStruct = NotesUniversalNoteIdStruct.newInstance(unidMem); NotesUniversalNoteId unid = new NotesUniversalNoteId(unidStruct); return Arrays.asList((Object) unid); } else if (dataTypeAsInt == NotesItem.TYPE_COLLATION) { NotesCollationInfo colInfo = CollationDecoder.decodeCollation(valueDataPtr); return Arrays.asList((Object) colInfo); } else if (dataTypeAsInt == NotesItem.TYPE_VIEW_FORMAT) { NotesViewFormat viewFormatInfo = ViewFormatDecoder.decodeViewFormat(valueDataPtr, valueDataLength); return Arrays.asList((Object) viewFormatInfo); } else if (dataTypeAsInt == NotesItem.TYPE_FORMULA) { boolean isSelectionFormula = "$FORMULA".equalsIgnoreCase(itemName) && getNoteClass().contains(NoteClass.VIEW); if (PlatformUtils.is64Bit()) { LongByReference rethFormulaText = new LongByReference(); ShortByReference retFormulaTextLength = new ShortByReference(); short result = NotesNativeAPI64.get().NSFFormulaDecompile(valueDataPtr, isSelectionFormula, rethFormulaText, retFormulaTextLength); NotesErrorUtils.checkResult(result); Pointer formulaPtr = Mem64.OSLockObject(rethFormulaText.getValue()); try { int textLen = (int) (retFormulaTextLength.getValue() & 0xffff); String formula = NotesStringUtils.fromLMBCS(formulaPtr, textLen); return Arrays.asList((Object) formula); } finally { Mem64.OSUnlockObject(rethFormulaText.getValue()); result = Mem64.OSMemFree(rethFormulaText.getValue()); NotesErrorUtils.checkResult(result); } } else { IntByReference rethFormulaText = new IntByReference(); ShortByReference retFormulaTextLength = new ShortByReference(); short result = NotesNativeAPI32.get().NSFFormulaDecompile(valueDataPtr, isSelectionFormula, rethFormulaText, retFormulaTextLength); NotesErrorUtils.checkResult(result); Pointer formulaPtr = Mem32.OSLockObject(rethFormulaText.getValue()); try { int textLen = (int) (retFormulaTextLength.getValue() & 0xffff); String formula = NotesStringUtils.fromLMBCS(formulaPtr, textLen); return Arrays.asList((Object) formula); } finally { Mem32.OSUnlockObject(rethFormulaText.getValue()); result = Mem32.OSMemFree(rethFormulaText.getValue()); NotesErrorUtils.checkResult(result); } } } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { return Collections.emptyList(); } else { throw new UnsupportedItemValueError("Data type for value of item "+itemName+" is currently unsupported: "+dataTypeAsInt); } } /** * Attaches a disk file to a note.<br> * <br> * To accomplish this, the function creates an item of TYPE_OBJECT, sub-category OBJECT_FILE, * whose ITEM_xxx flag(s) are set to ITEM_SIGN | ITEM_SEAL.<br> * The item that is built by NSFNoteAttachFile contains all relevant file information and * the compressed file itself.<br> * Since the Item APIs offer no means of dealing with signed, sealed, or compressed item values, * the File Attachment API NSFNoteDetachFile must be used exclusively to access these items. * * @param filePathOnDisk fully qualified file path specification for file being attached * @param uniqueFileNameInNote filename that will be stored internally with the attachment, displayed when the attachment is not part of any richtext item (called "V2 attachment" in the Domino help), and subsequently used when selecting which attachment to extract or detach. Note that these operations may be carried out both from the workstation application Attachments dialog box and programmatically, so try to choose meaningful filenames as opposed to attach.001, attach002, etc., whenever possible. This function will be sure that the filename is really unique by appending _2, _3 etc. to the base filename, followed by the extension; use the returned NotesAttachment to get the filename we picked * @param compression compression to use * @return attachment object just created, e.g. to pass into {@link RichTextBuilder#addFileHotspot(NotesAttachment, String)} */ public NotesAttachment attachFile(String filePathOnDisk, String uniqueFileNameInNote, Compression compression) { checkHandle(); //make sure that the unique filename is really unique, since it will be used to return the NotesAttachment object List<Object> existingFileItems = FormulaExecution.evaluate("@AttachmentNames", this); String reallyUniqueFileName = uniqueFileNameInNote; if (existingFileItems.contains(reallyUniqueFileName)) { String newFileName=reallyUniqueFileName; int idx = 1; while (existingFileItems.contains(reallyUniqueFileName)) { idx++; int iPos = reallyUniqueFileName.lastIndexOf('.'); if (iPos==-1) { newFileName = reallyUniqueFileName+"_"+idx; } else { newFileName = reallyUniqueFileName.substring(0, iPos)+"_"+idx+reallyUniqueFileName.substring(iPos); } reallyUniqueFileName = newFileName; } } Memory $fileItemName = NotesStringUtils.toLMBCS("$FILE", true); Memory filePathOnDiskMem = NotesStringUtils.toLMBCS(filePathOnDisk, true); Memory uniqueFileNameInNoteMem = NotesStringUtils.toLMBCS(reallyUniqueFileName, true); short compressionAsShort = (short) (compression.getValue() & 0xffff); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NSFNoteAttachFile(m_hNote64, $fileItemName, (short) (($fileItemName.size()-1) & 0xffff), filePathOnDiskMem, uniqueFileNameInNoteMem, compressionAsShort); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NSFNoteAttachFile(m_hNote32, $fileItemName, (short) (($fileItemName.size()-1) & 0xffff), filePathOnDiskMem, uniqueFileNameInNoteMem, compressionAsShort); NotesErrorUtils.checkResult(result); } return getAttachment(reallyUniqueFileName); } /** * The method searches for a note attachment with the specified filename * * @param fileName filename to search for (case-insensitive) * @return attachment or null if not found */ public NotesAttachment getAttachment(final String fileName) { final NotesAttachment[] foundAttInfo = new NotesAttachment[1]; getItems("$file", new IItemCallback() { @Override public void itemNotFound() { } @Override public Action itemFound(NotesItem item) { List<Object> values = item.getValues(); if (values!=null && !values.isEmpty() && values.get(0) instanceof NotesAttachment) { NotesAttachment attInfo = (NotesAttachment) values.get(0); if (attInfo.getFileName().equalsIgnoreCase(fileName)) { foundAttInfo[0] = attInfo; return Action.Stop; } } return Action.Continue; } }); return foundAttInfo[0]; } /** * Decodes the value(s) of the first item with the specified item name<br> * <br> * The supported data types are documented here: {@link NotesItem#getValues()} * * @param itemName item name * @return value(s) as list, not null * @throws UnsupportedItemValueError if item type is not supported yet */ public List<Object> getItemValue(String itemName) { checkHandle(); NotesItem item = getFirstItem(itemName); if (item==null) { return Collections.emptyList(); } int valueLength = item.getValueLength(); Pointer valuePtr; //lock and decode value NotesBlockIdStruct valueBlockId = item.getValueBlockId(); Pointer poolPtr; if (PlatformUtils.is64Bit()) { poolPtr = Mem64.OSLockObject((long) valueBlockId.pool); } else { poolPtr = Mem32.OSLockObject(valueBlockId.pool); } int block = (int) (valueBlockId.block & 0xffff); long poolPtrLong = Pointer.nativeValue(poolPtr) + block; valuePtr = new Pointer(poolPtrLong); try { List<Object> values = getItemValue(itemName, item.getItemBlockId(), valuePtr, valueLength); return values; } finally { if (PlatformUtils.is64Bit()) { Mem64.OSUnlockObject((long) valueBlockId.pool); } else { Mem32.OSUnlockObject(valueBlockId.pool); } } } /** * Callback interface for {@link NotesNote#getItems(IItemCallback)} * * @author Karsten Lehmann */ public static interface IItemCallback { public static enum Action {Continue, Stop}; /** * Method is called when an item could not be found in the note */ public void itemNotFound(); /** * Method is called for each item in the note. A note may contain the same item name * multiple times. In this case, the method is called for each item instance * * @param item item object with meta data and access method to decode item value * @return next action, either continue or stop scan */ public Action itemFound(NotesItem item); } /** * Utility class to decode the item flag bitmask * * @author Karsten Lehmann */ public static class ItemFlags { private int m_itemFlags; public ItemFlags(int itemFlags) { m_itemFlags = itemFlags; } public int getBitMask() { return m_itemFlags; } public boolean isSigned() { return (m_itemFlags & NotesConstants.ITEM_SIGN) == NotesConstants.ITEM_SIGN; } public boolean isSealed() { return (m_itemFlags & NotesConstants.ITEM_SEAL) == NotesConstants.ITEM_SEAL; } public boolean isSummary() { return (m_itemFlags & NotesConstants.ITEM_SUMMARY) == NotesConstants.ITEM_SUMMARY; } public boolean isReadWriters() { return (m_itemFlags & NotesConstants.ITEM_READWRITERS) == NotesConstants.ITEM_READWRITERS; } public boolean isNames() { return (m_itemFlags & NotesConstants.ITEM_NAMES) == NotesConstants.ITEM_NAMES; } public boolean isPlaceholder() { return (m_itemFlags & NotesConstants.ITEM_PLACEHOLDER) == NotesConstants.ITEM_PLACEHOLDER; } public boolean isProtected() { return (m_itemFlags & NotesConstants.ITEM_PROTECTED) == NotesConstants.ITEM_PROTECTED; } public boolean isReaders() { return (m_itemFlags & NotesConstants.ITEM_READERS) == NotesConstants.ITEM_READERS; } public boolean isUnchanged() { return (m_itemFlags & NotesConstants.ITEM_UNCHANGED) == NotesConstants.ITEM_UNCHANGED; } } /** * Scans through all items of this note * * @param callback callback is called for each item found */ public void getItems(final IItemCallback callback) { getItems((String) null, callback); } /** * Scans through all items of this note that have the specified name * * @param searchForItemName item name to search for or null to scan through all items * @param callback callback is called for each scan result */ public void getItems(final String searchForItemName, final IItemCallback callback) { checkHandle(); Memory itemNameMem = StringUtil.isEmpty(searchForItemName) ? null : NotesStringUtils.toLMBCS(searchForItemName, false); NotesBlockIdStruct.ByReference itemBlockId = NotesBlockIdStruct.ByReference.newInstance(); NotesBlockIdStruct.ByReference valueBlockId = NotesBlockIdStruct.ByReference.newInstance(); ShortByReference retDataType = new ShortByReference(); IntByReference retValueLen = new IntByReference(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFItemInfo(m_hNote64, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retValueLen); } else { result = NotesNativeAPI32.get().NSFItemInfo(m_hNote32, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retValueLen); } if (result == INotesErrorConstants.ERR_ITEM_NOT_FOUND) { callback.itemNotFound(); return; } NotesErrorUtils.checkResult(result); NotesBlockIdStruct itemBlockIdClone = NotesBlockIdStruct.newInstance(); itemBlockIdClone.pool = itemBlockId.pool; itemBlockIdClone.block = itemBlockId.block; itemBlockIdClone.write(); NotesBlockIdStruct valueBlockIdClone = NotesBlockIdStruct.newInstance(); valueBlockIdClone.pool = valueBlockId.pool; valueBlockIdClone.block = valueBlockId.block; valueBlockIdClone.write(); int dataType = retDataType.getValue(); NotesItem itemInfo = new NotesItem(this, itemBlockIdClone, dataType, valueBlockIdClone); Action action = callback.itemFound(itemInfo); if (action != Action.Continue) { return; } while (true) { IntByReference retNextValueLen = new IntByReference(); NotesBlockIdStruct.ByValue itemBlockIdByVal = NotesBlockIdStruct.ByValue.newInstance(); itemBlockIdByVal.pool = itemBlockId.pool; itemBlockIdByVal.block = itemBlockId.block; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFItemInfoNext(m_hNote64, itemBlockIdByVal, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retNextValueLen); } else { result = NotesNativeAPI32.get().NSFItemInfoNext(m_hNote32, itemBlockIdByVal, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retNextValueLen); } if (result == INotesErrorConstants.ERR_ITEM_NOT_FOUND) { return; } NotesErrorUtils.checkResult(result); itemBlockIdClone = NotesBlockIdStruct.newInstance(); itemBlockIdClone.pool = itemBlockId.pool; itemBlockIdClone.block = itemBlockId.block; itemBlockIdClone.write(); valueBlockIdClone = NotesBlockIdStruct.newInstance(); valueBlockIdClone.pool = valueBlockId.pool; valueBlockIdClone.block = valueBlockId.block; valueBlockIdClone.write(); dataType = retDataType.getValue(); itemInfo = new NotesItem(this, itemBlockIdClone, dataType, valueBlockIdClone); action = callback.itemFound(itemInfo); if (action != Action.Continue) { return; } } } /** * Returns a {@link IRichTextNavigator} to traverse the CD record structure of a richtext item * back and forth * * @param richTextItemName richtext item name * @return navigator with position already set to the first CD record */ public IRichTextNavigator getRichtextNavigator(String richTextItemName) { return new MultiItemRichTextNavigator(richTextItemName); } /** * Extracts all text from a richtext item * * @param itemName item name * @return text content */ public String getRichtextContentAsText(String itemName) { final StringWriter sWriter = new StringWriter(); //find all items with this name in case the content got to big to fit into one item alone getItems(itemName, new IItemCallback() { @Override public void itemNotFound() { } @Override public Action itemFound(NotesItem item) { if (item.getType()==NotesItem.TYPE_COMPOSITE) { item.getAllCompositeTextContent(sWriter); } return Action.Continue; } }); return sWriter.toString(); } /** * Returns the first item with the specified name from the note * * @param itemName item name * @return item data or null if not found */ public NotesItem getFirstItem(String itemName) { if (itemName==null) { throw new IllegalArgumentException("Item name cannot be null. Use getItems() instead."); } final NotesItem[] retItem = new NotesItem[1]; getItems(itemName, new IItemCallback() { @Override public void itemNotFound() { retItem[0]=null; } @Override public Action itemFound(NotesItem itemInfo) { retItem[0] = itemInfo; return Action.Stop; } }); return retItem[0]; } /** * Checks whether this note is signed * * @return true if signed */ public boolean isSigned() { checkHandle(); ByteByReference signed_flag_ptr = new ByteByReference(); ByteByReference sealed_flag_ptr = new ByteByReference(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteIsSignedOrSealed(m_hNote64, signed_flag_ptr, sealed_flag_ptr); byte signed = signed_flag_ptr.getValue(); return signed == 1; } else { NotesNativeAPI32.get().NSFNoteIsSignedOrSealed(m_hNote32, signed_flag_ptr, sealed_flag_ptr); byte signed = signed_flag_ptr.getValue(); return signed == 1; } } /** * Checks whether this note is sealed * * @return true if sealed */ public boolean isSealed() { checkHandle(); ByteByReference signed_flag_ptr = new ByteByReference(); ByteByReference sealed_flag_ptr = new ByteByReference(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NSFNoteIsSignedOrSealed(m_hNote64, signed_flag_ptr, sealed_flag_ptr); byte sealed = sealed_flag_ptr.getValue(); return sealed == 1; } else { NotesNativeAPI32.get().NSFNoteIsSignedOrSealed(m_hNote32, signed_flag_ptr, sealed_flag_ptr); byte sealed = sealed_flag_ptr.getValue(); return sealed == 1; } } /** Possible validation phases for {@link NotesNote#computeWithForm(boolean, ComputeWithFormCallback)} */ public static enum ValidationPhase { /** Error occurred when processing the Default Value formula. */ CWF_DV_FORMULA, /** Error occurred when processing the Translation formula. */ CWF_IT_FORMULA, /** Error occurred when processing the Validation formula. */ CWF_IV_FORMULA, /** Error occurred when processing the computed field Value formula. */ CWF_COMPUTED_FORMULA, /** Error occurred when verifying the data type for the field. */ CWF_DATATYPE_CONVERSION, /** Error occurred when processing the computed field Value formula, during the "load" pass. */ CWF_COMPUTED_FORMULA_LOAD, /** Error occurred when processing the computed field Value formula, during the "save" pass. */ CWF_COMPUTED_FORMULA_SAVE }; /* Possible return values from the callback routine specified in NSFNoteComputeWithForm() */ public static enum CWF_Action { /** End all processing by NSFNoteComputeWithForm() and return the error status to the caller. */ CWF_ABORT((short) 1), /** End validation of the current field and go on to the next. */ CWF_NEXT_FIELD((short) 2), /** Begin the validation process for this field over again. */ CWF_RECHECK_FIELD((short) 3); short actionVal; CWF_Action(short val) { this.actionVal = val; } public short getShortVal() { return actionVal; } } private ValidationPhase decodeValidationPhase(short phase) { ValidationPhase phaseEnum = null; if (phase == NotesConstants.CWF_DV_FORMULA) { phaseEnum = ValidationPhase.CWF_DV_FORMULA; } else if (phase == NotesConstants.CWF_IT_FORMULA) { phaseEnum = ValidationPhase.CWF_IT_FORMULA; } else if (phase == NotesConstants.CWF_IV_FORMULA) { phaseEnum = ValidationPhase.CWF_IV_FORMULA; } else if (phase == NotesConstants.CWF_COMPUTED_FORMULA) { phaseEnum = ValidationPhase.CWF_COMPUTED_FORMULA; } else if (phase == NotesConstants.CWF_DATATYPE_CONVERSION) { phaseEnum = ValidationPhase.CWF_DATATYPE_CONVERSION; } else if (phase == NotesConstants.CWF_COMPUTED_FORMULA_LOAD) { phaseEnum = ValidationPhase.CWF_COMPUTED_FORMULA_LOAD; } else if (phase == NotesConstants.CWF_COMPUTED_FORMULA_SAVE) { phaseEnum = ValidationPhase.CWF_COMPUTED_FORMULA_SAVE; } return phaseEnum; } private FieldInfo readCDFieldInfo(Pointer ptrCDField) { NotesCDFieldStruct cdField = NotesCDFieldStruct.newInstance(ptrCDField); cdField.read(); Pointer defaultValueFormulaPtr = ptrCDField.share(NotesConstants.cdFieldSize); Pointer inputTranslationFormulaPtr = defaultValueFormulaPtr.share(cdField.DVLength & 0xffff); Pointer inputValidityCheckFormulaPtr = inputTranslationFormulaPtr.share((cdField.ITLength &0xffff) + (cdField.TabOrder & 0xffff)); // Pointer namePtr = inputValidityCheckFormulaPtr.share(cdField.IVLength & 0xffff); // field.DVLength + field.ITLength + field.IVLength, // field.NameLength Pointer namePtr = ptrCDField.share((cdField.DVLength & 0xffff) + (cdField.ITLength & 0xffff) + (cdField.IVLength & 0xffff)); Pointer descriptionPtr = namePtr.share(cdField.NameLength & 0xffff); String defaultValueFormula = NotesStringUtils.fromLMBCS(defaultValueFormulaPtr, cdField.DVLength & 0xffff); String inputTranslationFormula = NotesStringUtils.fromLMBCS(inputTranslationFormulaPtr, cdField.ITLength & 0xffff); String inputValidityCheckFormula = NotesStringUtils.fromLMBCS(inputValidityCheckFormulaPtr, cdField.IVLength & 0xffff); String name = NotesStringUtils.fromLMBCS(namePtr, cdField.NameLength & 0xffff); String description = NotesStringUtils.fromLMBCS(descriptionPtr, cdField.DescLength & 0xffff); return new FieldInfo(defaultValueFormula, inputTranslationFormula, inputValidityCheckFormula, name, description); } public static class FieldInfo { private String m_defaultValueFormula; private String m_inputTranslationFormula; private String m_inputValidityCheckFormula; private String m_name; private String m_description; public FieldInfo(String defaultValueFormula, String inputTranslationFormula, String inputValidityCheckFormula, String name, String description) { m_defaultValueFormula = defaultValueFormula; m_inputTranslationFormula = inputTranslationFormula; m_inputValidityCheckFormula = inputValidityCheckFormula; m_name = name; m_description = description; } public String getDefaultValueFormula() { return m_defaultValueFormula; } public String getInputTranslationFormula() { return m_inputTranslationFormula; } public String getInputValidityCheckFormula() { return m_inputValidityCheckFormula; } public String getName() { return m_name; } public String getDescription() { return m_description; } @Override public String toString() { return "FieldInfo [name="+getName()+", description="+getDescription()+", default="+getDefaultValueFormula()+ ", inputtranslation="+getInputTranslationFormula()+", validation="+getInputValidityCheckFormula()+"]"; } } /** * Compiles all LotusScript code in this design note. * * @throws LotusScriptCompilationError when encountering descriptive compilation problem * @throws NotesError for other errors or compilation problems without further description */ public void compileLotusScript() { checkHandle(); final Ref<NotesError> exception = new Ref<NotesError>(); final NotesCallbacks.LSCompilerErrorProc errorProc; if (PlatformUtils.isWin32()) { errorProc = new Win32NotesCallbacks.LSCompilerErrorProcWin32() { @Override public short invoke(Pointer pInfo, Pointer pCtx) { NotesLSCompileErrorInfoStruct errorInfo = NotesLSCompileErrorInfoStruct.newInstance(pInfo); errorInfo.read(); int errTextLen = NotesStringUtils.getNullTerminatedLength(errorInfo.pErrText); int errFileLen = NotesStringUtils.getNullTerminatedLength(errorInfo.pErrFile); String errText = NotesStringUtils.fromLMBCS(errorInfo.pErrText, errTextLen); String errFile = NotesStringUtils.fromLMBCS(errorInfo.pErrFile, errFileLen); exception.set(new LotusScriptCompilationError(12051, errorInfo.getLineAsInt(), errText, errFile)); return 0; } }; } else { errorProc = new NotesCallbacks.LSCompilerErrorProc() { @Override public short invoke(Pointer pInfo, Pointer pCtx) { NotesLSCompileErrorInfoStruct errorInfo = NotesLSCompileErrorInfoStruct.newInstance(pInfo); errorInfo.read(); int errTextLen = NotesStringUtils.getNullTerminatedLength(errorInfo.pErrText); int errFileLen = NotesStringUtils.getNullTerminatedLength(errorInfo.pErrFile); String errText = NotesStringUtils.fromLMBCS(errorInfo.pErrText, errTextLen); String errFile = NotesStringUtils.fromLMBCS(errorInfo.pErrFile, errFileLen); exception.set(new LotusScriptCompilationError(12051, errorInfo.getLineAsInt(), errText, errFile)); return 0; } }; } short result; try { if (PlatformUtils.is64Bit()) { //AccessController call required to prevent SecurityException when running in XPages result = AccessController.doPrivileged(new PrivilegedExceptionAction<Short>() { @Override public Short run() throws Exception { return NotesNativeAPI64.get().NSFNoteLSCompileExt(NotesNote.this.getParent().getHandle64(), m_hNote64, 0, errorProc, null); } }); } else { result = AccessController.doPrivileged(new PrivilegedExceptionAction<Short>() { @Override public Short run() throws Exception { return NotesNativeAPI32.get().NSFNoteLSCompileExt(NotesNote.this.getParent().getHandle32(), m_hNote32, 0, errorProc, null); } }); } } catch (PrivilegedActionException e) { if (e.getCause() instanceof RuntimeException) throw (RuntimeException) e.getCause(); else throw new NotesError(0, "Error getting notes from database", e); } if(exception.get() != null) { throw exception.get(); } NotesErrorUtils.checkResult(result); } public void computeWithForm(boolean continueOnError, final ComputeWithFormCallback callback) { checkHandle(); int dwFlags = 0; if (continueOnError) { dwFlags = NotesConstants.CWF_CONTINUE_ON_ERROR; } if (PlatformUtils.is64Bit()) { NotesCallbacks.b64_CWFErrorProc errorProc = new NotesCallbacks.b64_CWFErrorProc() { @Override public short invoke(Pointer pCDField, short phase, short error, long hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = Mem64.OSLockObject(hErrorText); System.out.println("ErrorTextPtr: "+errorTextPtr.dump(0, (int) (wErrorTextSize & 0xffff))); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { Mem64.OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; short result = NotesNativeAPI64.get().NSFNoteComputeWithForm(m_hNote64, 0, dwFlags, errorProc, null); NotesErrorUtils.checkResult(result); } else { NotesCallbacks.b32_CWFErrorProc errorProc; if (PlatformUtils.isWin32()) { errorProc = new Win32NotesCallbacks.CWFErrorProcWin32() { @Override public short invoke(Pointer pCDField, short phase, short error, int hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = Mem32.OSLockObject(hErrorText); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { Mem32.OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; } else { errorProc = new NotesCallbacks.b32_CWFErrorProc() { @Override public short invoke(Pointer pCDField, short phase, short error, int hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = Mem32.OSLockObject(hErrorText); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { Mem32.OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; } short result = NotesNativeAPI32.get().NSFNoteComputeWithForm(m_hNote32, 0, dwFlags, errorProc, null); NotesErrorUtils.checkResult(result); } } public static interface ComputeWithFormCallback { public CWF_Action errorRaised(FieldInfo fieldInfo, ValidationPhase phase, String errorTxt, long errCode); } public static enum EncryptionMode { /** Encrypt the message with the key in the user's ID. This flag is not for outgoing mail * messages because recipients, other than the sender, will not be able to decrypt * the message. This flag can be useful to encrypt documents in a local database to * keep them secure or to encrypt documents that can only be decrypted by the same user. */ ENCRYPT_WITH_USER_PUBLIC_KEY (NotesConstants.ENCRYPT_WITH_USER_PUBLIC_KEY), /** * Encrypt SMIME if MIME present */ ENCRYPT_SMIME_IF_MIME_PRESENT (NotesConstants.ENCRYPT_SMIME_IF_MIME_PRESENT), /** * Encrypt SMIME no sender. */ ENCRYPT_SMIME_NO_SENDER (NotesConstants.ENCRYPT_SMIME_NO_SENDER), /** * Encrypt SMIME trusting all certificates. */ ENCRYPT_SMIME_TRUST_ALL_CERTS(NotesConstants.ENCRYPT_SMIME_TRUST_ALL_CERTS); private int m_mode; private EncryptionMode(int mode) { m_mode = mode; } public int getMode() { return m_mode; } }; /** * This function copies and encrypts (seals) the encryption enabled fields in a note * (including the note's file objects), using the current ID file.<br> * <br> * It can encrypt a note in several ways -- by using the Domino public key of the caller, * by using specified secret encryption keys stored in the caller's ID, or by using the * Domino public keys of specified users, if the note does not have any mime parts.<br> * <br> * The method decides which type of encryption to do based upon the setting of the flag * passed to it in its <code>encryptionMode</code> argument.<br> * <br> * If the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is set, it uses the * caller's public ID to encrypt the note.<br> * In this case, only the user who encodes the note can decrypt it.<br> * This feature allows an individual to protect information from anyone else.<br> * <br> * If, instead, the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is not set, * then the function expects the note to contain a field named "SecretEncryptionKeys" * a field named "PublicEncryptionKeys", or both.<br> * Each field is either a TYPE_TEXT or TYPE_TEXT_LIST field.<br> * <br> * "SecretEncryptionKeys" contains the name(s) of the secret encryption keys in the * calling user's ID to be used to encrypt the note.<br> * This feature is intended to allow a group to encrypt some of the notes in a single * database in a way that only they can decrypt them -- they must share the secret encryption * keys among themselves first for this to work.<br> * <br> * "PublicEncryptionKeys" contains the name(s) of users, in canonical format.<br> * The note will be encrypted with each user's Domino public key.<br> * The user can then decrypt the note with the private key in the user's ID.<br> * This feature provides a way to encrypt documents, such as mail documents, for another user.<br> * <br> * The note must contain at least one encryption enabled item (an item with the ITEM_SEAL flag set) * in order to be encrypted.<br> * If the note has mime parts and flag {@link EncryptionMode#ENCRYPT_SMIME_IF_MIME_PRESENT} * is set, then it is SMIME encrypted.<br> * <br> * If the document is to be signed as well as encrypted, you must sign the document * before using this method. * @param encryptionMode encryption mode * @return encrypted note copy */ public NotesNote copyAndEncrypt(EnumSet<EncryptionMode> encryptionMode) { return copyAndEncrypt(null, encryptionMode); } /** * This function copies and encrypts (seals) the encryption enabled fields in a note * (including the note's file objects), using a handle to an ID file.<br> * <br> * It can encrypt a note in several ways -- by using the Domino public key of the caller, * by using specified secret encryption keys stored in the caller's ID, or by using the * Domino public keys of specified users, if the note does not have any mime parts.<br> * <br> * The method decides which type of encryption to do based upon the setting of the flag * passed to it in its <code>encryptionMode</code> argument.<br> * <br> * If the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is set, it uses the * caller's public ID to encrypt the note.<br> * In this case, only the user who encodes the note can decrypt it.<br> * This feature allows an individual to protect information from anyone else.<br> * <br> * If, instead, the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is not set, * then the function expects the note to contain a field named "SecretEncryptionKeys" * a field named "PublicEncryptionKeys", or both.<br> * Each field is either a TYPE_TEXT or TYPE_TEXT_LIST field.<br> * <br> * "SecretEncryptionKeys" contains the name(s) of the secret encryption keys in the * calling user's ID to be used to encrypt the note.<br> * This feature is intended to allow a group to encrypt some of the notes in a single * database in a way that only they can decrypt them -- they must share the secret encryption * keys among themselves first for this to work.<br> * <br> * "PublicEncryptionKeys" contains the name(s) of users, in canonical format.<br> * The note will be encrypted with each user's Domino public key.<br> * The user can then decrypt the note with the private key in the user's ID.<br> * This feature provides a way to encrypt documents, such as mail documents, for another user.<br> * <br> * The note must contain at least one encryption enabled item (an item with the ITEM_SEAL flag set) * in order to be encrypted.<br> * If the note has mime parts and flag {@link EncryptionMode#ENCRYPT_SMIME_IF_MIME_PRESENT} * is set, then it is SMIME encrypted.<br> * <br> * If the document is to be signed as well as encrypted, you must sign the document * before using this method. * @param id user id to be used for encryption, use null for current id * @param encryptionMode encryption mode * @return encrypted note copy */ public NotesNote copyAndEncrypt(NotesUserId id, EnumSet<EncryptionMode> encryptionMode) { checkHandle(); int flags = 0; for (EncryptionMode currMode : encryptionMode) { flags = flags | currMode.getMode(); } short flagsShort = (short) (flags & 0xffff); short result; if (PlatformUtils.is64Bit()) { LongByReference rethDstNote = new LongByReference(); result = NotesNativeAPI64.get().NSFNoteCopyAndEncryptExt2(m_hNote64, id==null ? 0 : id.getHandle64(), flagsShort, rethDstNote, 0, null); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(m_parentDb, rethDstNote.getValue()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } else { IntByReference rethDstNote = new IntByReference(); result = NotesNativeAPI32.get().NSFNoteCopyAndEncryptExt2(m_hNote32, id==null ? 0 : id.getHandle32(), flagsShort, rethDstNote, 0, null); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(m_parentDb, rethDstNote.getValue()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } } public NotesNote copyToDatabase(NotesDatabase targetDb) { checkHandle(); if (targetDb.isRecycled()) { throw new NotesError(0, "Target database already recycled"); } if (PlatformUtils.is64Bit()) { LongByReference note_handle_dst = new LongByReference(); short result = NotesNativeAPI64.get().NSFNoteCopy(m_hNote64, note_handle_dst); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(targetDb, note_handle_dst.getValue()); NotesOriginatorId newOid = targetDb.generateOID(); NotesOriginatorIdStruct newOidStruct = newOid.getAdapter(NotesOriginatorIdStruct.class); NotesNativeAPI64.get().NSFNoteSetInfo(copyNote.getHandle64(), NotesConstants._NOTE_ID, null); NotesNativeAPI64.get().NSFNoteSetInfo(copyNote.getHandle64(), NotesConstants._NOTE_OID, newOidStruct.getPointer()); LongByReference targetDbHandle = new LongByReference(); targetDbHandle.setValue(targetDb.getHandle64()); NotesNativeAPI64.get().NSFNoteSetInfo(copyNote.getHandle64(), NotesConstants._NOTE_DB, targetDbHandle.getPointer()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } else { IntByReference note_handle_dst = new IntByReference(); short result = NotesNativeAPI32.get().NSFNoteCopy(m_hNote32, note_handle_dst); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(targetDb, note_handle_dst.getValue()); NotesOriginatorId newOid = targetDb.generateOID(); NotesOriginatorIdStruct newOidStruct = newOid.getAdapter(NotesOriginatorIdStruct.class); NotesNativeAPI32.get().NSFNoteSetInfo(copyNote.getHandle32(), NotesConstants._NOTE_ID, null); NotesNativeAPI32.get().NSFNoteSetInfo(copyNote.getHandle32(), NotesConstants._NOTE_OID, newOidStruct.getPointer()); IntByReference targetDbHandle = new IntByReference(); targetDbHandle.setValue(targetDb.getHandle32()); NotesNativeAPI32.get().NSFNoteSetInfo(copyNote.getHandle32(), NotesConstants._NOTE_DB, targetDbHandle.getPointer()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } } /** * This function decrypts an encrypted note, using the current user's ID file.<br> * If the user does not have the appropriate encryption key to decrypt the note, an error is returned.<br> * <br> * This function supports new cryptographic keys and algorithms introduced in Release 8.0.1 as * well as any from releases prior to 8.0.1. * <br> * The current implementation of this function automatically decrypts attachments as well. */ public void decrypt() { decrypt(null); } /** * This function decrypts an encrypted note, using the appropriate encryption key stored * in the user's ID file.<br> * If the user does not have the appropriate encryption key to decrypt the note, an error is returned.<br> * <br> * This function supports new cryptographic keys and algorithms introduced in Release 8.0.1 as * well as any from releases prior to 8.0.1. * <br> * The current implementation of this function automatically decrypts attachments as well. * * @param id user id used for decryption, use null for current id */ public void decrypt(NotesUserId id) { checkHandle(); short decryptFlags = NotesConstants.DECRYPT_ATTACHMENTS_IN_PLACE; short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteCipherDecrypt(m_hNote64, id==null ? 0 : id.getHandle64(), decryptFlags, null, 0, null); } else { result = NotesNativeAPI32.get().NSFNoteCipherDecrypt(m_hNote32, id==null ? 0 : id.getHandle32(), decryptFlags, null, 0, null); } NotesErrorUtils.checkResult(result); } /** * Removes any existing field with the specified name and creates a new one with the specified value, setting the {@link ItemType#SUMMARY}<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * </ul> * * @param itemName item name * @param value item value, see method comment for allowed types * @return created item */ public NotesItem replaceItemValue(String itemName, Object value) { return replaceItemValue(itemName, EnumSet.of(ItemType.SUMMARY), value); } /** * Removes any existing field with the specified name and creates a new one with the specified value.<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * </ul> * * @param itemName item name * @param flags item flags, e.g. {@link ItemType#SUMMARY} * @param value item value, see method comment for allowed types; use null to just remove the old item value * @return created item or null if value was null */ public NotesItem replaceItemValue(String itemName, EnumSet<ItemType> flags, Object value) { if (!hasSupportedItemObjectType(value)) { throw new IllegalArgumentException("Unsupported value type: "+(value==null ? "null" : value.getClass().getName())); } while (hasItem(itemName)) { removeItem(itemName); } if (value!=null) return appendItemValue(itemName, flags, value); else return null; } @SuppressWarnings("rawtypes") private boolean hasSupportedItemObjectType(Object value) { if (value==null) { return true; } else if (value instanceof String) { return true; } else if (value instanceof Number) { return true; } else if (value instanceof Calendar || value instanceof NotesTimeDate || value instanceof Date) { return true; } else if (value instanceof List && ((List)value).isEmpty()) { return true; } else if (value instanceof List && isStringList((List) value)) { return true; } else if (value instanceof List && isNumberOrNumberArrayList((List) value)) { return true; } else if (value instanceof List && isCalendarOrCalendarArrayList((List) value)) { return true; } else if (value instanceof Calendar[] && ((Calendar[])value).length==2) { return true; } else if (value instanceof NotesTimeDate[] && ((NotesTimeDate[])value).length==2) { return true; } else if (value instanceof Date[] && ((Date[])value).length==2) { return true; } else if (value instanceof Number[] && ((Number[])value).length==2) { return true; } else if (value instanceof Double[] && ((Double[])value).length==2) { return true; } else if (value instanceof Integer[] && ((Integer[])value).length==2) { return true; } else if (value instanceof Long[] && ((Long[])value).length==2) { return true; } else if (value instanceof Float[] && ((Float[])value).length==2) { return true; } else if (value instanceof double[] && ((double[])value).length==2) { return true; } else if (value instanceof int[] && ((int[])value).length==2) { return true; } else if (value instanceof long[] && ((long[])value).length==2) { return true; } else if (value instanceof float[] && ((float[])value).length==2) { return true; } else if (value instanceof NotesUniversalNoteId) { return true; } return false; } /** * Creates a new item with the specified value, setting the {@link ItemType#SUMMARY} (does not overwrite items with the same name)<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * </ul> * * @param itemName item name * @param value item value, see method comment for allowed types * @return created item */ public NotesItem appendItemValue(String itemName, Object value) { return appendItemValue(itemName, EnumSet.of(ItemType.SUMMARY), value); } /** * Creates a new item with the specified item flags and value<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * <li>{@link NotesUniversalNoteId} for $REF like items</li> * </ul> * * @param itemName item name * @param flags item flags * @param value item value, see method comment for allowed types * @return created item */ public NotesItem appendItemValue(String itemName, EnumSet<ItemType> flags, Object value) { checkHandle(); if (value instanceof String) { Memory strValueMem = NotesStringUtils.toLMBCS((String)value, false); int valueSize = (int) (2 + (strValueMem==null ? 0 : strValueMem.size())); if (PlatformUtils.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = Mem64.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem64.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TEXT); valuePtr = valuePtr.share(2); if (strValueMem!=null) { valuePtr.write(0, strValueMem.getByteArray(0, (int) strValueMem.size()), 0, (int) strValueMem.size()); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT, (int) rethItem.getValue(), valueSize); return item; } finally { Mem64.OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = Mem32.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem32.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TEXT); valuePtr = valuePtr.share(2); if (strValueMem!=null) { valuePtr.write(0, strValueMem.getByteArray(0, (int) strValueMem.size()), 0, (int) strValueMem.size()); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT, rethItem.getValue(), valueSize); return item; } finally { Mem32.OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof Number) { int valueSize = 2 + 8; if (PlatformUtils.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = Mem64.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem64.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER); valuePtr = valuePtr.share(2); valuePtr.setDouble(0, ((Number)value).doubleValue()); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER, (int) rethItem.getValue(), valueSize); return item; } finally { Mem64.OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = Mem32.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem32.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER); valuePtr = valuePtr.share(2); valuePtr.setDouble(0, ((Number)value).doubleValue()); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER, rethItem.getValue(), valueSize); return item; } finally { Mem32.OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof Calendar || value instanceof NotesTimeDate || value instanceof Date) { int[] innards; boolean hasDate; boolean hasTime; if (value instanceof NotesTimeDate) { //no date conversion to innards needing, we already have them innards = ((NotesTimeDate)value).getInnards(); hasTime = innards[0] != NotesConstants.ALLDAY; hasDate = innards[1] != NotesConstants.ANYDAY; } else { Calendar calValue; if (value instanceof Calendar) { calValue = (Calendar) value; } else if (value instanceof NotesTimeDate) { calValue = ((NotesTimeDate)value).toCalendar(); } else if (value instanceof Date) { calValue = Calendar.getInstance(); calValue.setTime((Date) value); } else { throw new IllegalArgumentException("Unsupported date value type: "+(value==null ? "null" : value.getClass().getName())); } hasDate = NotesDateTimeUtils.hasDate(calValue); hasTime = NotesDateTimeUtils.hasTime(calValue); innards = NotesDateTimeUtils.calendarToInnards(calValue, hasDate, hasTime); } int valueSize = 2 + 8; if (PlatformUtils.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = Mem64.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem64.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME); valuePtr = valuePtr.share(2); NotesTimeDateStruct timeDate = NotesTimeDateStruct.newInstance(valuePtr); timeDate.Innards[0] = innards[0]; timeDate.Innards[1] = innards[1]; timeDate.write(); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME, (int) rethItem.getValue(), valueSize); return item; } finally { Mem64.OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = Mem32.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem32.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME); valuePtr = valuePtr.share(2); NotesTimeDateStruct timeDate = NotesTimeDateStruct.newInstance(valuePtr); timeDate.Innards[0] = innards[0]; timeDate.Innards[1] = innards[1]; timeDate.write(); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME, rethItem.getValue(), valueSize); return item; } finally { Mem32.OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof List && (((List)value).isEmpty() || isStringList((List) value))) { List<String> strList = (List<String>) value; if (strList.size()> 65535) { throw new IllegalArgumentException("String list size must fit in a WORD ("+strList.size()+">65535)"); } short result; if (PlatformUtils.is64Bit()) { LongByReference rethList = new LongByReference(); ShortByReference retListSize = new ShortByReference(); result = NotesNativeAPI64.get().ListAllocate((short) 0, (short) 0, 1, rethList, null, retListSize); NotesErrorUtils.checkResult(result); long hList = rethList.getValue(); Mem64.OSUnlockObject(hList); for (int i=0; i<strList.size(); i++) { String currStr = strList.get(i); Memory currStrMem = NotesStringUtils.toLMBCS(currStr, false); result = NotesNativeAPI64.get().ListAddEntry(hList, 1, retListSize, (short) (i & 0xffff), currStrMem, (short) (currStrMem==null ? 0 : (currStrMem.size() & 0xffff))); NotesErrorUtils.checkResult(result); } int listSize = retListSize.getValue() & 0xffff; @SuppressWarnings("unused") Pointer valuePtr = Mem64.OSLockObject(hList); try { NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT_LIST, (int) hList, listSize); return item; } finally { Mem64.OSUnlockObject(hList); } } else { IntByReference rethList = new IntByReference(); ShortByReference retListSize = new ShortByReference(); result = NotesNativeAPI32.get().ListAllocate((short) 0, (short) 0, 1, rethList, null, retListSize); NotesErrorUtils.checkResult(result); int hList = rethList.getValue(); Mem32.OSUnlockObject(hList); for (int i=0; i<strList.size(); i++) { String currStr = strList.get(i); Memory currStrMem = NotesStringUtils.toLMBCS(currStr, false); result = NotesNativeAPI32.get().ListAddEntry(hList, 1, retListSize, (short) (i & 0xffff), currStrMem, (short) (currStrMem==null ? 0 : (currStrMem.size() & 0xffff))); NotesErrorUtils.checkResult(result); } int listSize = retListSize.getValue() & 0xffff; @SuppressWarnings("unused") Pointer valuePtr = Mem32.OSLockObject(hList); try { NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT_LIST, (int) hList, listSize); return item; } finally { Mem32.OSUnlockObject(hList); } } } else if (value instanceof List && isNumberOrNumberArrayList((List) value)) { List<?> numberOrNumberArrList = toNumberOrNumberArrayList((List<?>) value); List<Number> numberList = new ArrayList<Number>(); List<double[]> numberArrList = new ArrayList<double[]>(); for (int i=0; i<numberOrNumberArrList.size(); i++) { Object currObj = numberOrNumberArrList.get(i); if (currObj instanceof Double) { numberList.add((Number) currObj); } else if (currObj instanceof double[]) { numberArrList.add((double[])currObj); } } if (numberList.size()> 65535) { throw new IllegalArgumentException("Number list size must fit in a WORD ("+numberList.size()+">65535)"); } if (numberArrList.size()> 65535) { throw new IllegalArgumentException("Number range list size must fit in a WORD ("+numberList.size()+">65535)"); } int valueSize = 2 + NotesConstants.rangeSize + 8 * numberList.size() + NotesConstants.numberPairSize * numberArrList.size(); if (PlatformUtils.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = Mem64.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem64.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (numberList.size() & 0xffff); range.RangeEntries = (short) (numberArrList.size() & 0xffff); range.write(); Pointer doubleListPtr = rangePtr.share(NotesConstants.rangeSize); for (int i=0; i<numberList.size(); i++) { doubleListPtr.setDouble(0, numberList.get(i).doubleValue()); doubleListPtr = doubleListPtr.share(8); } Pointer doubleArrListPtr = doubleListPtr; for (int i=0; i<numberArrList.size(); i++) { double[] currNumberArr = numberArrList.get(i); NotesNumberPairStruct numberPair = NotesNumberPairStruct.newInstance(doubleArrListPtr); numberPair.Lower = currNumberArr[0]; numberPair.Upper = currNumberArr[1]; numberPair.write(); doubleArrListPtr = doubleArrListPtr.share(NotesConstants.numberPairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER_RANGE, (int) rethItem.getValue(), valueSize); return item; } finally { Mem64.OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = Mem32.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem32.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (numberList.size() & 0xffff); range.RangeEntries = (short) (numberArrList.size() & 0xffff); range.write(); Pointer doubleListPtr = rangePtr.share(NotesConstants.rangeSize); for (int i=0; i<numberList.size(); i++) { doubleListPtr.setDouble(0, numberList.get(i).doubleValue()); doubleListPtr = doubleListPtr.share(8); } Pointer doubleArrListPtr = doubleListPtr; for (int i=0; i<numberArrList.size(); i++) { double[] currNumberArr = numberArrList.get(i); NotesNumberPairStruct numberPair = NotesNumberPairStruct.newInstance(doubleArrListPtr); numberPair.Lower = currNumberArr[0]; numberPair.Upper = currNumberArr[1]; numberPair.write(); doubleArrListPtr = doubleArrListPtr.share(NotesConstants.numberPairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER_RANGE, rethItem.getValue(), valueSize); return item; } finally { Mem32.OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof Calendar[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Date[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof NotesTimeDate[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof List && isCalendarOrCalendarArrayList((List) value)) { List<?> calendarOrCalendarArrList = toCalendarOrCalendarArrayList((List<?>) value); List<Calendar> calendarList = new ArrayList<Calendar>(); List<Calendar[]> calendarArrList = new ArrayList<Calendar[]>(); for (int i=0; i<calendarOrCalendarArrList.size(); i++) { Object currObj = calendarOrCalendarArrList.get(i); if (currObj instanceof Calendar) { calendarList.add((Calendar) currObj); } else if (currObj instanceof Calendar[]) { calendarArrList.add((Calendar[]) currObj); } } if (calendarList.size() > 65535) { throw new IllegalArgumentException("Date list size must fit in a WORD ("+calendarList.size()+">65535)"); } if (calendarArrList.size() > 65535) { throw new IllegalArgumentException("Date range list size must fit in a WORD ("+calendarArrList.size()+">65535)"); } int valueSize = 2 + NotesConstants.rangeSize + 8 * calendarList.size() + NotesConstants.timeDatePairSize * calendarArrList.size(); if (PlatformUtils.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = Mem64.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem64.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (calendarList.size() & 0xffff); range.RangeEntries = (short) (calendarArrList.size() & 0xffff); range.write(); Pointer dateListPtr = rangePtr.share(NotesConstants.rangeSize); for (Calendar currCal : calendarList) { boolean hasDate = NotesDateTimeUtils.hasDate(currCal); boolean hasTime = NotesDateTimeUtils.hasTime(currCal); int[] innards = NotesDateTimeUtils.calendarToInnards(currCal, hasDate, hasTime); dateListPtr.setInt(0, innards[0]); dateListPtr = dateListPtr.share(4); dateListPtr.setInt(0, innards[1]); dateListPtr = dateListPtr.share(4); } Pointer rangeListPtr = dateListPtr; for (int i=0; i<calendarArrList.size(); i++) { Calendar[] currRangeVal = calendarArrList.get(i); boolean hasDateStart = NotesDateTimeUtils.hasDate(currRangeVal[0]); boolean hasTimeStart = NotesDateTimeUtils.hasTime(currRangeVal[0]); int[] innardsStart = NotesDateTimeUtils.calendarToInnards(currRangeVal[0], hasDateStart, hasTimeStart); boolean hasDateEnd = NotesDateTimeUtils.hasDate(currRangeVal[1]); boolean hasTimeEnd = NotesDateTimeUtils.hasTime(currRangeVal[1]); int[] innardsEnd = NotesDateTimeUtils.calendarToInnards(currRangeVal[1], hasDateEnd, hasTimeEnd); NotesTimeDateStruct timeDateStart = NotesTimeDateStruct.newInstance(innardsStart); NotesTimeDateStruct timeDateEnd = NotesTimeDateStruct.newInstance(innardsEnd); NotesTimeDatePairStruct timeDatePair = NotesTimeDatePairStruct.newInstance(rangeListPtr); timeDatePair.Lower = timeDateStart; timeDatePair.Upper = timeDateEnd; timeDatePair.write(); rangeListPtr = rangeListPtr.share(NotesConstants.timeDatePairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME_RANGE, (int) rethItem.getValue(), valueSize); return item; } finally { Mem64.OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = Mem32.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem32.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (calendarList.size() & 0xffff); range.RangeEntries = (short) (calendarArrList.size() & 0xffff); range.write(); Pointer dateListPtr = rangePtr.share(NotesConstants.rangeSize); for (Calendar currCal : calendarList) { boolean hasDate = NotesDateTimeUtils.hasDate(currCal); boolean hasTime = NotesDateTimeUtils.hasTime(currCal); int[] innards = NotesDateTimeUtils.calendarToInnards(currCal, hasDate, hasTime); dateListPtr.setInt(0, innards[0]); dateListPtr = dateListPtr.share(4); dateListPtr.setInt(0, innards[1]); dateListPtr = dateListPtr.share(4); } Pointer rangeListPtr = dateListPtr; for (int i=0; i<calendarArrList.size(); i++) { Calendar[] currRangeVal = calendarArrList.get(i); boolean hasDateStart = NotesDateTimeUtils.hasDate(currRangeVal[0]); boolean hasTimeStart = NotesDateTimeUtils.hasTime(currRangeVal[0]); int[] innardsStart = NotesDateTimeUtils.calendarToInnards(currRangeVal[0], hasDateStart, hasTimeStart); boolean hasDateEnd = NotesDateTimeUtils.hasDate(currRangeVal[1]); boolean hasTimeEnd = NotesDateTimeUtils.hasTime(currRangeVal[1]); int[] innardsEnd = NotesDateTimeUtils.calendarToInnards(currRangeVal[1], hasDateEnd, hasTimeEnd); NotesTimeDateStruct timeDateStart = NotesTimeDateStruct.newInstance(innardsStart); NotesTimeDateStruct timeDateEnd = NotesTimeDateStruct.newInstance(innardsEnd); NotesTimeDatePairStruct timeDatePair = NotesTimeDatePairStruct.newInstance(rangeListPtr); timeDatePair.Lower = timeDateStart; timeDatePair.Upper = timeDateEnd; timeDatePair.write(); rangeListPtr = rangeListPtr.share(NotesConstants.timeDatePairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME_RANGE, (int) rethItem.getValue(), valueSize); return item; } finally { Mem32.OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof double[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof int[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof float[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof long[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Number[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Double[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Integer[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Float[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Long[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof NotesUniversalNoteId) { NotesUniversalNoteIdStruct struct = ((NotesUniversalNoteId)value).getAdapter(NotesUniversalNoteIdStruct.class); //date type + LIST structure + UNIVERSALNOTEID int valueSize = 2 + 2 + 2 * NotesConstants.timeDateSize; if (PlatformUtils.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = Mem64.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem64.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NOTEREF_LIST); valuePtr = valuePtr.share(2); //LIST structure valuePtr.setShort(0, (short) 1); valuePtr = valuePtr.share(2); struct.write(); valuePtr.write(0, struct.getAdapter(Pointer.class).getByteArray(0, 2*NotesConstants.timeDateSize), 0, 2*NotesConstants.timeDateSize); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NOTEREF_LIST, (int) rethItem.getValue(), valueSize); return item; } finally { Mem64.OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = Mem32.OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = Mem32.OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NOTEREF_LIST); valuePtr = valuePtr.share(2); //LIST structure valuePtr.setShort(0, (short) 1); valuePtr = valuePtr.share(2); struct.write(); valuePtr.write(0, struct.getAdapter(Pointer.class).getByteArray(0, 2*NotesConstants.timeDateSize), 0, 2*NotesConstants.timeDateSize); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NOTEREF_LIST, (int) rethItem.getValue(), valueSize); return item; } finally { Mem32.OSUnlockObject(rethItem.getValue()); } } } else { throw new IllegalArgumentException("Unsupported value type: "+(value==null ? "null" : value.getClass().getName())); } } private List<?> toNumberOrNumberArrayList(List<?> list) { boolean allNumbers = true; for (int i=0; i<list.size(); i++) { if (!(list.get(i) instanceof double[]) && !(list.get(i) instanceof Double)) { allNumbers = false; break; } } if (allNumbers) return (List<?>) list; List convertedList = new ArrayList(); for (int i=0; i<list.size(); i++) { if (list.get(i) instanceof Number) { convertedList.add(((Number)list.get(i)).doubleValue()); } else if (list.get(i) instanceof double[]) { if (((double[])list.get(i)).length!=2) { throw new IllegalArgumentException("Length of double array entry must be 2 for number ranges"); } convertedList.add((double[]) list.get(i)); } else if (list.get(i) instanceof Number[]) { Number[] numberArr = (Number[]) list.get(i); if (numberArr.length!=2) { throw new IllegalArgumentException("Length of Number array entry must be 2 for number ranges"); } convertedList.add(new double[] { numberArr[0].doubleValue(), numberArr[1].doubleValue() }); } else if (list.get(i) instanceof Double[]) { Double[] doubleArr = (Double[]) list.get(i); if (doubleArr.length!=2) { throw new IllegalArgumentException("Length of Number array entry must be 2 for number ranges"); } convertedList.add(new double[] { doubleArr[0], doubleArr[1] }); } else if (list.get(i) instanceof Integer[]) { Integer[] integerArr = (Integer[]) list.get(i); if (integerArr.length!=2) { throw new IllegalArgumentException("Length of Integer array entry must be 2 for number ranges"); } convertedList.add(new double[] { integerArr[0].doubleValue(), integerArr[1].doubleValue() }); } else if (list.get(i) instanceof Long[]) { Long[] longArr = (Long[]) list.get(i); if (longArr.length!=2) { throw new IllegalArgumentException("Length of Long array entry must be 2 for number ranges"); } convertedList.add(new double[] { longArr[0].doubleValue(), longArr[1].doubleValue() }); } else if (list.get(i) instanceof Float[]) { Float[] floatArr = (Float[]) list.get(i); if (floatArr.length!=2) { throw new IllegalArgumentException("Length of Float array entry must be 2 for number ranges"); } convertedList.add(new double[] { floatArr[0].doubleValue(), floatArr[1].doubleValue() }); } else if (list.get(i) instanceof int[]) { int[] intArr = (int[]) list.get(i); if (intArr.length!=2) { throw new IllegalArgumentException("Length of int array entry must be 2 for number ranges"); } convertedList.add(new double[] { intArr[0], intArr[1] }); } else if (list.get(i) instanceof long[]) { long[] longArr = (long[]) list.get(i); if (longArr.length!=2) { throw new IllegalArgumentException("Length of long array entry must be 2 for number ranges"); } convertedList.add(new double[] { longArr[0], longArr[1] }); } else if (list.get(i) instanceof float[]) { float[] floatArr = (float[]) list.get(i); if (floatArr.length!=2) { throw new IllegalArgumentException("Length of float array entry must be 2 for number ranges"); } convertedList.add(new double[] { floatArr[0], floatArr[1] }); } else { throw new IllegalArgumentException("Unsupported date format found in list: "+(list.get(i)==null ? "null" : list.get(i).getClass().getName())); } } return convertedList; } private List<?> toCalendarOrCalendarArrayList(List<?> list) { boolean allCalendar = true; for (int i=0; i<list.size(); i++) { if (!(list.get(i) instanceof Calendar[]) && !(list.get(i) instanceof Calendar)) { allCalendar = false; break; } } if (allCalendar) return (List<?>) list; List convertedList = new ArrayList(); for (int i=0; i<list.size(); i++) { if (list.get(i) instanceof Calendar) { convertedList.add(list.get(i)); } else if (list.get(i) instanceof Calendar[]) { convertedList.add((Calendar[]) list.get(i)); } else if (list.get(i) instanceof Date) { Calendar cal = Calendar.getInstance(); cal.setTime((Date) list.get(i)); convertedList.add(cal); } else if (list.get(i) instanceof NotesTimeDate) { Calendar cal = ((NotesTimeDate)list.get(i)).toCalendar(); convertedList.add(cal); } else if (list.get(i) instanceof Date[]) { Date[] dateArr = (Date[]) list.get(i); if (dateArr.length!=2) { throw new IllegalArgumentException("Length of Date array entry must be 2 for date ranges"); } Calendar val1 = Calendar.getInstance(); val1.setTime(dateArr[0]); Calendar val2 = Calendar.getInstance(); val2.setTime(dateArr[1]); convertedList.add(new Calendar[] {val1, val2}); } else if (list.get(i) instanceof NotesTimeDate[]) { NotesTimeDate[] ntdArr = (NotesTimeDate[]) list.get(i); if (ntdArr.length!=2) { throw new IllegalArgumentException("Length of NotesTimeDate array entry must be 2 for date ranges"); } Calendar val1 = ntdArr[0].toCalendar(); Calendar val2 = ntdArr[1].toCalendar(); convertedList.add(new Calendar[] {val1, val2}); } else { throw new IllegalArgumentException("Unsupported date format found in list: "+(list.get(i)==null ? "null" : list.get(i).getClass().getName())); } } return convertedList; } private boolean isStringList(List<?> list) { if (list==null || list.isEmpty()) { return false; } for (int i=0; i<list.size(); i++) { if (!(list.get(i) instanceof String)) { return false; } } return true; } private boolean isCalendarOrCalendarArrayList(List<?> list) { if (list==null || list.isEmpty()) { return false; } for (int i=0; i<list.size(); i++) { boolean isAccepted=false; Object currObj = list.get(i); if (currObj instanceof Calendar[]) { Calendar[] calArr = (Calendar[]) currObj; if (calArr.length==2) { isAccepted = true; } } else if (currObj instanceof Date[]) { Date[] dateArr = (Date[]) currObj; if (dateArr.length==2) { isAccepted = true; } } else if (currObj instanceof NotesTimeDate[]) { NotesTimeDate[] ndtArr = (NotesTimeDate[]) currObj; if (ndtArr.length==2) { isAccepted = true; } } else if (currObj instanceof Calendar) { isAccepted = true; } else if (currObj instanceof Date) { isAccepted = true; } else if (currObj instanceof NotesTimeDate) { isAccepted = true; } if (!isAccepted) { return false; } } return true; } private boolean isNumberOrNumberArrayList(List<?> list) { if (list==null || list.isEmpty()) { return false; } for (int i=0; i<list.size(); i++) { boolean isAccepted=false; Object currObj = list.get(i); if (currObj instanceof double[]) { double[] valArr = (double[]) currObj; if (valArr.length==2) { isAccepted = true; } } if (currObj instanceof int[]) { int[] valArr = (int[]) currObj; if (valArr.length==2) { isAccepted = true; } } if (currObj instanceof long[]) { long[] valArr = (long[]) currObj; if (valArr.length==2) { isAccepted = true; } } if (currObj instanceof float[]) { float[] valArr = (float[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Number[]) { Number[] valArr = (Number[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Integer[]) { Integer[] valArr = (Integer[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Long[]) { Long[] valArr = (Long[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Double[]) { Double[] valArr = (Double[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Float[]) { Float[] valArr = (Float[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Number) { isAccepted = true; } if (!isAccepted) { return false; } } return true; } /** * Internal method that calls the C API method to write the item * * @param itemName item name * @param flags item flags * @param itemType item type * @param hItemValue handle to memory block with item value * @param valueLength length of binary item value (without data type short) */ private NotesItem appendItemValue(String itemName, EnumSet<ItemType> flags, int itemType, int hItemValue, int valueLength) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); short flagsShort = ItemType.toBitMask(flags); NotesBlockIdStruct.ByValue valueBlockIdByVal = NotesBlockIdStruct.ByValue.newInstance(); valueBlockIdByVal.pool = hItemValue; valueBlockIdByVal.block = 0; valueBlockIdByVal.write(); NotesBlockIdStruct retItemBlockId = NotesBlockIdStruct.newInstance(); retItemBlockId.pool = 0; retItemBlockId.block = 0; retItemBlockId.write(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFItemAppendByBLOCKID(m_hNote64, flagsShort, itemNameMem, (short) (itemNameMem==null ? 0 : itemNameMem.size()), valueBlockIdByVal, valueLength, retItemBlockId); } else { result = NotesNativeAPI32.get().NSFItemAppendByBLOCKID(m_hNote32, flagsShort, itemNameMem, (short) (itemNameMem==null ? 0 : itemNameMem.size()), valueBlockIdByVal, valueLength, retItemBlockId); } NotesErrorUtils.checkResult(result); NotesItem item = new NotesItem(this, retItemBlockId, itemType, valueBlockIdByVal); return item; } /** * This function signs a document by creating a unique electronic signature and appending this * signature to the note.<br> * <br> * A signature constitutes proof of the user's identity and serves to assure the reader that * the user was the real author of the document.<br> * <br> * The signature is derived from the User ID. A signature item has data type {@link NotesItem#TYPE_SIGNATURE} * and item flags {@link NotesConstants#ITEM_SEAL}. The data value of the signature item is a digest * of the data stored in items in the note, signed with the user's private key.<br> * <br> * This method signs entire document. It creates a digest of all the items in the note, and * appends a signature item with field name $Signature (ITEM_NAME_NOTE_SIGNATURE).<br> * <br> * If the document to be signed is encrypted, this function will attempt to decrypt the * document in order to generate a valid signature.<br> * If you want the document to be signed and encrypted, you must sign the document * {@link #copyAndEncrypt(NotesUserId, EnumSet)}.<br> * <br> * Note: When the Notes user interface opens a note, it always uses the {@link OpenNote#EXPAND} * option to promote items of type number to number list, and items of type text to text list.<br> */ public void sign() { checkHandle(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteExpand(m_hNote64); NotesErrorUtils.checkResult(result); result = NotesNativeAPI64.get().NSFNoteSign(m_hNote64); NotesErrorUtils.checkResult(result); result = NotesNativeAPI64.get().NSFNoteContract(m_hNote64); NotesErrorUtils.checkResult(result); } else { result = NotesNativeAPI32.get().NSFNoteExpand(m_hNote32); NotesErrorUtils.checkResult(result); result = NotesNativeAPI32.get().NSFNoteSign(m_hNote32); NotesErrorUtils.checkResult(result); result = NotesNativeAPI32.get().NSFNoteContract(m_hNote32); NotesErrorUtils.checkResult(result); } } public void sign(NotesUserId id, boolean signNotesIfMimePresent) { checkHandle(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteExpand(m_hNote64); NotesErrorUtils.checkResult(result); result = NotesNativeAPI64.get().NSFNoteSignExt3(m_hNote64, id==null ? 0 : id.getHandle64(), null, NotesConstants.MAXWORD, 0, signNotesIfMimePresent ? NotesConstants.SIGN_NOTES_IF_MIME_PRESENT : 0, 0, null); NotesErrorUtils.checkResult(result); result = NotesNativeAPI64.get().NSFNoteContract(m_hNote64); NotesErrorUtils.checkResult(result); //verify signature NotesTimeDateStruct retWhenSigned = NotesTimeDateStruct.newInstance(); Memory retSigner = new Memory(NotesConstants.MAXUSERNAME); Memory retCertifier = new Memory(NotesConstants.MAXUSERNAME); result = NotesNativeAPI64.get().NSFNoteVerifySignature (m_hNote64, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); } else { result = NotesNativeAPI32.get().NSFNoteExpand(m_hNote32); NotesErrorUtils.checkResult(result); result = NotesNativeAPI32.get().NSFNoteSignExt3(m_hNote32, id==null ? 0 : id.getHandle32(), null, NotesConstants.MAXWORD, 0, signNotesIfMimePresent ? NotesConstants.SIGN_NOTES_IF_MIME_PRESENT : 0, 0, null); NotesErrorUtils.checkResult(result); result = NotesNativeAPI32.get().NSFNoteContract(m_hNote32); NotesErrorUtils.checkResult(result); //verify signature NotesTimeDateStruct retWhenSigned = NotesTimeDateStruct.newInstance(); Memory retSigner = new Memory(NotesConstants.MAXUSERNAME); Memory retCertifier = new Memory(NotesConstants.MAXUSERNAME); result = NotesNativeAPI32.get().NSFNoteVerifySignature (m_hNote32, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); } } /** * This function will sign all hotspots in a document that contain object code.<br> * <br> * Using the current ID, signature data will be added to any signature containing CD * records for hotspots having code within TYPE_COMPOSITE items.<br> * <br> * This routine only operates on documents.<br> * If the note is a design element, the routine returns without signing anything. * * @return true if any hotspots are signed */ public boolean signHotSpots() { checkHandle(); IntByReference retfSigned = new IntByReference(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteSignHotspots(m_hNote64, 0, retfSigned); } else { result = NotesNativeAPI32.get().NSFNoteSignHotspots(m_hNote32, 0, retfSigned); } NotesErrorUtils.checkResult(result); return retfSigned.getValue() == 1; } /** * Container for note signature data * * @author Karsten Lehmann */ public static class SignatureData { private NotesTimeDate m_whenSigned; private String m_signer; private String m_certifier; private SignatureData(NotesTimeDate whenSigned, String signer, String certifier) { m_whenSigned = whenSigned; m_signer = signer; m_certifier = certifier; } public NotesTimeDate getWhenSigned() { return m_whenSigned; } public String getSigner() { return m_signer; } public String getCertifier() { return m_certifier; } } /** * Returns the signer of a note * * @return signer or empty string if not signed */ public String getSigner() { try { SignatureData signatureData = verifySignature(); return signatureData.getSigner(); } catch (NotesError e) { if (e.getId()==INotesErrorConstants.ERR_NOTE_NOT_SIGNED) { return ""; } else { throw e; } } } /** * This function verifies a signature on a note or section(s) within a note.<br> * It returns an error if a signature did not verify.<br> * <br> * @return signer data */ public SignatureData verifySignature() { checkHandle(); NotesTimeDateStruct retWhenSigned = NotesTimeDateStruct.newInstance(); Memory retSigner = new Memory(NotesConstants.MAXUSERNAME); Memory retCertifier = new Memory(NotesConstants.MAXUSERNAME); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFNoteExpand(m_hNote64); NotesErrorUtils.checkResult(result); result = NotesNativeAPI64.get().NSFNoteVerifySignature (m_hNote64, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); result = NotesNativeAPI64.get().NSFNoteContract(m_hNote64); NotesErrorUtils.checkResult(result); } else { result = NotesNativeAPI32.get().NSFNoteExpand(m_hNote32); NotesErrorUtils.checkResult(result); result = NotesNativeAPI32.get().NSFNoteVerifySignature (m_hNote32, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); result = NotesNativeAPI32.get().NSFNoteContract(m_hNote32); NotesErrorUtils.checkResult(result); } String signer = NotesStringUtils.fromLMBCS(retSigner, NotesStringUtils.getNullTerminatedLength(retSigner)); String certifier = NotesStringUtils.fromLMBCS(retCertifier, NotesStringUtils.getNullTerminatedLength(retCertifier)); SignatureData data = new SignatureData(new NotesTimeDate(retWhenSigned), signer, certifier); return data; } /** * Creates/overwrites a $REF item pointing to another {@link NotesNote} * * @param note $REF target note */ public void makeResponse(NotesNote note) { makeResponse(note.getUNID()); } /** * Creates/overwrites a $REF item pointing to a UNID * * @param targetUnid $REF target UNID */ public void makeResponse(String targetUnid) { replaceItemValue("$REF", EnumSet.of(ItemType.SUMMARY), new NotesUniversalNoteId(targetUnid)); } /** * Callback interface that receives data of images embedded in a HTML conversion result * * @author Karsten Lehmann */ public static interface IHtmlItemImageConversionCallback { public static enum Action {Continue, Stop}; /** * Reports the size of the image * * @param size size * @return return how many bytes to skip before reading */ public int setSize(int size); /** * Implement this method to receive element data * * @param data data * @return action, either Continue or Stop */ public Action read(byte[] data); } public enum HtmlConvertOption { ForceSectionExpand, RowAtATimeTableAlt, ForceOutlineExpand; public static String[] toStringArray(EnumSet<HtmlConvertOption> options) { List<String> optionsAsStrList = new ArrayList<String>(options.size()); for (HtmlConvertOption currOption : options) { optionsAsStrList.add(currOption.toString()+"=1"); } return optionsAsStrList.toArray(new String[optionsAsStrList.size()]); } } /** * Convenience method to read the binary data of a {@link IHtmlImageRef} * * @param image image reference * @param callback callback to receive the data */ public void convertHtmlElement(IHtmlImageRef image, IHtmlItemImageConversionCallback callback) { String itemName = image.getItemName(); int itemIndex = image.getItemIndex(); int itemOffset = image.getItemOffset(); EnumSet<HtmlConvertOption> options = image.getOptions(); convertHtmlElement(itemName, options, itemIndex, itemOffset, callback); } /** * Method to access images embedded in HTML conversion result. Compute index and offset parameters * from the img tag path like this: 1.3E =&gt; index=1, offset=63 * * @param itemName rich text field which is being converted * @param options conversion options * @param itemIndex the relative item index -- if there is more than one, Item with the same pszItemName, then this indicates which one (zero relative) * @param itemOffset byte offset in the Item where the element starts * @param callback callback to receive the data */ public void convertHtmlElement(String itemName, EnumSet<HtmlConvertOption> options, int itemIndex, int itemOffset, IHtmlItemImageConversionCallback callback) { checkHandle(); LongByReference phHTML64 = new LongByReference(); IntByReference phHTML32 = new IntByReference(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLCreateConverter(phHTML64); } else { result = NotesNativeAPI32.get().HTMLCreateConverter(phHTML32); } NotesErrorUtils.checkResult(result); long hHTML64 = phHTML64.getValue(); int hHTML32 = phHTML32.getValue(); try { if (!options.isEmpty()) { if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLSetHTMLOptions(hHTML64, new StringArray(HtmlConvertOption.toStringArray(options))); } else { result = NotesNativeAPI32.get().HTMLSetHTMLOptions(hHTML32, new StringArray(HtmlConvertOption.toStringArray(options))); } NotesErrorUtils.checkResult(result); } Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); int totalLen; int skip; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLConvertElement(hHTML64, getParent().getHandle64(), m_hNote64, itemNameMem, itemIndex, itemOffset); NotesErrorUtils.checkResult(result); Memory tLenMem = new Memory(4); result = NotesNativeAPI64.get().HTMLGetProperty(hHTML64, (long) NotesConstants.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); skip = callback.setSize(totalLen); } else { result = NotesNativeAPI32.get().HTMLConvertElement(hHTML32, getParent().getHandle32(), m_hNote32, itemNameMem, itemIndex, itemOffset); NotesErrorUtils.checkResult(result); Memory tLenMem = new Memory(4); result = NotesNativeAPI32.get().HTMLGetProperty(hHTML32, (int) NotesConstants.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); skip = callback.setSize(totalLen); } if (skip > totalLen) throw new IllegalArgumentException("Skip value cannot be greater than size: "+skip+" > "+totalLen); IntByReference len = new IntByReference(); len.setValue(NotesConstants.MAXPATH); int startOffset=skip; Memory bufMem = new Memory(NotesConstants.MAXPATH+1); while (result==0 && len.getValue()>0 && startOffset<totalLen) { len.setValue(NotesConstants.MAXPATH); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLGetText(hHTML64, startOffset, len, bufMem); } else { result = NotesNativeAPI32.get().HTMLGetText(hHTML32, startOffset, len, bufMem); } NotesErrorUtils.checkResult(result); byte[] data = bufMem.getByteArray(0, len.getValue()); IHtmlItemImageConversionCallback.Action action = callback.read(data); if (action == IHtmlItemImageConversionCallback.Action.Stop) break; startOffset += len.getValue(); } } finally { if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLDestroyConverter(hHTML64); } else { result = NotesNativeAPI32.get().HTMLDestroyConverter(hHTML32); } NotesErrorUtils.checkResult(result); } } /** * Method to convert the whole note to HTML * * @param options conversion options * @return conversion result */ public IHtmlConversionResult convertNoteToHtml(EnumSet<HtmlConvertOption> options) { return convertNoteToHtml(options, (EnumSet<ReferenceType>) null, (Map<ReferenceType,EnumSet<TargetType>>) null); } /** * Method to convert the whole note to HTML with additional filters for the * data returned in the conversion result * * @param options conversion options * @param refTypeFilter optional filter for ref types to be returned or null for no filter * @param targetTypeFilter optional filter for target types to be returned or null for no filter * @return conversion result */ public IHtmlConversionResult convertNoteToHtml(EnumSet<HtmlConvertOption> options, EnumSet<ReferenceType> refTypeFilter, Map<ReferenceType,EnumSet<TargetType>> targetTypeFilter) { return internalConvertItemToHtml(null, options, refTypeFilter, targetTypeFilter); } /** * Method to convert a single item of this note to HTML * * @param itemName item name * @param options conversion options * @return conversion result */ public IHtmlConversionResult convertItemToHtml(String itemName, EnumSet<HtmlConvertOption> options) { return convertItemToHtml(itemName, options, (EnumSet<ReferenceType>) null, (Map<ReferenceType,EnumSet<TargetType>>) null); } /** * Method to convert a single item of this note to HTML with additional filters for the * data returned in the conversion result * * @param itemName item name * @param options conversion options * @param refTypeFilter optional filter for ref types to be returned or null for no filter * @param targetTypeFilter optional filter for target types to be returned or null for no filter * @return conversion result */ public IHtmlConversionResult convertItemToHtml(String itemName, EnumSet<HtmlConvertOption> options, EnumSet<ReferenceType> refTypeFilter, Map<ReferenceType,EnumSet<TargetType>> targetTypeFilter) { if (StringUtil.isEmpty(itemName)) throw new NullPointerException("Item name cannot be null"); return internalConvertItemToHtml(itemName, options, refTypeFilter, targetTypeFilter); } /** * Implementation of {@link IHtmlConversionResult} that contains the HTML conversion result * * @author Karsten Lehmann */ private class HtmlConversionResult implements IHtmlConversionResult { private String m_html; private List<IHtmlApiReference> m_references; private EnumSet<HtmlConvertOption> m_options; private HtmlConversionResult(String html, List<IHtmlApiReference> references, EnumSet<HtmlConvertOption> options) { m_html = html; m_references = references; m_options = options; } @Override public String getText() { return m_html; } @Override public List<IHtmlApiReference> getReferences() { return m_references; } private IHtmlImageRef createImageRef(final String refText, final String fieldName, final int itemIndex, final int itemOffset, final String format) { return new IHtmlImageRef() { @Override public void readImage(IHtmlItemImageConversionCallback callback) { NotesNote.this.convertHtmlElement(this, callback); } @Override public void writeImage(File f) throws IOException { if (f.exists() && !f.delete()) throw new IOException("Cannot delete existing file "+f.getAbsolutePath()); final FileOutputStream fOut = new FileOutputStream(f); final IOException[] ex = new IOException[1]; try { NotesNote.this.convertHtmlElement(this, new IHtmlItemImageConversionCallback() { @Override public int setSize(int size) { return 0; } @Override public Action read(byte[] data) { try { fOut.write(data); return Action.Continue; } catch (IOException e) { ex[0] = e; return Action.Stop; } } }); if (ex[0]!=null) throw ex[0]; } finally { fOut.close(); } } @Override public void writeImage(final OutputStream out) throws IOException { final IOException[] ex = new IOException[1]; NotesNote.this.convertHtmlElement(this, new IHtmlItemImageConversionCallback() { @Override public int setSize(int size) { return 0; } @Override public Action read(byte[] data) { try { out.write(data); return Action.Continue; } catch (IOException e) { ex[0] = e; return Action.Stop; } } }); if (ex[0]!=null) throw ex[0]; out.flush(); } @Override public String getReferenceText() { return refText; } @Override public EnumSet<HtmlConvertOption> getOptions() { return m_options; } @Override public int getItemOffset() { return itemOffset; } @Override public String getItemName() { return fieldName; } @Override public int getItemIndex() { return itemIndex; } @Override public String getFormat() { return format; } }; } public java.util.List<com.mindoo.domino.jna.html.IHtmlImageRef> getImages() { List<IHtmlImageRef> imageRefs = new ArrayList<IHtmlImageRef>(); for (IHtmlApiReference currRef : m_references) { if (currRef.getType() == ReferenceType.IMG) { String refText = currRef.getReferenceText(); String format = "gif"; int iFormatPos = refText.indexOf("FieldElemFormat="); if (iFormatPos!=-1) { String remainder = refText.substring(iFormatPos + "FieldElemFormat=".length()); int iNextDelim = remainder.indexOf('&'); if (iNextDelim==-1) { format = remainder; } else { format = remainder.substring(0, iNextDelim); } } IHtmlApiUrlTargetComponent<?> fieldOffsetTarget = currRef.getTargetByType(TargetType.FIELDOFFSET); if (fieldOffsetTarget!=null) { Object fieldOffsetObj = fieldOffsetTarget.getValue(); if (fieldOffsetObj instanceof String) { String fieldOffset = (String) fieldOffsetObj; // 1.3E -> index=1, offset=63 int iPos = fieldOffset.indexOf('.'); if (iPos!=-1) { String indexStr = fieldOffset.substring(0, iPos); String offsetStr = fieldOffset.substring(iPos+1); int itemIndex = Integer.parseInt(indexStr, 16); int itemOffset = Integer.parseInt(offsetStr, 16); IHtmlApiUrlTargetComponent<?> fieldTarget = currRef.getTargetByType(TargetType.FIELD); if (fieldTarget!=null) { Object fieldNameObj = fieldTarget.getValue(); String fieldName = (fieldNameObj instanceof String) ? (String) fieldNameObj : null; IHtmlImageRef newImgRef = createImageRef(refText, fieldName, itemIndex, itemOffset, format); imageRefs.add(newImgRef); } } } } } } return imageRefs; }; } private static class HTMLApiReference implements IHtmlApiReference { private ReferenceType m_type; private String m_refText; private String m_fragment; private CommandId m_commandId; private List<IHtmlApiUrlTargetComponent<?>> m_targets; private Map<TargetType, IHtmlApiUrlTargetComponent<?>> m_targetByType; private HTMLApiReference(ReferenceType type, String refText, String fragment, CommandId commandId, List<IHtmlApiUrlTargetComponent<?>> targets) { m_type = type; m_refText = refText; m_fragment = fragment; m_commandId = commandId; m_targets = targets; } @Override public ReferenceType getType() { return m_type; } @Override public String getReferenceText() { return m_refText; } @Override public String getFragment() { return m_fragment; } @Override public CommandId getCommandId() { return m_commandId; } @Override public List<IHtmlApiUrlTargetComponent<?>> getTargets() { return m_targets; } @Override public IHtmlApiUrlTargetComponent<?> getTargetByType(TargetType type) { if (m_targetByType==null) { m_targetByType = new HashMap<TargetType, IHtmlApiUrlTargetComponent<?>>(); if (m_targets!=null && !m_targets.isEmpty()) { for (IHtmlApiUrlTargetComponent<?> currTarget : m_targets) { m_targetByType.put(currTarget.getType(), currTarget); } } } return m_targetByType.get(type); } } private static class HtmlApiUrlTargetComponent<T> implements IHtmlApiUrlTargetComponent<T> { private TargetType m_type; private Class<T> m_valueClazz; private T m_value; private HtmlApiUrlTargetComponent(TargetType type, Class<T> valueClazz, T value) { m_type = type; m_valueClazz = valueClazz; m_value = value; } @Override public TargetType getType() { return m_type; } @Override public Class<T> getValueClass() { return m_valueClazz; } @Override public T getValue() { return m_value; } } /** * Internal method doing the HTML conversion work * * @param itemName item name to be converted or null for whole note * @param options conversion options * @param refTypeFilter optional filter for ref types to be returned or null for no filter * @param targetTypeFilter optional filter for target types to be returned or null for no filter * @return conversion result */ private IHtmlConversionResult internalConvertItemToHtml(String itemName, EnumSet<HtmlConvertOption> options, EnumSet<ReferenceType> refTypeFilter, Map<ReferenceType,EnumSet<TargetType>> targetTypeFilter) { checkHandle(); LongByReference phHTML64 = new LongByReference(); phHTML64.setValue(0); IntByReference phHTML32 = new IntByReference(); phHTML32.setValue(0); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLCreateConverter(phHTML64); } else { result = NotesNativeAPI32.get().HTMLCreateConverter(phHTML32); } NotesErrorUtils.checkResult(result); long hHTML64 = phHTML64.getValue(); int hHTML32 = phHTML32.getValue(); try { if (!options.isEmpty()) { if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLSetHTMLOptions(hHTML64, new StringArray(HtmlConvertOption.toStringArray(options))); } else { result = NotesNativeAPI32.get().HTMLSetHTMLOptions(hHTML32, new StringArray(HtmlConvertOption.toStringArray(options))); } NotesErrorUtils.checkResult(result); } Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); int totalLen; if (PlatformUtils.is64Bit()) { if (itemName==null) { result = NotesNativeAPI64.get().HTMLConvertNote(hHTML64, getParent().getHandle64(), m_hNote64, 0, null); NotesErrorUtils.checkResult(result); } else { result = NotesNativeAPI64.get().HTMLConvertItem(hHTML64, getParent().getHandle64(), m_hNote64, itemNameMem); NotesErrorUtils.checkResult(result); } Memory tLenMem = new Memory(4); result = NotesNativeAPI64.get().HTMLGetProperty(hHTML64, (long) NotesConstants.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); } else { if (itemName==null) { result = NotesNativeAPI32.get().HTMLConvertNote(hHTML32, getParent().getHandle32(), m_hNote32, 0, null); NotesErrorUtils.checkResult(result); } else { result = NotesNativeAPI32.get().HTMLConvertItem(hHTML32, getParent().getHandle32(), m_hNote32, itemNameMem); NotesErrorUtils.checkResult(result); } Memory tLenMem = new Memory(4); result = NotesNativeAPI32.get().HTMLGetProperty(hHTML32, NotesConstants.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); } IntByReference len = new IntByReference(); len.setValue(NotesConstants.MAXPATH); int startOffset=0; Memory textMem = new Memory(NotesConstants.MAXPATH+1); ByteArrayOutputStream htmlTextLMBCSOut = new ByteArrayOutputStream(); while (result==0 && len.getValue()>0 && startOffset<totalLen) { len.setValue(NotesConstants.MAXPATH); textMem.setByte(0, (byte) 0); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLGetText(hHTML64, startOffset, len, textMem); } else { result = NotesNativeAPI32.get().HTMLGetText(hHTML32, startOffset, len, textMem); } NotesErrorUtils.checkResult(result); if (result == 0) { byte[] byteArr = textMem.getByteArray(0, len.getValue()); try { htmlTextLMBCSOut.write(byteArr); } catch (IOException e) { throw new NotesError(0, "Unexpected write error", e); } startOffset += len.getValue(); } } String htmlText = NotesStringUtils.fromLMBCS(htmlTextLMBCSOut.toByteArray()); Memory refCount = new Memory(4); if (PlatformUtils.is64Bit()) { result=NotesNativeAPI64.get().HTMLGetProperty(hHTML64, NotesConstants.HTMLAPI_PROP_NUMREFS, refCount); } else { result=NotesNativeAPI32.get().HTMLGetProperty(hHTML32, NotesConstants.HTMLAPI_PROP_NUMREFS, refCount); } NotesErrorUtils.checkResult(result); int iRefCount = refCount.getInt(0); List<IHtmlApiReference> references = new ArrayList<IHtmlApiReference>(); for (int i=0; i<iRefCount; i++) { LongByReference phRef64 = new LongByReference(); phRef64.setValue(0); IntByReference phRef32 = new IntByReference(); phRef32.setValue(0); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLGetReference(hHTML64, i, phRef64); } else { result = NotesNativeAPI32.get().HTMLGetReference(hHTML32, i, phRef32); } NotesErrorUtils.checkResult(result); Memory ppRef = new Memory(Pointer.SIZE); long hRef64 = phRef64.getValue(); int hRef32 = phRef32.getValue(); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().HTMLLockAndFixupReference(hRef64, ppRef); } else { result = NotesNativeAPI32.get().HTMLLockAndFixupReference(hRef32, ppRef); } NotesErrorUtils.checkResult(result); try { int iRefType; Pointer pRefText; Pointer pFragment; int iCmdId; int nTargets; Pointer pTargets; //use separate structs for 64/32, because RefType uses 8 bytes on 64 and 4 bytes on 32 bit if (PlatformUtils.is64Bit()) { HTMLAPIReference64Struct htmlApiRef = HTMLAPIReference64Struct.newInstance(ppRef.getPointer(0)); htmlApiRef.read(); iRefType = (int) htmlApiRef.RefType; pRefText = htmlApiRef.pRefText; pFragment = htmlApiRef.pFragment; iCmdId = (int) htmlApiRef.CommandId; nTargets = htmlApiRef.NumTargets; pTargets = htmlApiRef.pTargets; } else { HTMLAPIReference32Struct htmlApiRef = HTMLAPIReference32Struct.newInstance(ppRef.getPointer(0)); htmlApiRef.read(); iRefType = htmlApiRef.RefType; pRefText = htmlApiRef.pRefText; pFragment = htmlApiRef.pFragment; iCmdId = htmlApiRef.CommandId; nTargets = htmlApiRef.NumTargets; pTargets = htmlApiRef.pTargets; } ReferenceType refType = ReferenceType.getType((int) iRefType); if (refTypeFilter==null || refTypeFilter.contains(refType)) { String refText = NotesStringUtils.fromLMBCS(pRefText, -1); String fragment = NotesStringUtils.fromLMBCS(pFragment, -1); CommandId cmdId = CommandId.getCommandId(iCmdId); List<IHtmlApiUrlTargetComponent<?>> targets = new ArrayList<IHtmlApiUrlTargetComponent<?>>(nTargets); for (int t=0; t<nTargets; t++) { Pointer pCurrTarget = pTargets.share(t * NotesConstants.htmlApiUrlComponentSize); HtmlApi_UrlTargetComponentStruct currTarget = HtmlApi_UrlTargetComponentStruct.newInstance(pCurrTarget); currTarget.read(); int iTargetType = currTarget.AddressableType; TargetType targetType = TargetType.getType(iTargetType); EnumSet<TargetType> targetTypeFilterForRefType = targetTypeFilter==null ? null : targetTypeFilter.get(refType); if (targetTypeFilterForRefType==null || targetTypeFilterForRefType.contains(targetType)) { switch (currTarget.ReferenceType) { case NotesConstants.URT_Name: currTarget.Value.setType(Pointer.class); currTarget.Value.read(); String name = NotesStringUtils.fromLMBCS(currTarget.Value.name, -1); targets.add(new HtmlApiUrlTargetComponent(targetType, String.class, name)); break; case NotesConstants.URT_NoteId: currTarget.Value.setType(NoteIdStruct.class); currTarget.Value.read(); NoteIdStruct noteIdStruct = currTarget.Value.nid; int iNoteId = noteIdStruct.nid; targets.add(new HtmlApiUrlTargetComponent(targetType, Integer.class, iNoteId)); break; case NotesConstants.URT_Unid: currTarget.Value.setType(NotesUniversalNoteIdStruct.class); currTarget.Value.read(); NotesUniversalNoteIdStruct unidStruct = currTarget.Value.unid; unidStruct.read(); String unid = unidStruct.toString(); targets.add(new HtmlApiUrlTargetComponent(targetType, String.class, unid)); break; case NotesConstants.URT_None: targets.add(new HtmlApiUrlTargetComponent(targetType, Object.class, null)); break; case NotesConstants.URT_RepId: //TODO find out how to decode this one break; case NotesConstants.URT_Special: //TODO find out how to decode this one break; } } } IHtmlApiReference newRef = new HTMLApiReference(refType, refText, fragment, cmdId, targets); references.add(newRef); } } finally { if (PlatformUtils.is64Bit()) { if (hRef64!=0) { Mem64.OSMemoryUnlock(hRef64); Mem64.OSMemoryFree(hRef64); } } else { if (hRef32!=0) { Mem32.OSMemoryUnlock(hRef32); Mem32.OSMemoryFree(hRef32); } } } } return new HtmlConversionResult(htmlText, references, options); } finally { if (PlatformUtils.is64Bit()) { if (hHTML64!=0) { result = NotesNativeAPI64.get().HTMLDestroyConverter(hHTML64); } } else { if (hHTML32!=0) { result = NotesNativeAPI32.get().HTMLDestroyConverter(hHTML32); } } NotesErrorUtils.checkResult(result); } } /** * Applies one of multiple conversions to a richtext item * * @param itemName richtext item name * @param conversions conversions, processed from left to right * @return true if richtext has been updated, false if all conversion classes returned {@link IRichTextConversion#isMatch(IRichTextNavigator)} as false */ public boolean convertRichTextItem(String itemName, IRichTextConversion... conversions) { return convertRichTextItem(itemName, this, itemName, conversions); } /** * Applies one of multiple conversions to a richtext item * * @param itemName richtext item name * @param targetNote note to copy to conversion result to * @param targetItemName item name in target note where we should save the conversion result * @param conversions conversions, processed from left to right * @return true if richtext has been updated, false if all conversion classes returned {@link IRichTextConversion#isMatch(IRichTextNavigator)} as false */ public boolean convertRichTextItem(String itemName, NotesNote targetNote, String targetItemName, IRichTextConversion... conversions) { checkHandle(); if (conversions==null || conversions.length==0) return false; IRichTextNavigator navFromNote = getRichtextNavigator(itemName); IRichTextNavigator currNav = navFromNote; StandaloneRichText tmpRichText = null; for (int i=0; i<conversions.length; i++) { IRichTextConversion currConversion = conversions[i]; if (currConversion.isMatch(currNav)) { tmpRichText = new StandaloneRichText(); currConversion.convert(currNav, tmpRichText); IRichTextNavigator nextNav = tmpRichText.closeAndGetRichTextNavigator(); currNav = nextNav; } } if (tmpRichText!=null) { tmpRichText.closeAndCopyToNote(targetNote, targetItemName); return true; } else { return false; } } /** * This function can be used to create basic richtext content. It uses C API methods to create * "CompoundText", which provide some high-level methods for richtext creation, e.g. * to add text, doclinks, render notes as richtext or append other richtext items.<br> * <br> * <b>After calling the available methods in the returned {@link RichTextBuilder}, you must * call {@link RichTextBuilder#close()} to write your changes into the note. Otherwise * it is discarded.</b> * * @param itemName item name * @return richtext builder */ public RichTextBuilder createRichTextItem(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); short result; if (PlatformUtils.is64Bit()) { LongByReference rethCompound = new LongByReference(); result = NotesNativeAPI64.get().CompoundTextCreate(m_hNote64, itemNameMem, rethCompound); NotesErrorUtils.checkResult(result); long hCompound = rethCompound.getValue(); CompoundTextWriter ct = new CompoundTextWriter(hCompound, false); NotesGC.__objectCreated(CompoundTextWriter.class, ct); RichTextBuilder rt = new RichTextBuilder(this, ct); return rt; } else { IntByReference rethCompound = new IntByReference(); result = NotesNativeAPI32.get().CompoundTextCreate(m_hNote32, itemNameMem, rethCompound); NotesErrorUtils.checkResult(result); int hCompound = rethCompound.getValue(); CompoundTextWriter ct = new CompoundTextWriter(hCompound, false); NotesGC.__objectCreated(CompoundTextWriter.class, ct); RichTextBuilder rt = new RichTextBuilder(this, ct); return rt; } } private class RichTextNavPositionImpl implements RichTextNavPosition { private MultiItemRichTextNavigator m_parentNav; private int m_itemIndex; private int m_recordIndex; public RichTextNavPositionImpl(MultiItemRichTextNavigator parentNav, int itemIndex, int recordIndex) { m_parentNav = parentNav; m_itemIndex = itemIndex; m_recordIndex = recordIndex; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + m_itemIndex; result = prime * result + ((m_parentNav == null) ? 0 : m_parentNav.hashCode()); result = prime * result + m_recordIndex; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RichTextNavPositionImpl other = (RichTextNavPositionImpl) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (m_itemIndex != other.m_itemIndex) return false; if (m_parentNav == null) { if (other.m_parentNav != null) return false; } else if (!m_parentNav.equals(other.m_parentNav)) return false; if (m_recordIndex != other.m_recordIndex) return false; return true; } private NotesNote getOuterType() { return NotesNote.this; } } /** * Implementation of {@link IRichTextNavigator} to traverse the CD record structure * of a richtext item stored in a {@link NotesNote} and split up into multiple * items of type {@link NotesItem#TYPE_COMPOSITE}. * * @author Karsten Lehmann */ private class MultiItemRichTextNavigator implements IRichTextNavigator { private String m_richTextItemName; private LinkedList<NotesItem> m_items; private int m_currentItemIndex = -1; private LinkedList<CDRecordMemory> m_currentItemRecords; private int m_currentItemRecordsIndex = -1; /** * Creates a new navigator and moves to the first CD record * * @param richTextItemName richtext item name */ public MultiItemRichTextNavigator(String richTextItemName) { m_richTextItemName = richTextItemName; //read items m_items = new LinkedList<NotesItem>(); getItems(richTextItemName, new IItemCallback() { @Override public void itemNotFound() { } @Override public Action itemFound(NotesItem item) { if (item.getType()==NotesItem.TYPE_COMPOSITE) { m_items.add(item); } return Action.Continue; } }); } @Override public RichTextNavPosition getCurrentRecordPosition() { RichTextNavPositionImpl posImpl = new RichTextNavPositionImpl(this, m_currentItemIndex, m_currentItemRecordsIndex); return posImpl; } @Override public void restoreCurrentRecordPosition(RichTextNavPosition pos) { checkHandle(); if (!(pos instanceof RichTextNavPositionImpl)) throw new IllegalArgumentException("Invalid position, not generated by this navigator"); RichTextNavPositionImpl posImpl = (RichTextNavPositionImpl) pos; if (posImpl.m_parentNav!=this) throw new IllegalArgumentException("Invalid position, not generated by this navigator"); int oldItemIndex = m_currentItemIndex; m_currentItemIndex = posImpl.m_itemIndex; m_currentItemRecordsIndex = posImpl.m_recordIndex; if (oldItemIndex!=posImpl.m_itemIndex) { //current item changed, so we need to reload the records NotesItem currItem = m_items.get(m_currentItemIndex); m_currentItemRecords = readCDRecords(currItem); } } @Override public boolean isEmpty() { checkHandle(); if (m_items.isEmpty()) { return true; } else { boolean hasRecords = hasCDRecords(m_items.getFirst()); return !hasRecords; } } @Override public boolean gotoFirst() { checkHandle(); if (isEmpty()) { m_currentItemIndex = -1; m_currentItemRecords = null; m_currentItemRecordsIndex = -1; return false; } else if (m_currentItemRecords==null || m_currentItemIndex!=0) { //move to first item NotesItem firstItem = m_items.getFirst(); m_currentItemRecords = readCDRecords(firstItem); m_currentItemIndex = 0; } //move to first record if (m_currentItemRecords.isEmpty()) { m_currentItemRecordsIndex = -1; return false; } else { m_currentItemRecordsIndex = 0; return true; } } private boolean hasCDRecords(NotesItem item) { final boolean[] hasRecords = new boolean[1]; item.enumerateCDRecords(new ICompositeCallbackDirect() { @Override public ICompositeCallbackDirect.Action recordVisited(Pointer dataPtr, CDRecordType parsedSignature, short signature, int dataLength, Pointer cdRecordPtr, int cdRecordLength) { hasRecords[0] = true; return ICompositeCallbackDirect.Action.Stop; } }); return hasRecords[0]; } /** * Copies all CD records from the specified item * * @param item item * @return list with CD record data */ private LinkedList<CDRecordMemory> readCDRecords(NotesItem item) { final LinkedList<CDRecordMemory> itemRecords = new LinkedList<CDRecordMemory>(); item.enumerateCDRecords(new ICompositeCallbackDirect() { @Override public ICompositeCallbackDirect.Action recordVisited(Pointer dataPtr, CDRecordType parsedSignature, short signature, int dataLength, Pointer cdRecordPtr, int cdRecordLength) { byte[] cdRecordDataArr = cdRecordPtr.getByteArray(0, cdRecordLength); ReadOnlyMemory cdRecordDataCopied = new ReadOnlyMemory(cdRecordLength); cdRecordDataCopied.write(0, cdRecordDataArr, 0, cdRecordLength); cdRecordDataCopied.seal(); CDRecordMemory cdRecordMem = new CDRecordMemory(cdRecordDataCopied, parsedSignature, signature, dataLength, cdRecordLength); itemRecords.add(cdRecordMem); return ICompositeCallbackDirect.Action.Continue; } }); return itemRecords; } @Override public boolean gotoLast() { checkHandle(); if (isEmpty()) { m_currentItemIndex = -1; m_currentItemRecords = null; m_currentItemRecordsIndex = -1; return false; } else if (m_currentItemIndex!=(m_items.size()-1)) { //move to last item NotesItem lastItem = m_items.getLast(); m_currentItemRecords = readCDRecords(lastItem); m_currentItemIndex = m_items.size()-1; } //move to last record if (m_currentItemRecords.isEmpty()) { m_currentItemRecordsIndex = -1; return false; } else { m_currentItemRecordsIndex = m_currentItemRecords.size()-1; return true; } } @Override public boolean gotoNext() { checkHandle(); if (isEmpty()) { m_currentItemIndex = -1; m_currentItemRecords = null; m_currentItemRecordsIndex = -1; return false; } else { if (m_currentItemRecordsIndex==-1) { //offroad? return false; } else if (m_currentItemRecordsIndex<(m_currentItemRecords.size()-1)) { //more records available for current item m_currentItemRecordsIndex++; return true; } else { //move to next item if (m_currentItemIndex==-1) { //offroad? return false; } else if (m_currentItemIndex<(m_items.size()-1)) { //move items available m_currentItemIndex++; NotesItem currItem = m_items.get(m_currentItemIndex); m_currentItemRecords = readCDRecords(currItem); if (m_currentItemRecords.isEmpty()) { m_currentItemRecordsIndex = -1; return false; } else { //more to first record of that item m_currentItemRecordsIndex = 0; return true; } } else { //no more items available return false; } } } } @Override public boolean gotoPrev() { checkHandle(); if (isEmpty()) { m_currentItemIndex = -1; m_currentItemRecords = null; m_currentItemRecordsIndex = -1; return false; } else { if (m_currentItemRecordsIndex==-1) { //offroad? return false; } else if (m_currentItemRecordsIndex>0) { //more records available for current item m_currentItemRecordsIndex return true; } else { //move to prev item if (m_currentItemIndex==-1) { //offroad? return false; } else if (m_currentItemIndex>0) { //move items available m_currentItemIndex NotesItem currItem = m_items.get(m_currentItemIndex); m_currentItemRecords = readCDRecords(currItem); if (m_currentItemRecords.isEmpty()) { m_currentItemRecordsIndex = -1; return false; } else { //more to last record of that item m_currentItemRecordsIndex = m_currentItemRecords.size()-1; return true; } } else { //no more items available return false; } } } } @Override public boolean hasNext() { checkHandle(); if (m_items.isEmpty()) { return false; } else { if (m_currentItemRecordsIndex==-1) { //offroad? return false; } else if (m_currentItemRecordsIndex<(m_currentItemRecords.size()-1)) { //more records available for current item return true; } else { if (m_currentItemIndex==-1) { //offroad? return false; } else if (m_currentItemIndex<(m_items.size()-1)) { //more items available NotesItem currItem = m_items.get(m_currentItemIndex+1); boolean hasRecords = hasCDRecords(currItem); return hasRecords; } else { //no more items available return false; } } } } @Override public boolean hasPrev() { checkHandle(); if (m_items.isEmpty()) { return false; } else { if (m_currentItemRecordsIndex==-1) { //offroad? return false; } else if (m_currentItemRecordsIndex>0) { //more records available for current item return true; } else { //move to prev item if (m_currentItemIndex==-1) { //offroad? return false; } else if (m_currentItemIndex>0) { //move items available NotesItem currItem = m_items.get(m_currentItemIndex-1); boolean hasRecords = hasCDRecords(currItem); return hasRecords; } else { //no more items available return false; } } } } private CDRecordMemory getCurrentRecord() { if (m_currentItemRecordsIndex==-1) { return null; } else { CDRecordMemory record = m_currentItemRecords.get(m_currentItemRecordsIndex); return record; } } @Override public CDRecordType getCurrentRecordType() { CDRecordMemory record = getCurrentRecord(); return record==null ? null : record.getType(); } // Memory getCurrentRecordDataAsPointer() { // CDRecordMemory record = getCurrentRecord(); // if (record==null) { // return null; // else { // Pointer dataPtr = record.getRecordDataWithoutHeader(); // return dataPtr; @Override public Memory getCurrentRecordData() { CDRecordMemory record = getCurrentRecord(); if (record==null) { return null; } else { return record.getRecordDataWithoutHeader(); } } @Override public short getCurrentRecordTypeAsShort() { CDRecordMemory record = getCurrentRecord(); return record==null ? 0 : record.getTypeAsShort(); } @Override public int getCurrentRecordDataLength() { CDRecordMemory record = getCurrentRecord(); return record==null ? 0 : record.getDataSize(); } @Override public int getCurrentRecordTotalLength() { CDRecordMemory record = getCurrentRecord(); return record==null ? 0 : record.getCDRecordLength(); } @Override public void copyCurrentRecordTo(ICompoundText ct) { if (ct.isRecycled()) throw new NotesError(0, "ICompoundText already recycled"); CompoundTextWriter writer = ct.getAdapter(CompoundTextWriter.class); if (writer==null) throw new NotesError(0, "Unable to get CompoundTextWriter from RichTextBuilder"); addCurrentRecordToCompoundTextWriter(writer); } private void addCurrentRecordToCompoundTextWriter(CompoundTextWriter writer) { CDRecordMemory record = getCurrentRecord(); if (record==null) throw new IllegalStateException("Current record is null"); Pointer recordPtr = record.getRecordDataWithHeader(); int recordLength = record.getCDRecordLength(); if (recordPtr==null || recordLength<=0) { throw new NotesError(0, "The current record does not contain any data"); } writer.addCDRecords(recordPtr, recordLength); } /** * Data container for a single CD record * * @author Karsten Lehmann */ private class CDRecordMemory { private ReadOnlyMemory m_cdRecordMemory; private CDRecordType m_type; private short m_typeAsShort; private int m_dataSize; private int m_cdRecordLength; public CDRecordMemory(ReadOnlyMemory cdRecordMem, CDRecordType type, short typeAsShort, int dataSize, int cdRecordLength) { m_cdRecordMemory = cdRecordMem; m_type = type; m_typeAsShort = typeAsShort; m_dataSize = dataSize; m_cdRecordLength = cdRecordLength; } public Memory getRecordDataWithHeader() { return m_cdRecordMemory; } public Memory getRecordDataWithoutHeader() { return (Memory) m_cdRecordMemory.share(m_cdRecordLength - m_dataSize); } public CDRecordType getType() { return m_type; } public short getTypeAsShort() { return m_typeAsShort; } public int getDataSize() { return m_dataSize; } public int getCDRecordLength() { return m_cdRecordLength; } } } /** * if the document is locked, the method returns a list of current lock holders. If the * document is not locked, we return an empty list. * * @return lock holders or empty list */ public List<String> getLockHolders() { checkHandle(); if (isNewNote()) { return Collections.emptyList(); } int lockFlags = NotesConstants.NOTE_LOCK_STATUS; short result; if (PlatformUtils.is64Bit()) { LongByReference rethLockers = new LongByReference(); IntByReference retLength = new IntByReference(); result = NotesNativeAPI64.get().NSFDbNoteLock(getParent().getHandle64(), getNoteId(), lockFlags, null, rethLockers, retLength); NotesErrorUtils.checkResult(result); long rethLockersAsLong = rethLockers.getValue(); if (rethLockersAsLong==0 || retLength.getValue()==0) return Collections.emptyList(); Pointer retLockersPtr = Mem64.OSLockObject(rethLockersAsLong); try { String retLockHoldersConc = NotesStringUtils.fromLMBCS(retLockersPtr, retLength.getValue()); if (StringUtil.isEmpty(retLockHoldersConc)) return Collections.emptyList(); String[] retLockHoldersArr = retLockHoldersConc.split(";"); return Arrays.asList(retLockHoldersArr); } finally { Mem64.OSUnlockObject(rethLockersAsLong); } } else { IntByReference rethLockers = new IntByReference(); IntByReference retLength = new IntByReference(); result = NotesNativeAPI32.get().NSFDbNoteLock(getParent().getHandle32(), getNoteId(), lockFlags, null, rethLockers, retLength); NotesErrorUtils.checkResult(result); int rethLockersAsInt = rethLockers.getValue(); if (rethLockersAsInt==0 || retLength.getValue()==0) return Collections.emptyList(); Pointer retLockersPtr = Mem32.OSLockObject(rethLockersAsInt); try { String retLockHoldersConc = NotesStringUtils.fromLMBCS(retLockersPtr, retLength.getValue()); if (StringUtil.isEmpty(retLockHoldersConc)) return Collections.emptyList(); String[] retLockHoldersArr = retLockHoldersConc.split(";"); return Arrays.asList(retLockHoldersArr); } finally { Mem32.OSUnlockObject(rethLockersAsInt); } } } /** Document locking mode */ public static enum LockMode { /** Hard lock can only be set if Master Locking Server is available */ Hard, /** Try to create a hard lock; if Master Locking Server is not available, use a provisional lock */ HardOrProvisional, /** Provisional lock can be set if Master Locking Server is not available */ Provisional } /** * This function adds an "$Writers" field to a note which contains a list of "writers" * who will be able to update the note.<br> * <br> * Any user will be able to open the note, but only the members contained in the "$Writers" * field are allowed to update the note.<br> * <br> * This function will only succeed if the database option "Allow document locking" is set.<br> * <br> * Please refer to the Domino documentation for a full description of document locking. * * @param lockHolder new lock holder * @param mode lock mode * @return true if successful, false if already locked */ public boolean lock(String lockHolder, LockMode mode) { return lock(Arrays.asList(lockHolder), mode); } /** * This function adds an "$Writers" field to a note which contains a list of "writers" * who will be able to update the note.<br> * <br> * Any user will be able to open the note, but only the members contained in the "$Writers" * field are allowed to update the note.<br> * <br> * This function will only succeed if the database option "Allow document locking" is set.<br> * <br> * Please refer to the Domino documentation for a full description of document locking. * * @param lockHolders new lock holders * @param mode lock mode * @return true if successful, false if already locked */ public boolean lock(List<String> lockHolders, LockMode mode) { checkHandle(); if (isNewNote()) throw new NotesError(0, "Note must be saved before locking"); int lockFlags = 0; if (mode==LockMode.Hard || mode==LockMode.HardOrProvisional) { lockFlags = NotesConstants.NOTE_LOCK_HARD; } else if (mode==LockMode.Provisional) { lockFlags = NotesConstants.NOTE_LOCK_PROVISIONAL; } else throw new IllegalArgumentException("Missing lock mode"); String lockHoldersConc = StringUtil.join(lockHolders, ";"); Memory lockHoldersMem = NotesStringUtils.toLMBCS(lockHoldersConc, true); short result; if (PlatformUtils.is64Bit()) { LongByReference rethLockers = new LongByReference(); IntByReference retLength = new IntByReference(); result = NotesNativeAPI64.get().NSFDbNoteLock(getParent().getHandle64(), getNoteId(), lockFlags, lockHoldersMem, rethLockers, retLength); if (result==1463) { //Unable to connect to Master Lock Database if (mode==LockMode.HardOrProvisional) { result = NotesNativeAPI64.get().NSFDbNoteLock(getParent().getHandle64(), getNoteId(), NotesConstants.NOTE_LOCK_PROVISIONAL, lockHoldersMem, rethLockers, retLength); } } } else { IntByReference rethLockers = new IntByReference(); IntByReference retLength = new IntByReference(); result = NotesNativeAPI32.get().NSFDbNoteLock(getParent().getHandle32(), getNoteId(), lockFlags, lockHoldersMem, rethLockers, retLength); if (result==1463) { //Unable to connect to Master Lock Database if (mode==LockMode.HardOrProvisional) { result = NotesNativeAPI32.get().NSFDbNoteLock(getParent().getHandle32(), getNoteId(), NotesConstants.NOTE_LOCK_PROVISIONAL, lockHoldersMem, rethLockers, retLength); } } } if (result == INotesErrorConstants.ERR_NOTE_LOCKED) { return false; } NotesErrorUtils.checkResult(result); return true; } /** * This function removes the lock on a note.<br> * <br> * Only the members contained in the "writers" list are allowed to remove a lock, * with the exception of person(s) designated as capable of removing locks.<br> * <br> * Please refer to the Domino documentation for a full description of document locking.# * * @param mode lock mode */ public void unlock(LockMode mode) { checkHandle(); if (isNewNote()) return; int lockFlags = 0; if (mode==LockMode.Hard || mode==LockMode.HardOrProvisional) { lockFlags = NotesConstants.NOTE_LOCK_HARD; } else if (mode==LockMode.Provisional) { lockFlags = NotesConstants.NOTE_LOCK_PROVISIONAL; } else throw new IllegalArgumentException("Missing lock mode"); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NSFDbNoteUnlock(getParent().getHandle64(), getNoteId(), lockFlags); if (result==1463) { //Unable to connect to Master Lock Database if (mode==LockMode.HardOrProvisional) { result = NotesNativeAPI64.get().NSFDbNoteUnlock(getParent().getHandle64(), getNoteId(), NotesConstants.NOTE_LOCK_PROVISIONAL); } } } else { result = NotesNativeAPI32.get().NSFDbNoteUnlock(getParent().getHandle32(), getNoteId(), lockFlags); if (result==1463) { //Unable to connect to Master Lock Database if (mode==LockMode.HardOrProvisional) { result = NotesNativeAPI32.get().NSFDbNoteUnlock(getParent().getHandle32(), getNoteId(), NotesConstants.NOTE_LOCK_PROVISIONAL); } } } NotesErrorUtils.checkResult(result); } }
package com.thaiopensource.xml.dtd.app; import java.io.IOException; import java.util.Hashtable; import java.util.Enumeration; import com.thaiopensource.xml.dtd.om.*; import com.thaiopensource.xml.out.XmlWriter; import com.thaiopensource.xml.em.ExternalId; public class RelaxNgWriter { private XmlWriter w; private boolean hadAny = false; private Hashtable elementNameTable = new Hashtable(); private Hashtable defTable = new Hashtable(); // These variables control the names use for definitions. private String colonReplacement = null; private String elementDeclPattern; private String attlistDeclPattern; private String anyName; static final int ELEMENT_DECL = 01; static final int ATTLIST_DECL = 02; static final int ELEMENT_REF = 04; // # is the category; % is the name in the category static final String DEFAULT_PATTERN = " static abstract class VisitorBase implements TopLevelVisitor { public void processingInstruction(String target, String value) throws Exception { } public void comment(String value) throws Exception { } public void flagDef(String name, Flag flag) throws Exception { } public void includedSection(Flag flag, TopLevel[] contents) throws Exception { for (int i = 0; i < contents.length; i++) contents[i].accept(this); } public void ignoredSection(Flag flag, String contents) throws Exception { } public void internalEntityDecl(String name, String value) throws Exception { } public void externalEntityDecl(String name, ExternalId externalId) throws Exception { } public void notationDecl(String name, ExternalId externalId) throws Exception { } public void nameSpecDef(String name, NameSpec nameSpec) throws Exception { } public void overriddenDef(Def def, boolean isDuplicate) throws Exception { } public void externalIdDef(String name, ExternalId externalId) throws Exception { } public void externalIdRef(String name, ExternalId externalId, TopLevel[] contents) throws Exception { for (int i = 0; i < contents.length; i++) contents[i].accept(this); } public void paramDef(String name, String value) throws Exception { } public void attributeDefaultDef(String name, AttributeDefault ad) throws Exception { } } class Analyzer extends VisitorBase implements ModelGroupVisitor, AttributeGroupVisitor { public void elementDecl(NameSpec nameSpec, ModelGroup modelGroup) throws Exception { noteElementName(nameSpec.getValue(), ELEMENT_DECL); modelGroup.accept(this); } public void attlistDecl(NameSpec nameSpec, AttributeGroup attributeGroup) throws Exception { noteElementName(nameSpec.getValue(), ATTLIST_DECL); attributeGroup.accept(this); } public void modelGroupDef(String name, ModelGroup modelGroup) throws Exception { noteDef(name); modelGroup.accept(this); } public void attributeGroupDef(String name, AttributeGroup attributeGroup) throws Exception { noteDef(name); attributeGroup.accept(this); } public void enumGroupDef(String name, EnumGroup enumGroup) { noteDef(name); } public void datatypeDef(String name, Datatype datatype) { noteDef(name); } public void choice(ModelGroup[] members) throws Exception { for (int i = 0; i < members.length; i++) members[i].accept(this); } public void sequence(ModelGroup[] members) throws Exception { for (int i = 0; i < members.length; i++) members[i].accept(this); } public void oneOrMore(ModelGroup member) throws Exception { member.accept(this); } public void zeroOrMore(ModelGroup member) throws Exception { member.accept(this); } public void optional(ModelGroup member) throws Exception { member.accept(this); } public void modelGroupRef(String name, ModelGroup modelGroup) { } public void elementRef(NameSpec name) { noteElementName(name.getValue(), ELEMENT_REF); } public void pcdata() { } public void any() { hadAny = true; } public void attribute(NameSpec nameSpec, Datatype datatype, AttributeDefault attributeDefault) { noteAttribute(nameSpec.getValue(), attributeDefault.getDefaultValue()); } public void attributeGroupRef(String name, AttributeGroup attributeGroup) { } } class Output extends VisitorBase implements ModelGroupVisitor, AttributeGroupVisitor, DatatypeVisitor, EnumGroupVisitor { public void elementDecl(NameSpec nameSpec, ModelGroup modelGroup) throws Exception { w.startElement("define"); w.attribute("name", elementDeclName(nameSpec.getValue())); w.startElement("element"); w.attribute("name", nameSpec.getValue()); ref(attlistDeclName(nameSpec.getValue())); modelGroup.accept(this); w.endElement(); w.endElement(); if ((nameFlags(nameSpec.getValue()) & ATTLIST_DECL) == 0) { w.startElement("define"); w.attribute("name", attlistDeclName(nameSpec.getValue())); w.attribute("combine", "interleave"); w.startElement("empty"); w.endElement(); w.endElement(); } } public void attlistDecl(NameSpec nameSpec, AttributeGroup attributeGroup) throws Exception { w.startElement("define"); w.attribute("name", attlistDeclName(nameSpec.getValue())); w.attribute("combine", "interleave"); attributeGroup.accept(this); w.endElement(); } public void modelGroupDef(String name, ModelGroup modelGroup) throws Exception { w.startElement("define"); w.attribute("name", name); modelGroup.accept(this); w.endElement(); } public void attributeGroupDef(String name, AttributeGroup attributeGroup) throws Exception { w.startElement("define"); w.attribute("name", name); attributeGroup.accept(this); w.endElement(); } public void enumGroupDef(String name, EnumGroup enumGroup) throws Exception { w.startElement("define"); w.attribute("name", name); enumDatatype(enumGroup); w.endElement(); } public void datatypeDef(String name, Datatype datatype) throws Exception { w.startElement("define"); w.attribute("name", name); datatype.accept(this); w.endElement(); } public void choice(ModelGroup[] members) throws Exception { if (members.length == 0) { w.startElement("notAllowed"); w.endElement(); } else if (members.length == 1) members[0].accept(this); else { w.startElement("choice"); for (int i = 0; i < members.length; i++) members[i].accept(this); w.endElement(); } } public void sequence(ModelGroup[] members) throws Exception { if (members.length == 0) { w.startElement("empty"); w.endElement(); } else if (members.length == 1) members[0].accept(this); else { w.startElement("group"); for (int i = 0; i < members.length; i++) members[i].accept(this); w.endElement(); } } public void oneOrMore(ModelGroup member) throws Exception { w.startElement("oneOrMore"); member.accept(this); w.endElement(); } public void zeroOrMore(ModelGroup member) throws Exception { w.startElement("zeroOrMore"); member.accept(this); w.endElement(); } public void optional(ModelGroup member) throws Exception { w.startElement("optional"); member.accept(this); w.endElement(); } public void modelGroupRef(String name, ModelGroup modelGroup) throws IOException { ref(name); } public void elementRef(NameSpec name) throws IOException { ref(elementDeclName(name.getValue())); } public void pcdata() throws IOException { w.startElement("text"); w.endElement(); } public void any() throws IOException { ref(anyName); } public void attribute(NameSpec nameSpec, Datatype datatype, AttributeDefault attributeDefault) throws Exception { if (!attributeDefault.isRequired()) w.startElement("optional"); w.startElement("attribute"); w.attribute("name", nameSpec.getValue()); datatype.accept(this); w.endElement(); if (!attributeDefault.isRequired()) w.endElement(); } public void attributeGroupRef(String name, AttributeGroup attributeGroup) throws IOException { ref(name); } public void basicDatatype(String typeName) throws IOException { w.startElement("data"); w.attribute("type", typeName); w.endElement(); } public void enumDatatype(EnumGroup enumGroup) throws Exception { w.startElement("choice"); enumGroup.accept(this); w.endElement(); } public void notationDatatype(EnumGroup enumGroup) throws Exception { enumDatatype(enumGroup); } public void datatypeRef(String name, Datatype datatype) throws IOException { ref(name); } public void enumValue(String value) throws IOException { w.startElement("value"); w.characters(value); w.endElement(); } public void enumGroupRef(String name, EnumGroup enumGroup) throws IOException { ref(name); } private void ref(String name) throws IOException { w.startElement("ref"); w.attribute("name", name); w.endElement(); } public void comment(String value) throws IOException { w.comment(value); } } public RelaxNgWriter(XmlWriter w) { this.w = w; } public void writeDtd(Dtd dtd) throws IOException { try { dtd.accept(new Analyzer()); } catch (Exception e) { throw (RuntimeException)e; } chooseNames(); if (colonReplacement != null) System.err.println("colonReplacement: " + colonReplacement); System.err.println("elementDecl: " + elementDeclPattern); System.err.println("attlistDecl: " + attlistDeclPattern); w.startElement("grammar"); w.attribute("datatypeLibrary", "http: w.attribute("xmlns", "http://relaxng.org/ns/structure/0.9"); try { dtd.accept(new Output()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw (IOException)e; } w.endElement(); } void chooseNames() { chooseColonReplacement(); chooseDeclPatterns(); } static final String SEPARATORS = ".-_"; void chooseColonReplacement() { if (colonReplacementOk()) return; for (int n = 1;; n++) { for (int i = 0; i < SEPARATORS.length(); i++) { colonReplacement = repeatChar(SEPARATORS.charAt(i), n); if (colonReplacementOk()) return; } } } boolean colonReplacementOk() { Hashtable table = new Hashtable(); for (Enumeration e = elementNameTable.keys(); e.hasMoreElements();) { String name = mungeQName((String)e.nextElement()); if (table.get(name) != null) return false; table.put(name, name); } return true; } String[] ELEMENT_KEYWORDS = { "element", "elem", "e" }; String[] ATTLIST_KEYWORDS = { "attlist", "attributes", "attribs", "atts", "a" }; void chooseDeclPatterns() { // XXX Try to match length and case of best prefix String pattern = namingPattern(); if (patternOk("%")) elementDeclPattern = "%"; else elementDeclPattern = choosePattern(pattern, ELEMENT_KEYWORDS); attlistDeclPattern = choosePattern(pattern, ATTLIST_KEYWORDS); } String choosePattern(String metaPattern, String[] keywords) { for (;;) { for (int i = 0; i < keywords.length; i++) { String pattern = substitute(metaPattern, '#', keywords[i]); if (patternOk(pattern)) return pattern; } // add another separator metaPattern = (metaPattern.substring(0, 1) + metaPattern.substring(1, 2) + metaPattern.substring(1, 2) + metaPattern.substring(2)); } } String namingPattern() { Hashtable patternTable = new Hashtable(); for (Enumeration e = defTable.keys(); e.hasMoreElements();) { String name = (String)e.nextElement(); for (int i = 0; i < SEPARATORS.length(); i++) { char sep = SEPARATORS.charAt(i); int k = name.indexOf(sep); if (k > 0) inc(patternTable, name.substring(0, k + 1) + "%"); k = name.lastIndexOf(sep); if (k >= 0 && k < name.length() - 1) inc(patternTable, "%" + name.substring(k)); } } String bestPattern = null; int bestCount = 0; for (Enumeration e = patternTable.keys(); e.hasMoreElements();) { String pattern = (String)e.nextElement(); int count = ((Integer)patternTable.get(pattern)).intValue(); if (bestPattern == null || count > bestCount) { bestCount = count; bestPattern = pattern; } } if (bestPattern == null) return DEFAULT_PATTERN; if (bestPattern.charAt(0) == '%') return bestPattern.substring(0, 2) + " else return "#" + bestPattern.substring(bestPattern.length() - 2); } static void inc(Hashtable table, String str) { Integer n = (Integer)table.get(str); if (n == null) table.put(str, new Integer(1)); else table.put(str, new Integer(n.intValue() + 1)); } boolean patternOk(String pattern) { for (Enumeration e = elementNameTable.keys(); e.hasMoreElements();) { String name = mungeQName((String)e.nextElement()); if (defTable.get(substitute(pattern, '%', name)) != null) return false; } return true; } void noteDef(String name) { defTable.put(name, name); } void noteElementName(String name, int flags) { Integer n = (Integer)elementNameTable.get(name); if (n != null) { flags |= n.intValue(); if (n.intValue() == flags) return; } elementNameTable.put(name, new Integer(flags)); } void noteAttribute(String name, String defaultValue) { } int nameFlags(String name) { Integer n = (Integer)elementNameTable.get(name); if (n == null) return 0; return n.intValue(); } String elementDeclName(String name) { return substitute(elementDeclPattern, '%', mungeQName(name)); } String attlistDeclName(String name) { return substitute(attlistDeclPattern, '%', mungeQName(name)); } String mungeQName(String name) { if (colonReplacement == null) return name; return substitute(name, ':', colonReplacement); } static String repeatChar(char c, int n) { char[] buf = new char[n]; for (int i = 0; i < n; i++) buf[i] = c; return new String(buf); } /* Replace the first occurrence of ch in pattern by value. */ static String substitute(String pattern, char ch, String value) { int i = pattern.indexOf(ch); if (i < 0) return pattern; StringBuffer buf = new StringBuffer(); buf.append(pattern.substring(0, i)); buf.append(value); buf.append(pattern.substring(i + 1)); return buf.toString(); } }
package dynamake.commands; import java.util.ArrayList; import java.util.List; import dynamake.models.CanvasModel; import dynamake.models.CompositeLocation; import dynamake.models.HistoryChangeForwarder; import dynamake.models.Location; import dynamake.models.Model; import dynamake.models.ModelComponent; import dynamake.models.ModelRootLocation; import dynamake.models.PropogationContext; import dynamake.transcription.Collector; public class InheritLocalChangesCommand implements MappableCommand<Model> { private static final long serialVersionUID = 1L; private Location locationOfInhereter; public InheritLocalChangesCommand(Location locationOfInhereter) { this.locationOfInhereter = locationOfInhereter; } @Override public Object executeOn(PropogationContext propCtx, Model prevalentSystem, Collector<Model> collector, Location location) { Model inhereter = (Model)CompositeLocation.getChild(prevalentSystem, location, locationOfInhereter); Model inheretee = (Model)location.getChild(prevalentSystem); // HistoryChangeForwarder forwarder = inhereter.getObserverOfLike(new HistoryChangeForwarder(inhereter, inheretee)); // forwarder.changed(inhereter, new HistoryChangeForwarder.ForwardLogChange(new ArrayList<CommandState<Model>>(), inhereter.getLocalChanges()), propCtx, 0, 0, collector); // List<CommandState<Model>> inheritedChanges = inhereter.getLocalChanges(); // ArrayList<CommandState<Model>> filteredInheritedChanges = new ArrayList<CommandState<Model>>(); // for(CommandState<Model> inheritedChange: inheritedChanges) { // PendingCommandState<Model> pcsInheritedChange = (PendingCommandState<Model>)inheritedChange; // if(pcsInheritedChange.getCommand() instanceof CanvasModel.AddModelCommand) { // } else { // filteredInheritedChanges.add(inheritedChange); // Is it possible to traverse through the inherited changes and find all add commands (like above) // and then replace the add methods with off set commands relative to the added model's commands? // Can this be done recursively, such that the added model's commands are processed the same? // I.e.; recursively expand add command with the added model's commands List<CommandState<Model>> reversedInheritedChanges = inheretee.playThenReverse(inhereter.getLocalChanges(), propCtx, 0, collector); System.out.println(inheretee + " inherited from " + inhereter); return new PlayThenReverseCommand(reversedInheritedChanges); // return null; } @Override public Command<Model> mapToReferenceLocation(Model sourceReference, Model targetReference) { Model inhereter = (Model)CompositeLocation.getChild(sourceReference, new ModelRootLocation(), locationOfInhereter); Location locationOfInhereterFromTargetReference = ModelComponent.Util.locationBetween(targetReference, inhereter); return new InheritLocalChangesCommand(locationOfInhereterFromTargetReference); } }
package org.vaadin.elements.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Document; import org.vaadin.elements.ElementIntegration; import org.vaadin.elements.Elements; import org.vaadin.elements.Import; import org.vaadin.elements.Node; import org.vaadin.elements.Root; import org.vaadin.elements.TextNode; import com.vaadin.server.EncodeResult; import com.vaadin.server.JsonCodec; import com.vaadin.ui.Component; import com.vaadin.ui.JavaScriptFunction; import elemental.json.Json; import elemental.json.JsonArray; import elemental.json.JsonObject; import elemental.json.JsonType; import elemental.json.JsonValue; public class RootImpl extends ElementImpl implements Root { private ElementIntegration owner; private int callbackIdSequence = 0; private int nodeIdSequence = 0; private int fetchCallbackSequence = 0; private final Map<NodeImpl, Integer> nodeToId = new HashMap<>(); private final Map<Integer, NodeImpl> idToNode = new HashMap<>(); private JsonArray pendingCommands = Json.createArray(); private final Map<Integer, Runnable> fetchDomCallbacks = new HashMap<>(); private final Map<Integer, Component[]> fetchDomComponents = new HashMap<>(); private final Set<String> handledImports = new HashSet<>(); public RootImpl(ElementIntegration owner) { super(new org.jsoup.nodes.Element(org.jsoup.parser.Tag.valueOf("div"), "")); Context context = new Context() { @Override protected void adopt(NodeImpl node) { super.adopt(node); if (node != RootImpl.this) { adoptNode(node); } } @Override protected void remove(NodeImpl node) { addCommand("remove", node); Integer id = nodeToId.remove(node); idToNode.remove(id); super.remove(node); } @Override public RootImpl getRoot() { return RootImpl.this; } }; this.owner = owner; context.adopt(this); Integer ownId = Integer.valueOf(0); nodeToId.put(this, ownId); idToNode.put(ownId, this); } private void addCommand(String name, Node target, JsonValue... params) { assert target == null || target.getRoot() == this; JsonArray c = Json.createArray(); c.set(0, name); if (target != null) { c.set(1, nodeToId.get(target).doubleValue()); } Arrays.asList(params).forEach(p -> c.set(c.length(), p)); pendingCommands.set(pendingCommands.length(), c); owner.markAsDirty(); } private void adoptNode(NodeImpl child) { // Even numbers generated by server, odd by client nodeIdSequence += 2; Integer id = Integer.valueOf(nodeIdSequence); adoptNode(child, id); } private void adoptNode(NodeImpl child, Integer id) { nodeToId.put(child, id); idToNode.put(id, child); resolveImports(child.getClass()); // Enqueue initialization operations if (child instanceof ElementImpl) { ElementImpl e = (ElementImpl) child; addCommand("createElement", child, Json.create(e.getTag())); e.getAttributeNames().forEach(name -> setAttributeChange(e, name)); e.flushCommandQueues(); } else if (child instanceof TextNodeImpl) { TextNode t = (TextNode) child; addCommand("createText", child, Json.create(t.getText())); } else { throw new RuntimeException("Unsupported node type: " + child.getClass()); } // Finally add append command addCommand("appendChild", child.getParent(), Json.create(id.doubleValue())); } private void resolveImports(Class<? extends NodeImpl> type) { Arrays.stream(type.getInterfaces()) .map(i -> i.getAnnotation(Import.class)) .filter(Objects::nonNull).map(Import::value) .filter(url -> !handledImports.contains(url)).forEach(url -> { handledImports.add(url); addCommand("import", null, Json.create(url)); }); } void setAttributeChange(ElementImpl element, String name) { String value = element.getAttribute(name); if (value == null) { addCommand("removeAttribute", element, Json.create(name)); } else { addCommand("setAttribute", element, Json.create(name), Json.create(value)); } } public void setTextChange(TextNodeImpl textNode, String text) { addCommand("setText", textNode, Json.create(text)); } public JsonArray flushPendingCommands() { for (Entry<Integer, Component[]> entry : fetchDomComponents.entrySet()) { JsonArray connectorsJson = Json.createArray(); for (Component component : entry.getValue()) { connectorsJson.set(connectorsJson.length(), component.getConnectorId()); } addCommand("fetchDom", null, Json.create(entry.getKey().intValue()), connectorsJson); } fetchDomComponents.clear(); JsonArray payload = pendingCommands; pendingCommands = Json.createArray(); return payload; } void eval(ElementImpl element, String script, Object[] arguments) { // Param values JsonArray params = Json.createArray(); // Array of param indices that should be treated as callbacks JsonArray callbacks = Json.createArray(); for (int i = 0; i < arguments.length; i++) { Object value = arguments[0]; Class<? extends Object> type = value.getClass(); if (JavaScriptFunction.class.isAssignableFrom(type)) { // TODO keep sequence per element instead of "global" int cid = callbackIdSequence++; element.setCallback(cid, (JavaScriptFunction) value); value = Integer.valueOf(cid); type = Integer.class; callbacks.set(callbacks.length(), i); } EncodeResult encodeResult = JsonCodec.encode(value, null, type, null); params.set(i, encodeResult.getEncodedValue()); } addCommand("eval", element, Json.create(script), params, callbacks); } public void handleCallback(JsonArray arguments) { JsonArray attributeChanges = arguments.getArray(1); for (int i = 0; i < attributeChanges.length(); i++) { JsonArray attributeChange = attributeChanges.getArray(i); int id = (int) attributeChange.getNumber(0); String attribute = attributeChange.getString(1); JsonValue value = attributeChange.get(2); NodeImpl target = idToNode.get(Integer.valueOf(id)); if (value.getType() == JsonType.NULL) { target.node.removeAttr(attribute); } else { target.node.attr(attribute, value.asString()); } } JsonArray callbacks = arguments.getArray(0); for (int i = 0; i < callbacks.length(); i++) { JsonArray call = callbacks.getArray(i); int elementId = (int) call.getNumber(0); int cid = (int) call.getNumber(1); JsonArray params = call.getArray(2); ElementImpl element = (ElementImpl) idToNode.get(Integer .valueOf(elementId)); if (element == null) { System.out.println(cid + " detached?"); return; } JavaScriptFunction callback = element.getCallback(cid); callback.call(params); } } @Override public String asHtml() { StringBuilder b = new StringBuilder(); b.append(super.asHtml()); return b.toString(); } public void synchronize(int id, JsonArray hierarchy) { synchronizeRecursively(hierarchy, this); // Detach all removed nodes List<NodeImpl> detached = new ArrayList<>(); for (NodeImpl node : new ArrayList<>(idToNode.values())) { NodeImpl parent = node; while (parent != this) { if (parent == null) { detached.add(node); break; } parent = (NodeImpl) parent.getParent(); } } Context removedContext = new Context(); detached.forEach(node -> removedContext.adopt(node)); // Don't send the adopted structure to the client pendingCommands = Json.createArray(); Runnable callback = fetchDomCallbacks.remove(Integer.valueOf(id)); if (callback != null) { callback.run(); } } public void init(String html) { // Clear state removeAllChildren(); getAttributeNames().forEach(this::removeAttribute); nodeIdSequence = 2; Document bodyFragment = Jsoup.parseBodyFragment(html); List<org.jsoup.nodes.Node> childNodes = bodyFragment.body() .childNodes(); assert childNodes.size() == 1; org.jsoup.nodes.Node rootNode = childNodes.get(0); while (rootNode.childNodeSize() != 0) { org.jsoup.nodes.Node child = rootNode.childNode(0); ((org.jsoup.nodes.Element) this.node).appendChild(child); } context.wrapChildren(this); for (Attribute a : rootNode.attributes()) { setAttribute(a.getKey(), a.getValue()); } // Don't send the adopted structure to the client pendingCommands = Json.createArray(); // TODO sync ids fetchDomCallbacks.values().forEach(Runnable::run); fetchDomCallbacks.clear(); } private void synchronizeRecursively(JsonArray hierarchy, ElementImpl element) { int firstChild; JsonValue maybeAttributes = hierarchy.get(2); if (maybeAttributes.getType() == JsonType.OBJECT) { firstChild = 3; JsonObject attributes = (JsonObject) maybeAttributes; String[] names = attributes.keys(); HashSet<String> oldAttributes = new HashSet<>( element.getAttributeNames()); oldAttributes.removeAll(Arrays.asList(names)); oldAttributes.forEach(n -> element.removeAttribute(n)); Arrays.stream(names).forEach( name -> element.setAttribute(name, attributes.getString(name))); } else { firstChild = 2; } ArrayList<NodeImpl> newChildren = new ArrayList<>(); for (int i = firstChild; i < hierarchy.length(); i++) { JsonArray child = hierarchy.getArray(i); int nodeId; NodeImpl childNode; switch (child.get(0).getType()) { case NUMBER: TextNodeImpl textNode; nodeId = (int) child.getNumber(0); String text = child.getString(1); if (nodeId % 2 == 0) { // old node textNode = (TextNodeImpl) idToNode.get(Integer .valueOf(nodeId)); textNode.setText(text); } else { // new node textNode = (TextNodeImpl) Elements.createText(text); } childNode = textNode; break; case STRING: // Element node ElementImpl childElement; String tag = child.getString(0); nodeId = (int) child.getNumber(1); if (nodeId % 2 == 0) { // old node childElement = (ElementImpl) idToNode.get(Integer .valueOf(nodeId)); assert childElement.getTag().equals(tag); } else { // new node childElement = (ElementImpl) Elements.create(tag); } synchronizeRecursively(child, childElement); childNode = childElement; break; default: throw new RuntimeException("Unsupported child JSON: " + child.toJson()); } if (nodeId % 2 == 1) { context.adopt(childNode); adoptNode(childNode, nodeId); } newChildren.add(childNode); } element.resetChildren(newChildren); } @Override public void fetchDom(Runnable callback, Component... connectorsToInlcude) { assert callback != null; Integer id = Integer.valueOf(fetchCallbackSequence++); fetchDomCallbacks.put(id, callback); fetchDomComponents.put(id, connectorsToInlcude); owner.markAsDirty(); } void setAttributeBound(ElementImpl elementImpl, String attributeName, String eventName) { addCommand("bindAttribute", elementImpl, Json.create(attributeName), Json.create(eventName)); } }
package hudson.model; import hudson.util.ByteBuffer; import hudson.util.CharSpool; import hudson.util.CountingOutputStream; import hudson.util.LineEndNormalizingWriter; import hudson.util.WriterOutputStream; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Writer; /** * Represents a large text data. * * <p> * This class defines methods for handling progressive text update. * * @author Kohsuke Kawaguchi */ public class LargeText { /** * Represents the data source of this text. */ private interface Source { Session open() throws IOException; long length(); boolean exists(); } private final Source source; private volatile boolean completed; public LargeText(final File file, boolean completed) { this.source = new Source() { public Session open() throws IOException { return new FileSession(file); } public long length() { return file.length(); } public boolean exists() { return file.exists(); } }; this.completed = completed; } public LargeText(final ByteBuffer memory, boolean completed) { this.source = new Source() { public Session open() throws IOException { return new BufferSession(memory); } public long length() { return memory.length(); } public boolean exists() { return true; } }; this.completed = completed; } public void markAsComplete() { completed = true; } public boolean isComplete() { return completed; } /** * Writes the tail portion of the file to the {@link Writer}. * * <p> * The text file is assumed to be in the system default encoding. * * @param start * The byte offset in the input file where the write operation starts. * * @return * if the file is still being written, this method writes the file * until the last newline character and returns the offset to start * the next write operation. */ public long writeLogTo(long start, Writer w) throws IOException { CountingOutputStream os = new CountingOutputStream(new WriterOutputStream(w)); Session f = source.open(); f.skip(start); if(completed) { // write everything till EOF byte[] buf = new byte[1024]; int sz; while((sz=f.read(buf))>=0) os.write(buf,0,sz); } else { ByteBuf buf = new ByteBuf(null,f); HeadMark head = new HeadMark(buf); TailMark tail = new TailMark(buf); while(tail.moveToNextLine(f)) { head.moveTo(tail,os); } head.finish(os); } f.close(); os.flush(); return os.getCount()+start; } /** * Implements the progressive text handling. * This method is used as a "web method" with progressiveText.jelly. */ public void doProgressText(StaplerRequest req, StaplerResponse rsp) throws IOException { rsp.setContentType("text/plain"); rsp.setCharacterEncoding("UTF-8"); rsp.setStatus(HttpServletResponse.SC_OK); if(!source.exists()) { // file doesn't exist yet rsp.addHeader("X-Text-Size","0"); rsp.addHeader("X-More-Data","true"); return; } long start = 0; String s = req.getParameter("start"); if(s!=null) start = Long.parseLong(s); if(source.length() < start ) start = 0; // text rolled over CharSpool spool = new CharSpool(); long r = writeLogTo(start,spool); rsp.addHeader("X-Text-Size",String.valueOf(r)); if(!completed) rsp.addHeader("X-More-Data","true"); // when sending big text, try compression. don't bother if it's small Writer w; if(r-start>4096) w = rsp.getCompressedWriter(req); else w = rsp.getWriter(); spool.writeTo(new LineEndNormalizingWriter(w)); w.close(); } /** * Points to a byte in the buffer. */ private static class Mark { protected ByteBuf buf; protected int pos; public Mark(ByteBuf buf) { this.buf = buf; } } /** * Points to the start of the region that's not committed * to the output yet. */ private static final class HeadMark extends Mark { public HeadMark(ByteBuf buf) { super(buf); } /** * Moves this mark to 'that' mark, and writes the data * to {@link OutputStream} if necessary. */ void moveTo(Mark that, OutputStream os) throws IOException { while(this.buf!=that.buf) { os.write(buf.buf,0,buf.size); buf = buf.next; pos = 0; } this.pos = that.pos; } void finish(OutputStream os) throws IOException { os.write(buf.buf,0,pos); } } /** * Points to the end of the region. */ private static final class TailMark extends Mark { public TailMark(ByteBuf buf) { super(buf); } boolean moveToNextLine(Session f) throws IOException { while(true) { while(pos==buf.size) { if(!buf.isFull()) { // read until EOF return false; } else { // read into the next buffer buf = new ByteBuf(buf,f); pos = 0; } } byte b = buf.buf[pos++]; if(b=='\r' || b=='\n') return true; } } } private static final class ByteBuf { private final byte[] buf = new byte[1024]; private int size = 0; private ByteBuf next; public ByteBuf(ByteBuf previous, Session f) throws IOException { if(previous!=null) { assert previous.next==null; previous.next = this; } while(!this.isFull()) { int chunk = f.read(buf, size, buf.length - size); if(chunk==-1) return; size+= chunk; } } public boolean isFull() { return buf.length==size; } } /** * Represents the read session of the {@link Source}. * Methods generally follow the contracts of {@link InputStream}. */ private interface Session { void close() throws IOException; void skip(long start) throws IOException; int read(byte[] buf) throws IOException; int read(byte[] buf, int offset, int length) throws IOException; } /** * {@link Session} implementation over {@link RandomAccessFile}. */ private static final class FileSession implements Session { private final RandomAccessFile file; public FileSession(File file) throws IOException { this.file = new RandomAccessFile(file,"r"); } public void close() throws IOException { file.close(); } public void skip(long start) throws IOException { file.seek(file.getFilePointer()+start); } public int read(byte[] buf) throws IOException { return file.read(buf); } public int read(byte[] buf, int offset, int length) throws IOException { return file.read(buf,offset,length); } } /** * {@link Session} implementation over {@link ByteBuffer}. */ private static final class BufferSession implements Session { private final InputStream in; public BufferSession(ByteBuffer buf) { this.in = buf.newInputStream(); } public void close() throws IOException { in.close(); } public void skip(long start) throws IOException { in.skip(start); } public int read(byte[] buf) throws IOException { return in.read(buf); } public int read(byte[] buf, int offset, int length) throws IOException { return in.read(buf,offset,length); } } }
package edu.umd.cs.findbugs.detect; import java.math.BigDecimal; import java.util.Iterator; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.CodeException; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantDouble; import org.apache.bcel.classfile.ConstantInteger; import org.apache.bcel.classfile.ConstantLong; import org.apache.bcel.classfile.ConstantPool; import org.apache.bcel.classfile.ConstantValue; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Synthetic; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.IntAnnotation; import edu.umd.cs.findbugs.JavaVersion; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.Priorities; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.StringAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.OpcodeStack.Item; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Hierarchy; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class DumbMethods extends OpcodeStackDetector { private static final ObjectType CONDITION_TYPE = ObjectTypeFactory.getInstance("java.util.concurrent.locks.Condition"); private final BugReporter bugReporter; private boolean sawCurrentTimeMillis; private BugInstance gcInvocationBugReport; private int gcInvocationPC; private CodeException[] exceptionTable; /* * private boolean sawLDCEmptyString; */ private String primitiveObjCtorSeen; private boolean ctorSeen; private boolean prevOpcodeWasReadLine; private int prevOpcode; private boolean isPublicStaticVoidMain; private boolean isEqualsObject; private boolean sawInstanceofCheck; private boolean reportedBadCastInEquals; private int sawCheckForNonNegativeSignedByte; private int sinceBufferedInputStreamReady; private int randomNextIntState; private boolean checkForBitIorofSignedByte; private final boolean jdk15ChecksEnabled; private final BugAccumulator accumulator; private final BugAccumulator absoluteValueAccumulator; private static final int MICROS_PER_DAY_OVERFLOWED_AS_INT = 24 * 60 * 60 * 1000 * 1000; public DumbMethods(BugReporter bugReporter) { this.bugReporter = bugReporter; accumulator = new BugAccumulator(bugReporter); absoluteValueAccumulator = new BugAccumulator(bugReporter); jdk15ChecksEnabled = JavaVersion.getRuntimeVersion().isSameOrNewerThan(JavaVersion.JAVA_1_5); } boolean isSynthetic; @Override public void visit(JavaClass obj) { String superclassName = obj.getSuperclassName(); isSynthetic = superclassName.equals("java.rmi.server.RemoteStub"); Attribute[] attributes = obj.getAttributes(); if (attributes != null) { for (Attribute a : attributes) { if (a instanceof Synthetic) { isSynthetic = true; } } } } @Override public void visitAfter(JavaClass obj) { accumulator.reportAccumulatedBugs(); } public static boolean isTestMethod(Method method) { return method.getName().startsWith("test"); } @Override public void visit(Field field) { ConstantValue value = field.getConstantValue(); if (value == null) return; Constant c = getConstantPool().getConstant(value.getConstantValueIndex()); if (c instanceof ConstantLong && ((ConstantLong)c).getBytes() == MICROS_PER_DAY_OVERFLOWED_AS_INT) { bugReporter.reportBug( new BugInstance(this, "TESTING", HIGH_PRIORITY).addClass(this).addField(this) .addString("Did you mean MICROS_PER_DAY") .addInt(MICROS_PER_DAY_OVERFLOWED_AS_INT) .describe(IntAnnotation.INT_VALUE)); } } @Override public void visit(Method method) { String cName = getDottedClassName(); // System.out.println(getFullyQualifiedMethodName()); isPublicStaticVoidMain = method.isPublic() && method.isStatic() && getMethodName().equals("main") || cName.toLowerCase().indexOf("benchmark") >= 0; prevOpcodeWasReadLine = false; Code code = method.getCode(); if (code != null) { this.exceptionTable = code.getExceptionTable(); } if (this.exceptionTable == null) { this.exceptionTable = new CodeException[0]; } primitiveObjCtorSeen = null; ctorSeen = false; randomNextIntState = 0; checkForBitIorofSignedByte = false; isEqualsObject = getMethodName().equals("equals") && getMethodSig().equals("(Ljava/lang/Object;)Z") && !method.isStatic(); sawInstanceofCheck = false; reportedBadCastInEquals = false; freshRandomOnTos = false; sinceBufferedInputStreamReady = 100000; sawCheckForNonNegativeSignedByte = -1000; sawLoadOfMinValue = false; } int opcodesSincePendingAbsoluteValueBug; BugInstance pendingAbsoluteValueBug; SourceLineAnnotation pendingAbsoluteValueBugSourceLine; boolean freshRandomOnTos = false; boolean freshRandomOneBelowTos = false; boolean sawLoadOfMinValue = false; @Override public void sawOpcode(int seen) { // System.out.printf("%3d %12s %s%n", getPC(), OPCODE_NAMES[seen], // stack); if (seen == LDC || seen == LDC_W || seen == LDC2_W) { Constant c = getConstantRefOperand(); if ((c instanceof ConstantInteger && ((ConstantInteger) c).getBytes() == MICROS_PER_DAY_OVERFLOWED_AS_INT || c instanceof ConstantLong && ((ConstantLong) c).getBytes() == MICROS_PER_DAY_OVERFLOWED_AS_INT)) { BugInstance bug = new BugInstance(this, "TESTING", HIGH_PRIORITY).addClassAndMethod(this) .addString("Did you mean MICROS_PER_DAY").addInt(MICROS_PER_DAY_OVERFLOWED_AS_INT) .describe(IntAnnotation.INT_VALUE); accumulator.accumulateBug(bug, this); } if ((c instanceof ConstantInteger && ((ConstantInteger) c).getBytes() == Integer.MIN_VALUE || c instanceof ConstantLong && ((ConstantLong) c).getBytes() == Long.MIN_VALUE)) { sawLoadOfMinValue = true; pendingAbsoluteValueBug = null; pendingAbsoluteValueBugSourceLine = null; absoluteValueAccumulator.clearBugs(); } } if (seen == LCMP) { OpcodeStack.Item left = stack.getStackItem(1); OpcodeStack.Item right = stack.getStackItem(0); checkForCompatibleLongComparison(left, right); checkForCompatibleLongComparison(right, left); } if (stack.getStackDepth() >= 2) switch (seen) { case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLE: case IF_ICMPGE: case IF_ICMPLT: case IF_ICMPGT: OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.getConstant() instanceof Integer) { OpcodeStack.Item tmp = item0; item0 = item1; item1 = tmp; } Object constant1 = item1.getConstant(); XMethod returnValueOf = item0.getReturnValueOf(); if (constant1 instanceof Integer && returnValueOf != null && returnValueOf.getName().equals("getYear") && (returnValueOf.getClassName().equals("java.util.Date") || returnValueOf.getClassName().equals( "java.sql.Date"))) { int year = (Integer) constant1; if (year > 1900) accumulator.accumulateBug( new BugInstance(this, "TESTING", HIGH_PRIORITY).addClassAndMethod(this) .addString("Comparison of getYear does understand that it returns year-1900") .addMethod(returnValueOf).describe(MethodAnnotation.METHOD_CALLED).addInt(year) .describe(IntAnnotation.INT_VALUE), this); } } // System.out.printf("%4d %10s: %s\n", getPC(), OPCODE_NAMES[seen], // stack); if (seen == IFLT && stack.getStackDepth() > 0 && stack.getStackItem(0).getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE) { sawCheckForNonNegativeSignedByte = getPC(); } if (pendingAbsoluteValueBug != null) { if (opcodesSincePendingAbsoluteValueBug == 0) { opcodesSincePendingAbsoluteValueBug++; } else { if (seen == IREM) { OpcodeStack.Item top = stack.getStackItem(0); Object constantValue = top.getConstant(); if (constantValue instanceof Number && Util.isPowerOfTwo(((Number) constantValue).intValue())) { pendingAbsoluteValueBug.setPriority(Priorities.LOW_PRIORITY); } } if (false) try { pendingAbsoluteValueBug.addString(OPCODE_NAMES[getPrevOpcode(1)] + ":" + OPCODE_NAMES[seen] + ":" + OPCODE_NAMES[getNextOpcode()]); } catch (Exception e) { pendingAbsoluteValueBug.addString(OPCODE_NAMES[getPrevOpcode(1)] + ":" + OPCODE_NAMES[seen]); } absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine); pendingAbsoluteValueBug = null; pendingAbsoluteValueBugSourceLine = null; } } if (seen == INVOKESTATIC && getClassConstantOperand().equals("org/easymock/EasyMock") && (getNameConstantOperand().equals("replay") || getNameConstantOperand().equals("verify") || getNameConstantOperand() .startsWith("reset")) && getSigConstantOperand().equals("([Ljava/lang/Object;)V") && getPrevOpcode(1) == ANEWARRAY && getPrevOpcode(2) == ICONST_0) accumulator.accumulateBug(new BugInstance(this, "DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD", NORMAL_PRIORITY) .addClassAndMethod(this).addCalledMethod(this), this); if (seen == INVOKESTATIC && getClassConstantOperand().equals("com/google/common/base/Preconditions") && getNameConstantOperand().equals("checkNotNull")) { int args = PreorderVisitor.getNumberArguments(getSigConstantOperand()); OpcodeStack.Item item = stack.getStackItem(args - 1); Object o = item.getConstant(); if (o instanceof String) { OpcodeStack.Item secondArgument = null; String bugPattern = "DMI_DOH"; if (args > 1) { secondArgument = stack.getStackItem(args - 2); Object secondConstant = secondArgument.getConstant(); if (!(secondConstant instanceof String)) { bugPattern = "DMI_ARGUMENTS_WRONG_ORDER"; } } BugInstance bug = new BugInstance(this, bugPattern, NORMAL_PRIORITY).addClassAndMethod(this) .addCalledMethod(this) .addString("Passing String constant as value that should be null checked").describe(StringAnnotation.STRING_MESSAGE) .addString((String) o).describe(StringAnnotation.STRING_CONSTANT_ROLE); if (secondArgument != null) bug.addValueSource(secondArgument, this); accumulator.accumulateBug(bug, this); } } if (seen == INVOKESTATIC && getClassConstantOperand().equals("junit/framework/Assert") && getNameConstantOperand().equals("assertNotNull")) { int args = PreorderVisitor.getNumberArguments(getSigConstantOperand()); OpcodeStack.Item item = stack.getStackItem(0); Object o = item.getConstant(); if (o instanceof String) { OpcodeStack.Item secondArgument = null; String bugPattern = "DMI_DOH"; if (args == 2) { secondArgument = stack.getStackItem(1); Object secondConstant = secondArgument.getConstant(); if (!(secondConstant instanceof String)) { bugPattern = "DMI_ARGUMENTS_WRONG_ORDER"; } } BugInstance bug = new BugInstance(this, bugPattern, NORMAL_PRIORITY).addClassAndMethod(this) .addCalledMethod(this).addString("Passing String constant as value that should be null checked").describe(StringAnnotation.STRING_MESSAGE) .addString((String) o).describe(StringAnnotation.STRING_CONSTANT_ROLE); if (secondArgument != null) bug.addValueSource(secondArgument, this); accumulator.accumulateBug(bug, this); } } if ((seen == INVOKESTATIC || seen == INVOKEVIRTUAL || seen == INVOKESPECIAL || seen == INVOKEINTERFACE) && getSigConstantOperand().indexOf("Ljava/lang/Runnable;") >= 0) { SignatureParser parser = new SignatureParser(getSigConstantOperand()); int count = 0; for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext(); count++) { String parameter = i.next(); if (parameter.equals("Ljava/lang/Runnable;")) { OpcodeStack.Item item = stack.getStackItem(parser.getNumParameters() - 1 - count); if ("Ljava/lang/Thread;".equals(item.getSignature())) { accumulator.accumulateBug(new BugInstance(this, "DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED", NORMAL_PRIORITY).addClassAndMethod(this).addCalledMethod(this), this); } } } } if (prevOpcode == I2L && seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/Double") && getNameConstantOperand().equals("longBitsToDouble")) { accumulator.accumulateBug(new BugInstance(this, "DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT", HIGH_PRIORITY) .addClassAndMethod(this).addCalledMethod(this), this); } if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/Random") && (freshRandomOnTos || freshRandomOneBelowTos)) { accumulator.accumulateBug(new BugInstance(this, "DMI_RANDOM_USED_ONLY_ONCE", HIGH_PRIORITY).addClassAndMethod(this) .addCalledMethod(this), this); } freshRandomOneBelowTos = freshRandomOnTos && isRegisterLoad(); freshRandomOnTos = seen == INVOKESPECIAL && getClassConstantOperand().equals("java/util/Random") && getNameConstantOperand().equals("<init>"); if ((seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/HashMap") && getNameConstantOperand().equals( "get")) || (seen == INVOKEINTERFACE && getClassConstantOperand().equals("java/util/Map") && getNameConstantOperand() .equals("get")) || (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/HashSet") && getNameConstantOperand() .equals("contains")) || (seen == INVOKEINTERFACE && getClassConstantOperand().equals("java/util/Set") && getNameConstantOperand() .equals("contains"))) { OpcodeStack.Item top = stack.getStackItem(0); if (top.getSignature().equals("Ljava/net/URL;")) { accumulator.accumulateBug(new BugInstance(this, "DMI_COLLECTION_OF_URLS", HIGH_PRIORITY).addClassAndMethod(this), this); } } /** * Since you can change the number of core threads for a scheduled * thread pool executor, disabling this for now */ if (false && seen == INVOKESPECIAL && getClassConstantOperand().equals("java/util/concurrent/ScheduledThreadPoolExecutor") && getNameConstantOperand().equals("<init>")) { int arguments = getNumberArguments(getSigConstantOperand()); OpcodeStack.Item item = stack.getStackItem(arguments - 1); Object value = item.getConstant(); if (value instanceof Integer && ((Integer) value).intValue() == 0) accumulator.accumulateBug(new BugInstance(this, "DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS", HIGH_PRIORITY).addClassAndMethod(this), this); } if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/concurrent/ScheduledThreadPoolExecutor") && getNameConstantOperand().equals("setMaximumPoolSize")) { accumulator.accumulateBug(new BugInstance(this, "DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR", HIGH_PRIORITY) .addClassAndMethod(this), this); } if (isEqualsObject && !reportedBadCastInEquals) { if (seen == INVOKEVIRTUAL && getNameConstantOperand().equals("isInstance") && getClassConstantOperand().equals("java/lang/Class")) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) { sawInstanceofCheck = true; } } else if (seen == INSTANCEOF || seen == INVOKEVIRTUAL && getNameConstantOperand().equals("getClass") && getSigConstantOperand().equals("()Ljava/lang/Class;")) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) { sawInstanceofCheck = true; } } else if (seen == INVOKESPECIAL && getNameConstantOperand().equals("equals") && getSigConstantOperand().equals("(Ljava/lang/Object;)Z")) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item1.getRegisterNumber() + item0.getRegisterNumber() == 1) { sawInstanceofCheck = true; } } else if (seen == CHECKCAST && !sawInstanceofCheck) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 1) { if (getSizeOfSurroundingTryBlock(getPC()) == Integer.MAX_VALUE) { accumulator.accumulateBug(new BugInstance(this, "BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS", NORMAL_PRIORITY).addClassAndMethod(this), this); } reportedBadCastInEquals = true; } } } { boolean foundVacuousComparison = false; if (seen == IF_ICMPGT || seen == IF_ICMPLE) { OpcodeStack.Item rhs = stack.getStackItem(0); Object rhsConstant = rhs.getConstant(); if (rhsConstant instanceof Integer && ((Integer) rhsConstant).intValue() == Integer.MAX_VALUE) { foundVacuousComparison = true; } OpcodeStack.Item lhs = stack.getStackItem(1); Object lhsConstant = lhs.getConstant(); if (lhsConstant instanceof Integer && ((Integer) lhsConstant).intValue() == Integer.MIN_VALUE) { foundVacuousComparison = true; } } if (seen == IF_ICMPLT || seen == IF_ICMPGE) { OpcodeStack.Item rhs = stack.getStackItem(0); Object rhsConstant = rhs.getConstant(); if (rhsConstant instanceof Integer && ((Integer) rhsConstant).intValue() == Integer.MIN_VALUE) { foundVacuousComparison = true; } OpcodeStack.Item lhs = stack.getStackItem(1); Object lhsConstant = lhs.getConstant(); if (lhsConstant instanceof Integer && ((Integer) lhsConstant).intValue() == Integer.MAX_VALUE) { foundVacuousComparison = true; } } if (foundVacuousComparison) { accumulator.accumulateBug(new BugInstance(this, "INT_VACUOUS_COMPARISON", getBranchOffset() < 0 ? HIGH_PRIORITY : NORMAL_PRIORITY).addClassAndMethod(this), this); } } if (!sawLoadOfMinValue && seen == INVOKESTATIC && ClassName.isMathClass(getClassConstantOperand()) && getNameConstantOperand().equals("abs") ) { OpcodeStack.Item item0 = stack.getStackItem(0); int special = item0.getSpecialKind(); if (special == OpcodeStack.Item.RANDOM_INT) { pendingAbsoluteValueBug = new BugInstance(this, "RV_ABSOLUTE_VALUE_OF_RANDOM_INT", HIGH_PRIORITY) .addClassAndMethod(this); pendingAbsoluteValueBugSourceLine = SourceLineAnnotation.fromVisitedInstruction(this); opcodesSincePendingAbsoluteValueBug = 0; } else if (special == OpcodeStack.Item.HASHCODE_INT) { pendingAbsoluteValueBug = new BugInstance(this, "RV_ABSOLUTE_VALUE_OF_HASHCODE", HIGH_PRIORITY) .addClassAndMethod(this); pendingAbsoluteValueBugSourceLine = SourceLineAnnotation.fromVisitedInstruction(this); opcodesSincePendingAbsoluteValueBug = 0; } } try { int stackLoc = stackEntryThatMustBeNonnegative(seen); if (stackLoc >= 0) { OpcodeStack.Item tos = stack.getStackItem(stackLoc); switch (tos.getSpecialKind()) { case OpcodeStack.Item.HASHCODE_INT_REMAINDER: accumulator.accumulateBug(new BugInstance(this, "RV_REM_OF_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this), this); break; case OpcodeStack.Item.RANDOM_INT: case OpcodeStack.Item.RANDOM_INT_REMAINDER: accumulator.accumulateBug( new BugInstance(this, "RV_REM_OF_RANDOM_INT", HIGH_PRIORITY).addClassAndMethod(this), this); break; } } if (seen == IREM) { OpcodeStack.Item item0 = stack.getStackItem(0); Object constant0 = item0.getConstant(); if (constant0 instanceof Integer && ((Integer) constant0).intValue() == 1) { accumulator.accumulateBug(new BugInstance(this, "INT_BAD_REM_BY_1", HIGH_PRIORITY).addClassAndMethod(this), this); } } if (stack.getStackDepth() >= 1 && (seen == LOOKUPSWITCH || seen == TABLESWITCH)) { OpcodeStack.Item item0 = stack.getStackItem(0); if (item0.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE) { int[] switchLabels = getSwitchLabels(); int[] switchOffsets = getSwitchOffsets(); for (int i = 0; i < switchLabels.length; i++) { int v = switchLabels[i]; if (v <= -129 || v >= 128) { accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_SIGNED_BYTE", HIGH_PRIORITY) .addClassAndMethod(this).addInt(v).describe(IntAnnotation.INT_VALUE), SourceLineAnnotation.fromVisitedInstruction(this, getPC() + switchOffsets[i])); } } } } // check for use of signed byte where is it assumed it can be out of // the -128...127 range if (stack.getStackDepth() >= 2) { switch (seen) { case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPLE: case IF_ICMPGE: case IF_ICMPGT: OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); int seen2 = seen; if (item0.getConstant() != null) { OpcodeStack.Item tmp = item0; item0 = item1; item1 = tmp; switch (seen) { case IF_ICMPLT: seen2 = IF_ICMPGT; break; case IF_ICMPGE: seen2 = IF_ICMPLE; break; case IF_ICMPGT: seen2 = IF_ICMPLT; break; case IF_ICMPLE: seen2 = IF_ICMPGE; break; } } Object constant1 = item1.getConstant(); if (item0.getSpecialKind() == OpcodeStack.Item.SIGNED_BYTE && constant1 instanceof Number) { int v1 = ((Number) constant1).intValue(); if (v1 <= -129 || v1 >= 128 || v1 == 127 && !(seen2 == IF_ICMPEQ || seen2 == IF_ICMPNE )) { int priority = HIGH_PRIORITY; if (v1 == 127) { switch (seen2) { case IF_ICMPGT: // 127 > x priority = LOW_PRIORITY; break; case IF_ICMPGE: // 127 >= x : always true priority = NORMAL_PRIORITY; break; case IF_ICMPLT: // 127 < x : never true priority = NORMAL_PRIORITY; break; case IF_ICMPLE: // 127 <= x priority = LOW_PRIORITY; break; } } else if (v1 == 128) { switch (seen2) { case IF_ICMPGT: // 128 > x; always true priority = NORMAL_PRIORITY; break; case IF_ICMPGE: // 128 >= x priority = HIGH_PRIORITY; break; case IF_ICMPLT: // 128 < x priority = HIGH_PRIORITY; break; case IF_ICMPLE: // 128 <= x; never true priority = NORMAL_PRIORITY; break; } } else if (v1 <= -129) { priority = NORMAL_PRIORITY; } if (getPC() - sawCheckForNonNegativeSignedByte < 10) priority++; accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_SIGNED_BYTE", priority) .addClassAndMethod(this).addInt(v1).describe(IntAnnotation.INT_VALUE), this); } } else if (item0.getSpecialKind() == OpcodeStack.Item.NON_NEGATIVE && constant1 instanceof Number) { int v1 = ((Number) constant1).intValue(); if (v1 < 0) { accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE", HIGH_PRIORITY).addClassAndMethod(this).addInt(v1).describe(IntAnnotation.INT_VALUE), this); } } } } switch (seen) { case IAND: case LAND: case IOR: case LOR: case IXOR: case LXOR: long badValue = (seen == IAND || seen == LAND) ? -1 : 0; OpcodeStack.Item rhs = stack.getStackItem(0); OpcodeStack.Item lhs = stack.getStackItem(1); int prevOpcode = getPrevOpcode(1); int prevPrevOpcode = getPrevOpcode(2); if (rhs.hasConstantValue(badValue) && (prevOpcode == LDC || prevOpcode == ICONST_0 || prevOpcode == ICONST_M1 || prevOpcode == LCONST_0) && prevPrevOpcode != GOTO) reportVacuousBitOperation(seen, lhs); } if (checkForBitIorofSignedByte && seen != I2B) { String pattern = (prevOpcode == LOR || prevOpcode == IOR) ? "BIT_IOR_OF_SIGNED_BYTE" : "BIT_ADD_OF_SIGNED_BYTE"; int priority = (prevOpcode == LOR || prevOpcode == LADD) ? HIGH_PRIORITY : NORMAL_PRIORITY; accumulator.accumulateBug(new BugInstance(this, pattern, priority).addClassAndMethod(this), this); checkForBitIorofSignedByte = false; } else if ((seen == IOR || seen == LOR || seen == IADD || seen == LADD) && stack.getStackDepth() >= 2) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); int special0 = item0.getSpecialKind(); int special1 = item1.getSpecialKind(); if (special0 == OpcodeStack.Item.SIGNED_BYTE && special1 == OpcodeStack.Item.LOW_8_BITS_CLEAR && !item1.hasConstantValue(256) || special0 == OpcodeStack.Item.LOW_8_BITS_CLEAR && !item0.hasConstantValue(256) && special1 == OpcodeStack.Item.SIGNED_BYTE) { checkForBitIorofSignedByte = true; } else { checkForBitIorofSignedByte = false; } } else { checkForBitIorofSignedByte = false; } if (prevOpcodeWasReadLine && sinceBufferedInputStreamReady >= 100 && seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/String") && getSigConstantOperand().startsWith("()")) { accumulator.accumulateBug( new BugInstance(this, "NP_IMMEDIATE_DEREFERENCE_OF_READLINE", NORMAL_PRIORITY).addClassAndMethod(this), this); } if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/io/BufferedReader") && getNameConstantOperand().equals("ready") && getSigConstantOperand().equals("()Z")) { sinceBufferedInputStreamReady = 0; } else { sinceBufferedInputStreamReady++; } prevOpcodeWasReadLine = (seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE) && getNameConstantOperand().equals("readLine") && getSigConstantOperand().equals("()Ljava/lang/String;"); // System.out.println(randomNextIntState + " " + OPCODE_NAMES[seen] // + " " + getMethodName()); switch (randomNextIntState) { case 0: if (seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/util/Random") && getNameConstantOperand().equals("nextDouble") || seen == INVOKESTATIC && ClassName.isMathClass(getClassConstantOperand()) && getNameConstantOperand().equals("random")) { randomNextIntState = 1; } break; case 1: if (seen == D2I) { accumulator.accumulateBug(new BugInstance(this, "RV_01_TO_INT", HIGH_PRIORITY).addClassAndMethod(this), this); randomNextIntState = 0; } else if (seen == DMUL) randomNextIntState = 4; else if (seen == LDC2_W && getConstantRefOperand() instanceof ConstantDouble && ((ConstantDouble) getConstantRefOperand()).getBytes() == Integer.MIN_VALUE) randomNextIntState = 0; else randomNextIntState = 2; break; case 2: if (seen == I2D) { randomNextIntState = 3; } else if (seen == DMUL) { randomNextIntState = 4; } else { randomNextIntState = 0; } break; case 3: if (seen == DMUL) { randomNextIntState = 4; } else { randomNextIntState = 0; } break; case 4: if (seen == D2I) { accumulator.accumulateBug( new BugInstance(this, "DM_NEXTINT_VIA_NEXTDOUBLE", NORMAL_PRIORITY).addClassAndMethod(this), this); } randomNextIntState = 0; break; default: throw new IllegalStateException(); } if (isPublicStaticVoidMain && seen == INVOKEVIRTUAL && getClassConstantOperand().startsWith("javax/swing/") && (getNameConstantOperand().equals("show") && getSigConstantOperand().equals("()V") || getNameConstantOperand().equals("pack") && getSigConstantOperand().equals("()V") || getNameConstantOperand() .equals("setVisible") && getSigConstantOperand().equals("(Z)V"))) { accumulator.accumulateBug( new BugInstance(this, "SW_SWING_METHODS_INVOKED_IN_SWING_THREAD", LOW_PRIORITY).addClassAndMethod(this), this); } // if ((seen == INVOKEVIRTUAL) // && getClassConstantOperand().equals("java/lang/String") // && getNameConstantOperand().equals("substring") // && getSigConstantOperand().equals("(I)Ljava/lang/String;") // && stack.getStackDepth() > 1) { // OpcodeStack.Item item = stack.getStackItem(0); // Object o = item.getConstant(); // if (o != null && o instanceof Integer) { // int v = ((Integer) o).intValue(); // if (v == 0) // accumulator.accumulateBug(new BugInstance(this, // "DMI_USELESS_SUBSTRING", NORMAL_PRIORITY) // .addClassAndMethod(this) // .addSourceLine(this)); if ((seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("isAnnotationPresent") && getSigConstantOperand().equals("(Ljava/lang/Class;)Z") && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); Object value = item.getConstant(); if (value instanceof String) { String annotationClassName = (String) value; boolean lacksClassfileRetention = AnalysisContext.currentAnalysisContext().getAnnotationRetentionDatabase() .lacksRuntimeRetention(annotationClassName.replace('/', '.')); if (lacksClassfileRetention) { ClassDescriptor annotationClass = DescriptorFactory.createClassDescriptor(annotationClassName); accumulator.accumulateBug( new BugInstance(this, "DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION", HIGH_PRIORITY) .addClassAndMethod(this).addCalledMethod(this).addClass(annotationClass) .describe(ClassAnnotation.ANNOTATION_ROLE), this); } } } if ((seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("next") && getSigConstantOperand().equals("()Ljava/lang/Object;") && getMethodName().equals("hasNext") && getMethodSig().equals("()Z") && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); accumulator.accumulateBug(new BugInstance(this, "DMI_CALLING_NEXT_FROM_HASNEXT", item.isInitialParameter() && item.getRegisterNumber() == 0 ? NORMAL_PRIORITY : LOW_PRIORITY).addClassAndMethod(this) .addCalledMethod(this), this); } if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("(Ljava/lang/String;)V")) { accumulator.accumulateBug(new BugInstance(this, "DM_STRING_CTOR", NORMAL_PRIORITY).addClassAndMethod(this), this); } if (seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("runFinalizersOnExit") || seen == INVOKEVIRTUAL && getClassConstantOperand().equals("java/lang/Runtime") && getNameConstantOperand().equals("runFinalizersOnExit")) { accumulator.accumulateBug( new BugInstance(this, "DM_RUN_FINALIZERS_ON_EXIT", HIGH_PRIORITY).addClassAndMethod(this), this); } if ((seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("()V")) { accumulator.accumulateBug(new BugInstance(this, "DM_STRING_VOID_CTOR", NORMAL_PRIORITY).addClassAndMethod(this), this); } if (!isPublicStaticVoidMain && seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System") && getNameConstantOperand().equals("exit") && !getMethodName().equals("processWindowEvent") && !getMethodName().startsWith("windowClos") && getMethodName().indexOf("exit") == -1 && getMethodName().indexOf("Exit") == -1 && getMethodName().indexOf("crash") == -1 && getMethodName().indexOf("Crash") == -1 && getMethodName().indexOf("die") == -1 && getMethodName().indexOf("Die") == -1 && getMethodName().indexOf("main") == -1) { accumulator.accumulateBug(new BugInstance(this, "DM_EXIT", getMethod().isStatic() ? LOW_PRIORITY : NORMAL_PRIORITY).addClassAndMethod(this), SourceLineAnnotation.fromVisitedInstruction(this)); } if (((seen == INVOKESTATIC && getClassConstantOperand().equals("java/lang/System")) || (seen == INVOKEVIRTUAL && getClassConstantOperand() .equals("java/lang/Runtime"))) && getNameConstantOperand().equals("gc") && getSigConstantOperand().equals("()V") && !getDottedClassName().startsWith("java.lang") && !getMethodName().startsWith("gc") && !getMethodName().endsWith("gc")) { if (gcInvocationBugReport == null) { // System.out.println("Saw call to GC"); if (isPublicStaticVoidMain) { // System.out.println("Skipping GC complaint in main method"); return; } if (isTestMethod(getMethod())) { return; } // Just save this report in a field; it will be flushed // IFF there were no calls to System.currentTimeMillis(); // in the method. gcInvocationBugReport = new BugInstance(this, "DM_GC", HIGH_PRIORITY).addClassAndMethod(this).addSourceLine( this); gcInvocationPC = getPC(); // System.out.println("GC invocation at pc " + PC); } } if (!isSynthetic && (seen == INVOKESPECIAL) && getClassConstantOperand().equals("java/lang/Boolean") && getNameConstantOperand().equals("<init>") && !getClassName().equals("java/lang/Boolean")) { int majorVersion = getThisClass().getMajor(); if (majorVersion >= MAJOR_1_4) { accumulator.accumulateBug(new BugInstance(this, "DM_BOOLEAN_CTOR", NORMAL_PRIORITY).addClassAndMethod(this), this); } } if ((seen == INVOKESTATIC) && getClassConstantOperand().equals("java/lang/System") && (getNameConstantOperand().equals("currentTimeMillis") || getNameConstantOperand().equals("nanoTime"))) { sawCurrentTimeMillis = true; } if ((seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/String") && getNameConstantOperand().equals("toString") && getSigConstantOperand().equals("()Ljava/lang/String;")) { accumulator .accumulateBug(new BugInstance(this, "DM_STRING_TOSTRING", LOW_PRIORITY).addClassAndMethod(this), this); } if ((seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/String") && (getNameConstantOperand().equals("toUpperCase") || getNameConstantOperand().equals("toLowerCase")) && getSigConstantOperand().equals("()Ljava/lang/String;")) { accumulator.accumulateBug(new BugInstance(this, "DM_CONVERT_CASE", LOW_PRIORITY).addClassAndMethod(this), this); } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>")) { String cls = getClassConstantOperand(); String sig = getSigConstantOperand(); if ((cls.equals("java/lang/Integer") && sig.equals("(I)V")) || (cls.equals("java/lang/Float") && sig.equals("(F)V")) || (cls.equals("java/lang/Double") && sig.equals("(D)V")) || (cls.equals("java/lang/Long") && sig.equals("(J)V")) || (cls.equals("java/lang/Byte") && sig.equals("(B)V")) || (cls.equals("java/lang/Character") && sig.equals("(C)V")) || (cls.equals("java/lang/Short") && sig.equals("(S)V")) || (cls.equals("java/lang/Boolean") && sig.equals("(Z)V"))) { primitiveObjCtorSeen = cls; } else { primitiveObjCtorSeen = null; } } else if ((primitiveObjCtorSeen != null) && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("toString") && getClassConstantOperand().equals(primitiveObjCtorSeen) && getSigConstantOperand().equals("()Ljava/lang/String;")) { accumulator.accumulateBug( new BugInstance(this, "DM_BOXED_PRIMITIVE_TOSTRING", LOW_PRIORITY).addClassAndMethod(this), this); primitiveObjCtorSeen = null; } else { primitiveObjCtorSeen = null; } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>")) { ctorSeen = true; } else if (ctorSeen && (seen == INVOKEVIRTUAL) && getClassConstantOperand().equals("java/lang/Object") && getNameConstantOperand().equals("getClass") && getSigConstantOperand().equals("()Ljava/lang/Class;")) { accumulator.accumulateBug(new BugInstance(this, "DM_NEW_FOR_GETCLASS", LOW_PRIORITY).addClassAndMethod(this), this); ctorSeen = false; } else { ctorSeen = false; } if (jdk15ChecksEnabled && (seen == INVOKEVIRTUAL) && isMonitorWait(getNameConstantOperand(), getSigConstantOperand())) { checkMonitorWait(); } if ((seen == INVOKESPECIAL) && getNameConstantOperand().equals("<init>") && getClassConstantOperand().equals("java/lang/Thread")) { String sig = getSigConstantOperand(); if (sig.equals("()V") || sig.equals("(Ljava/lang/String;)V") || sig.equals("(Ljava/lang/ThreadGroup;Ljava/lang/String;)V")) { OpcodeStack.Item invokedOn = stack.getItemMethodInvokedOn(this); if (!getMethodName().equals("<init>") || invokedOn.getRegisterNumber() != 0) { accumulator.accumulateBug( new BugInstance(this, "DM_USELESS_THREAD", LOW_PRIORITY).addClassAndMethod(this), this); } } } if (seen == INVOKESPECIAL && getClassConstantOperand().equals("java/math/BigDecimal") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().equals("(D)V")) { OpcodeStack.Item top = stack.getStackItem(0); Object value = top.getConstant(); if (value instanceof Double) { double arg = ((Double) value).doubleValue(); String dblString = Double.toString(arg); String bigDecimalString = new BigDecimal(arg).toString(); boolean ok = dblString.equals(bigDecimalString) || dblString.equals(bigDecimalString + ".0"); if (!ok) { boolean scary = dblString.length() <= 8 && bigDecimalString.length() > 12 && dblString.toUpperCase().indexOf("E") == -1; bugReporter.reportBug(new BugInstance(this, "DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE", scary ? NORMAL_PRIORITY : LOW_PRIORITY).addClassAndMethod(this).addCalledMethod(this) .addMethod("java.math.BigDecimal", "valueOf", "(D)Ljava/math/BigDecimal;", true) .describe(MethodAnnotation.METHOD_ALTERNATIVE_TARGET).addString(dblString) .addString(bigDecimalString).addSourceLine(this)); } } } } finally { prevOpcode = seen; } } private void checkForCompatibleLongComparison(OpcodeStack.Item left, OpcodeStack.Item right) { if (left.getSpecialKind() == Item.RESULT_OF_I2L && right.getConstant() != null) { long value = ((Number) right.getConstant()).longValue(); if ( (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE)) { int priority = Priorities.HIGH_PRIORITY; if (value == Integer.MAX_VALUE+1 || value == Integer.MIN_VALUE -1) priority = Priorities.NORMAL_PRIORITY; String stringValue = IntAnnotation.getShortInteger(value)+"L"; if (value == 0xffffffffL) stringValue = "0xffffffffL"; else if (value == 0x80000000L) stringValue = "0x80000000L"; accumulator.accumulateBug(new BugInstance(this, "INT_BAD_COMPARISON_WITH_INT_VALUE", priority ).addClassAndMethod(this) .addString(stringValue).describe(StringAnnotation.STRING_NONSTRING_CONSTANT_ROLE) .addValueSource(left, this) , this); } } } /** * @param seen * @param item */ private void reportVacuousBitOperation(int seen, OpcodeStack.Item item) { if (item.getConstant() == null) accumulator .accumulateBug( new BugInstance(this, "INT_VACUOUS_BIT_OPERATION", NORMAL_PRIORITY) .addClassAndMethod(this) .addString(OPCODE_NAMES[seen]) .addOptionalAnnotation( LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(), item, getPC())), this); } /** * Return index of stack entry that must be nonnegative. * * Return -1 if no stack entry is required to be nonnegative. * * @param seen * @return */ private int stackEntryThatMustBeNonnegative(int seen) { switch (seen) { case INVOKEINTERFACE: if (getClassConstantOperand().equals("java/util/List")) { return getStackEntryOfListCallThatMustBeNonnegative(); } break; case INVOKEVIRTUAL: if (getClassConstantOperand().equals("java/util/LinkedList") || getClassConstantOperand().equals("java/util/ArrayList")) { return getStackEntryOfListCallThatMustBeNonnegative(); } break; case IALOAD: case AALOAD: case SALOAD: case CALOAD: case BALOAD: case LALOAD: case DALOAD: case FALOAD: return 0; case IASTORE: case AASTORE: case SASTORE: case CASTORE: case BASTORE: case LASTORE: case DASTORE: case FASTORE: return 1; } return -1; } private int getStackEntryOfListCallThatMustBeNonnegative() { String name = getNameConstantOperand(); if ((name.equals("add") || name.equals("set")) && getSigConstantOperand().startsWith("(I")) { return 1; } if ((name.equals("get") || name.equals("remove")) && getSigConstantOperand().startsWith("(I)")) { return 0; } return -1; } private void checkMonitorWait() { try { TypeDataflow typeDataflow = getClassContext().getTypeDataflow(getMethod()); TypeDataflow.LocationAndFactPair pair = typeDataflow.getLocationAndFactForInstruction(getPC()); if (pair == null) { return; } Type receiver = pair.frame.getInstance(pair.location.getHandle().getInstruction(), getClassContext() .getConstantPoolGen()); if (!(receiver instanceof ReferenceType)) { return; } if (Hierarchy.isSubtype((ReferenceType) receiver, CONDITION_TYPE)) { accumulator.accumulateBug( new BugInstance(this, "DM_MONITOR_WAIT_ON_CONDITION", HIGH_PRIORITY).addClassAndMethod(this), this); } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } catch (DataflowAnalysisException e) { bugReporter.logError("Exception caught by DumbMethods", e); } catch (CFGBuilderException e) { bugReporter.logError("Exception caught by DumbMethods", e); } } private boolean isMonitorWait(String name, String sig) { // System.out.println("Check call " + name + "," + sig); return name.equals("wait") && (sig.equals("()V") || sig.equals("(J)V") || sig.equals("(JI)V")); } @Override public void visit(Code obj) { super.visit(obj); flush(); } /** * A heuristic - how long a catch block for OutOfMemoryError might be. */ private static final int OOM_CATCH_LEN = 20; /** * Flush out cached state at the end of a method. */ private void flush() { if (pendingAbsoluteValueBug != null) { absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine); pendingAbsoluteValueBug = null; pendingAbsoluteValueBugSourceLine = null; } accumulator.reportAccumulatedBugs(); if (sawLoadOfMinValue) absoluteValueAccumulator.clearBugs(); else absoluteValueAccumulator.reportAccumulatedBugs(); if (gcInvocationBugReport != null && !sawCurrentTimeMillis) { // Make sure the GC invocation is not in an exception handler // for OutOfMemoryError. boolean outOfMemoryHandler = false; for (CodeException handler : exceptionTable) { if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) { continue; } int catchTypeIndex = handler.getCatchType(); if (catchTypeIndex > 0) { ConstantPool cp = getThisClass().getConstantPool(); Constant constant = cp.getConstant(catchTypeIndex); if (constant instanceof ConstantClass) { String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp); if (exClassName.equals("java/lang/OutOfMemoryError")) { outOfMemoryHandler = true; break; } } } } if (!outOfMemoryHandler) { bugReporter.reportBug(gcInvocationBugReport); } } sawCurrentTimeMillis = false; gcInvocationBugReport = null; exceptionTable = null; } }
package gnu.lists; /** A Consumer extended with XML-specific methods. * This should probably be in gnu.xml, but that complications TreeList. FIXME. */ public interface XConsumer extends Consumer // Maybe future: extends org.xml.sax.ContentHandler { /** Write/set the base-uri property of the current element or document. * Only allowed immediately following beginDocument, beginGroup, * or writeProcessingInstruction. */ public void writeBaseUri (Object uri); public void writeComment(char[] chars, int offset, int length); public void writeProcessingInstruction(String target, char[] content, int offset, int length); public void writeCDATA(char[] chars, int offset, int length); // Maybe future? // public void setDocumentLocator(org.xml.sax.Locator locator); }
package net.argius.stew.ui.window; import static java.awt.EventQueue.invokeLater; import static java.awt.event.InputEvent.ALT_DOWN_MASK; import static java.awt.event.InputEvent.SHIFT_DOWN_MASK; import static java.awt.event.KeyEvent.VK_C; import static java.util.Collections.emptyList; import static java.util.Collections.nCopies; import static javax.swing.KeyStroke.getKeyStroke; import static net.argius.stew.text.TextUtilities.join; import static net.argius.stew.ui.window.AnyActionKey.copy; import static net.argius.stew.ui.window.AnyActionKey.refresh; import static net.argius.stew.ui.window.DatabaseInfoTree.ActionKey.*; import static net.argius.stew.ui.window.WindowOutputProcessor.showInformationMessageDialog; import java.awt.*; import java.awt.event.*; import java.io.*; import java.sql.*; import java.util.*; import java.util.Map.Entry; import java.util.List; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import net.argius.stew.*; /** * The Database Information Tree is a tree pane that provides to * display database object information from DatabaseMetaData. */ final class DatabaseInfoTree extends JTree implements AnyActionListener, TextSearch { enum ActionKey { copySimpleName, copyFullName, generateWherePhrase, generateSelectPhrase, generateUpdateStatement, generateInsertStatement, jumpToColumnByName, toggleShowColumnNumber } private static final Logger log = Logger.getLogger(DatabaseInfoTree.class); private static final ResourceManager res = ResourceManager.getInstance(DatabaseInfoTree.class); static volatile boolean showColumnNumber; private Connector currentConnector; private DatabaseMetaData dbmeta; private AnyActionListener anyActionListener; DatabaseInfoTree(AnyActionListener anyActionListener) { this.anyActionListener = anyActionListener; setRootVisible(false); setShowsRootHandles(false); setScrollsOnExpand(true); setCellRenderer(new Renderer()); setModel(new DefaultTreeModel(null)); // [Events] int sckm = Utilities.getMenuShortcutKeyMask(); AnyAction aa = new AnyAction(this); aa.bindKeyStroke(false, copy, KeyStroke.getKeyStroke(VK_C, sckm)); aa.bindSelf(copySimpleName, getKeyStroke(VK_C, sckm | ALT_DOWN_MASK)); aa.bindSelf(copyFullName, getKeyStroke(VK_C, sckm | SHIFT_DOWN_MASK)); } @Override protected void processMouseEvent(MouseEvent e) { super.processMouseEvent(e); if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() % 2 == 0) { anyActionPerformed(new AnyActionEvent(this, jumpToColumnByName)); } } @Override public void anyActionPerformed(AnyActionEvent ev) { log.atEnter("anyActionPerformed", ev); if (ev.isAnyOf(copySimpleName)) { copySimpleName(); } else if (ev.isAnyOf(copyFullName)) { copyFullName(); } else if (ev.isAnyOf(refresh)) { for (TreePath path : getSelectionPaths()) { refresh((InfoNode)path.getLastPathComponent()); } } else if (ev.isAnyOf(generateWherePhrase)) { generateWherePhrase(); } else if (ev.isAnyOf(generateSelectPhrase)) { generateSelectPhrase(); } else if (ev.isAnyOf(generateUpdateStatement)) { generateUpdateStatement(); } else if (ev.isAnyOf(generateInsertStatement)) { generateInsertStatement(); } else if (ev.isAnyOf(jumpToColumnByName)) { jumpToColumnByName(); } else if (ev.isAnyOf(toggleShowColumnNumber)) { showColumnNumber = !showColumnNumber; repaint(); } else { log.warn("not expected: Event=%s", ev); } log.atExit("anyActionPerformed"); } private void insertTextToTextArea(String s) { AnyActionEvent ev = new AnyActionEvent(this, ConsoleTextArea.ActionKey.insertText, s); anyActionListener.anyActionPerformed(ev); } private void copySimpleName() { TreePath[] paths = getSelectionPaths(); if (paths == null || paths.length == 0) { return; } List<String> names = new ArrayList<String>(paths.length); for (TreePath path : paths) { if (path == null) { continue; } Object o = path.getLastPathComponent(); assert o instanceof InfoNode; final String name; if (o instanceof ColumnNode) { name = ((ColumnNode)o).getName(); } else if (o instanceof TableNode) { name = ((TableNode)o).getName(); } else { name = o.toString(); } names.add(name); } ClipboardHelper.setStrings(names); } private void copyFullName() { TreePath[] paths = getSelectionPaths(); if (paths == null || paths.length == 0) { return; } List<String> names = new ArrayList<String>(paths.length); for (TreePath path : paths) { if (path == null) { continue; } Object o = path.getLastPathComponent(); assert o instanceof InfoNode; names.add(((InfoNode)o).getNodeFullName()); } ClipboardHelper.setStrings(names); } private void generateWherePhrase() { List<ColumnNode> columns = collectColumnNode(getSelectionPaths()); if (!columns.isEmpty()) { insertTextToTextArea(generateEquivalentJoinClause(columns)); } } private void generateSelectPhrase() { TreePath[] paths = getSelectionPaths(); List<ColumnNode> columns = collectColumnNode(paths); final String columnString; final List<String> tableNames; if (columns.isEmpty()) { List<TableNode> tableNodes = collectTableNode(paths); if (tableNodes.isEmpty()) { return; } tableNames = new ArrayList<String>(); for (final TableNode tableNode : tableNodes) { tableNames.add(tableNode.getNodeFullName()); } columnString = "*"; } else { List<String> columnNames = new ArrayList<String>(); tableNames = collectTableName(columns); final boolean one = tableNames.size() == 1; for (ColumnNode node : columns) { columnNames.add(one ? node.getName() : node.getNodeFullName()); } columnString = join(", ", columnNames); } final String tableString = join(",", tableNames); insertTextToTextArea(String.format("SELECT %s FROM %s WHERE ", columnString, tableString)); } private void generateUpdateStatement() { TreePath[] paths = getSelectionPaths(); List<ColumnNode> columns = collectColumnNode(paths); List<String> tableNames = collectTableName(columns); if (tableNames.isEmpty()) { return; } if (tableNames.size() != 1 || columns.isEmpty()) { showInformationMessageDialog(this, res.get("e.enables-select-just-1-table"), ""); return; } List<String> columnExpressions = new ArrayList<String>(); for (ColumnNode columnNode : columns) { columnExpressions.add(columnNode.getName() + "=?"); } insertTextToTextArea(String.format("UPDATE %s SET %s WHERE ", tableNames.get(0), join(",", columnExpressions))); } private void generateInsertStatement() { TreePath[] paths = getSelectionPaths(); List<ColumnNode> columns = collectColumnNode(paths); final String tableName; final int tableCount; if (columns.isEmpty()) { List<TableNode> tables = collectTableNode(paths); if (tables.isEmpty()) { return; } TableNode tableNode = tables.get(0); if (tableNode.getChildCount() == 0) { showInformationMessageDialog(this, res.get("i.can-only-use-after-tablenode-expanded"), ""); return; } @SuppressWarnings("unchecked") List<ColumnNode> list = Collections.list(tableNode.children()); columns.addAll(list); tableName = tableNode.getNodeFullName(); tableCount = tables.size(); } else { List<String> tableNames = collectTableName(columns); tableCount = tableNames.size(); if (tableCount == 0) { return; } tableName = tableNames.get(0); } if (tableCount != 1) { showInformationMessageDialog(this, res.get("e.enables-select-just-1-table"), ""); return; } List<String> columnNames = new ArrayList<String>(); for (ColumnNode node : columns) { columnNames.add(node.getName()); } final int columnCount = columnNames.size(); insertTextToTextArea(String.format("INSERT INTO %s (%s) VALUES (%s);%s", tableName, join(",", columnNames), join(",", nCopies(columnCount, "?")), join(",", nCopies(columnCount, "")))); } private void jumpToColumnByName() { TreePath[] paths = getSelectionPaths(); if (paths == null || paths.length == 0) { return; } final TreePath path = paths[0]; Object o = path.getLastPathComponent(); if (o instanceof ColumnNode) { ColumnNode node = (ColumnNode)o; AnyActionEvent ev = new AnyActionEvent(this, ResultSetTable.ActionKey.jumpToColumn, node.getName()); anyActionListener.anyActionPerformed(ev); } } private static List<ColumnNode> collectColumnNode(TreePath[] paths) { List<ColumnNode> a = new ArrayList<ColumnNode>(); if (paths != null) { for (TreePath path : paths) { InfoNode node = (InfoNode)path.getLastPathComponent(); if (node instanceof ColumnNode) { ColumnNode columnNode = (ColumnNode)node; a.add(columnNode); } } } return a; } private static List<TableNode> collectTableNode(TreePath[] paths) { List<TableNode> a = new ArrayList<TableNode>(); if (paths != null) { for (TreePath path : paths) { InfoNode node = (InfoNode)path.getLastPathComponent(); if (node instanceof TableNode) { TableNode columnNode = (TableNode)node; a.add(columnNode); } } } return a; } private static List<String> collectTableName(List<ColumnNode> columnNodes) { Set<String> tableNames = new LinkedHashSet<String>(); for (final ColumnNode node : columnNodes) { tableNames.add(node.getTableNode().getNodeFullName()); } return new ArrayList<String>(tableNames); } static String generateEquivalentJoinClause(List<ColumnNode> nodes) { if (nodes.isEmpty()) { return ""; } ListMap tm = new ListMap(); ListMap cm = new ListMap(); for (ColumnNode node : nodes) { final String tableName = node.getTableNode().getName(); final String columnName = node.getName(); tm.add(tableName, columnName); cm.add(columnName, String.format("%s.%s", tableName, columnName)); } List<String> expressions = new ArrayList<String>(); if (tm.size() == 1) { for (ColumnNode node : nodes) { expressions.add(String.format("%s=?", node.getName())); } } else { final String tableName = nodes.get(0).getTableNode().getName(); for (String c : tm.get(tableName)) { expressions.add(String.format("%s.%s=?", tableName, c)); } for (Entry<String, List<String>> entry : cm.entrySet()) { if (!entry.getKey().equals(tableName) && entry.getValue().size() == 1) { expressions.add(String.format("%s=?", entry.getValue().get(0))); } } for (Entry<String, List<String>> entry : cm.entrySet()) { Object[] a = entry.getValue().toArray(); final int n = a.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { expressions.add(String.format("%s=%s", a[i], a[j])); } } } } return join(" AND ", expressions) + ';'; } // text-search @Override public boolean search(Matcher matcher) { return search(resolveTargetPath(getSelectionPath()), matcher); } private static TreePath resolveTargetPath(TreePath path) { if (path != null) { TreePath parent = path.getParentPath(); if (parent != null) { return parent; } } return path; } private boolean search(TreePath path, Matcher matcher) { if (path == null) { return false; } TreeNode node = (TreeNode)path.getLastPathComponent(); if (node == null) { return false; } boolean found = false; found = matcher.find(node.toString()); if (found) { addSelectionPath(path); } else { removeSelectionPath(path); } if (!node.isLeaf() && node.getChildCount() >= 0) { @SuppressWarnings("unchecked") Iterable<DefaultMutableTreeNode> children = Collections.list(node.children()); for (DefaultMutableTreeNode child : children) { if (search(path.pathByAddingChild(child), matcher)) { found = true; } } } return found; } @Override public void reset() { // empty } // node expansion /** * Refreshes the root and its children. * @param env Environment * @throws SQLException */ void refreshRoot(Environment env) throws SQLException { Connector c = env.getCurrentConnector(); if (c == null) { if (log.isDebugEnabled()) { log.debug("not connected"); } currentConnector = null; return; } if (c == currentConnector && getModel().getRoot() != null) { if (log.isDebugEnabled()) { log.debug("not changed"); } return; } if (log.isDebugEnabled()) { log.debug("updating"); } // initializing models ConnectorNode connectorNode = new ConnectorNode(c.getName()); DefaultTreeModel model = new DefaultTreeModel(connectorNode); setModel(model); final DefaultTreeSelectionModel m = new DefaultTreeSelectionModel(); m.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); setSelectionModel(m); // initializing nodes final DatabaseMetaData dbmeta = env.getCurrentConnection().getMetaData(); final Set<InfoNode> createdStatusSet = new HashSet<InfoNode>(); expandNode(connectorNode, dbmeta); createdStatusSet.add(connectorNode); // events addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { TreePath path = event.getPath(); final Object lastPathComponent = path.getLastPathComponent(); if (!createdStatusSet.contains(lastPathComponent)) { InfoNode node = (InfoNode)lastPathComponent; if (node.isLeaf()) { return; } createdStatusSet.add(node); try { expandNode(node, dbmeta); } catch (SQLException ex) { throw new RuntimeException(ex); } } } @Override public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { // ignore } }); this.dbmeta = dbmeta; // showing model.reload(); setRootVisible(true); this.currentConnector = c; // auto-expansion try { File confFile = new File(Bootstrap.getDirectory(), "autoexpansion.tsv"); if (confFile.exists() && confFile.length() > 0) { AnyAction aa = new AnyAction(this); Scanner r = new Scanner(confFile); try { while (r.hasNextLine()) { final String line = r.nextLine(); if (line.matches("^\\s* continue; } aa.doParallel("expandNodes", Arrays.asList(line.split("\t"))); } } finally { r.close(); } } } catch (IOException ex) { throw new IllegalStateException(ex); } } void expandNodes(List<String> a) { long startTime = System.currentTimeMillis(); AnyAction aa = new AnyAction(this); int index = 1; while (index < a.size()) { final String s = a.subList(0, index + 1).toString(); for (int i = 0, n = getRowCount(); i < n; i++) { TreePath target; try { target = getPathForRow(i); } catch (IndexOutOfBoundsException ex) { // FIXME when IndexOutOfBoundsException was thrown at expandNodes log.warn(ex); break; } if (target != null && target.toString().equals(s)) { if (!isExpanded(target)) { aa.doLater("expandLater", target); Utilities.sleep(200L); } index++; break; } } if (System.currentTimeMillis() - startTime > 5000L) { break; // timeout } } } // called by expandNodes @SuppressWarnings("unused") private void expandLater(TreePath parent) { expandPath(parent); } /** * Refreshes a node and its children. * @param node */ void refresh(InfoNode node) { if (dbmeta == null) { return; } node.removeAllChildren(); final DefaultTreeModel model = (DefaultTreeModel)getModel(); model.reload(node); try { expandNode(node, dbmeta); } catch (SQLException ex) { throw new RuntimeException(ex); } } /** * Expands a node. * @param parent * @param dbmeta * @throws SQLException */ void expandNode(final InfoNode parent, final DatabaseMetaData dbmeta) throws SQLException { if (parent.isLeaf()) { return; } final DefaultTreeModel model = (DefaultTreeModel)getModel(); final InfoNode tmpNode = new InfoNode(res.get("i.paren-in-processing")) { @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { return Collections.emptyList(); } @Override public boolean isLeaf() { return true; } }; invokeLater(new Runnable() { @Override public void run() { model.insertNodeInto(tmpNode, parent, 0); } }); // asynchronous DaemonThreadFactory.execute(new Runnable() { @Override public void run() { try { final List<InfoNode> children = new ArrayList<InfoNode>(parent.createChildren(dbmeta)); invokeLater(new Runnable() { @Override public void run() { for (InfoNode child : children) { model.insertNodeInto(child, parent, parent.getChildCount()); } model.removeNodeFromParent(tmpNode); } }); } catch (SQLException ex) { throw new RuntimeException(ex); } } }); } /** * Clears (root). */ void clear() { for (TreeWillExpandListener listener : getListeners(TreeWillExpandListener.class).clone()) { removeTreeWillExpandListener(listener); } setModel(new DefaultTreeModel(null)); currentConnector = null; dbmeta = null; if (log.isDebugEnabled()) { log.debug("cleared"); } } @Override public TreePath[] getSelectionPaths() { TreePath[] a = super.getSelectionPaths(); if (a == null) { return new TreePath[0]; } return a; } // subclasses private static final class ListMap extends LinkedHashMap<String, List<String>> { ListMap() { // empty } void add(String key, String value) { if (get(key) == null) { put(key, new ArrayList<String>()); } get(key).add(value); } } private static class Renderer extends DefaultTreeCellRenderer { Renderer() { // empty } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof InfoNode) { setIcon(Utilities.getImageIcon(((InfoNode)value).getIconName())); } if (value instanceof ColumnNode) { if (showColumnNumber) { TreePath path = tree.getPathForRow(row); if (path != null) { TreePath parent = path.getParentPath(); if (parent != null) { final int index = row - tree.getRowForPath(parent); setText(String.format("%d %s", index, getText())); } } } } return this; } } private abstract static class InfoNode extends DefaultMutableTreeNode { InfoNode(Object userObject) { super(userObject, true); } @Override public boolean isLeaf() { return false; } abstract protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException; String getIconName() { final String className = getClass().getName(); final String nodeType = className.replaceFirst(".+?([^\\$]+)Node$", "$1"); return "node-" + nodeType.toLowerCase() + ".png"; } protected String getNodeFullName() { return String.valueOf(userObject); } static List<TableTypeNode> getTableTypeNodes(DatabaseMetaData dbmeta, String catalog, String schema) throws SQLException { List<TableTypeNode> a = new ArrayList<TableTypeNode>(); ResultSet rs = dbmeta.getTableTypes(); try { while (rs.next()) { TableTypeNode typeNode = new TableTypeNode(catalog, schema, rs.getString(1)); if (typeNode.hasItems(dbmeta)) { a.add(typeNode); } } } finally { rs.close(); } if (a.isEmpty()) { a.add(new TableTypeNode(catalog, schema, "TABLE")); } return a; } } private static class ConnectorNode extends InfoNode { ConnectorNode(String name) { super(name); } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); if (dbmeta.supportsCatalogsInDataManipulation()) { ResultSet rs = dbmeta.getCatalogs(); try { while (rs.next()) { a.add(new CatalogNode(rs.getString(1))); } } finally { rs.close(); } } else if (dbmeta.supportsSchemasInDataManipulation()) { ResultSet rs = dbmeta.getSchemas(); try { while (rs.next()) { a.add(new SchemaNode(null, rs.getString(1))); } } finally { rs.close(); } } else { a.addAll(getTableTypeNodes(dbmeta, null, null)); } return a; } } private static final class CatalogNode extends InfoNode { private final String name; CatalogNode(String name) { super(name); this.name = name; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); if (dbmeta.supportsSchemasInDataManipulation()) { ResultSet rs = dbmeta.getSchemas(); try { while (rs.next()) { a.add(new SchemaNode(name, rs.getString(1))); } } finally { rs.close(); } } else { a.addAll(getTableTypeNodes(dbmeta, name, null)); } return a; } } private static final class SchemaNode extends InfoNode { private final String catalog; private final String schema; SchemaNode(String catalog, String schema) { super(schema); this.catalog = catalog; this.schema = schema; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); a.addAll(getTableTypeNodes(dbmeta, catalog, schema)); return a; } } private static final class TableTypeNode extends InfoNode { private static final String ICON_NAME_FORMAT = "node-tabletype-%s.png"; private final String catalog; private final String schema; private final String tableType; TableTypeNode(String catalog, String schema, String tableType) { super(tableType); this.catalog = catalog; this.schema = schema; this.tableType = tableType; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); ResultSet rs = dbmeta.getTables(catalog, schema, null, new String[]{tableType}); try { while (rs.next()) { final String table = rs.getString(3); final String type = rs.getString(4); final boolean kindOfTable = type.matches("TABLE|VIEW|SYNONYM"); a.add(new TableNode(catalog, schema, table, kindOfTable)); } } finally { rs.close(); } return a; } @Override String getIconName() { final String name = String.format(ICON_NAME_FORMAT, getUserObject()); if (getClass().getResource("icon/" + name) == null) { return String.format(ICON_NAME_FORMAT, ""); } return name; } boolean hasItems(DatabaseMetaData dbmeta) throws SQLException { ResultSet rs = dbmeta.getTables(catalog, schema, null, new String[]{tableType}); try { return rs.next(); } finally { rs.close(); } } } static final class TableNode extends InfoNode { private final String catalog; private final String schema; private final String name; private final boolean kindOfTable; TableNode(String catalog, String schema, String name, boolean kindOfTable) { super(name); this.catalog = catalog; this.schema = schema; this.name = name; this.kindOfTable = kindOfTable; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { List<InfoNode> a = new ArrayList<InfoNode>(); ResultSet rs = dbmeta.getColumns(catalog, schema, name, null); try { while (rs.next()) { a.add(new ColumnNode(rs.getString(4), rs.getString(6), rs.getInt(7), rs.getString(18), this)); } } finally { rs.close(); } return a; } @Override public boolean isLeaf() { return false; } @Override protected String getNodeFullName() { List<String> a = new ArrayList<String>(); if (catalog != null) { a.add(catalog); } if (schema != null) { a.add(schema); } a.add(name); return join(".", a); } String getName() { return name; } boolean isKindOfTable() { return kindOfTable; } } static final class ColumnNode extends InfoNode { private final String name; private final TableNode tableNode; ColumnNode(String name, String type, int size, String nulls, TableNode tableNode) { super(format(name, type, size, nulls)); setAllowsChildren(false); this.name = name; this.tableNode = tableNode; } String getName() { return name; } TableNode getTableNode() { return tableNode; } private static String format(String name, String type, int size, String nulls) { final String nonNull = "NO".equals(nulls) ? " NOT NULL" : ""; return String.format("%s [%s(%d)%s]", name, type, size, nonNull); } @Override public boolean isLeaf() { return true; } @Override protected List<InfoNode> createChildren(DatabaseMetaData dbmeta) throws SQLException { return emptyList(); } @Override protected String getNodeFullName() { return String.format("%s.%s", tableNode.getNodeFullName(), name); } } }
package net.sensnet.node.pages; import java.io.IOException; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sensnet.node.InvalidNodeAuthException; import net.sensnet.node.dbobjects.DataPoint; public class DataPointSubmitPage extends APIPage { public static final String PATH = "/api/submit/datapoint"; public DataPointSubmitPage(String name) { super(name); } @Override public void doAction(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, InvalidNodeAuthException { DataPoint dp = new DataPoint(req); dp.commit(); } }
package net.starbs.antipleurdawn.client; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import net.starbs.antipleurdawn.exceptions.HttpClientException; import net.starbs.antipleurdawn.exceptions.HttpServerException; public class HttpClient { private String uri; public HttpClient(String uri) { this.uri = uri; } public Response send(String route) throws IOException, HttpServerException, HttpClientException { URL url = new URL(uri + route); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "antiplerdawn/1.0"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); try { String inputLine; StringBuffer buffer = new StringBuffer(); while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } Response response = new Response(con.getResponseCode(), buffer.toString()); if (response.getCode() >= 300) { if (response.getCode() >= 500) { throw new HttpServerException(response); } else { throw new HttpClientException(response); } } return response; } finally { in.close(); } } }
package org.bouncycastle.jce.provider; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.SignatureSpi; import java.security.interfaces.DSAKey; import java.security.spec.AlgorithmParameterSpec; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.GOST3410Key; import org.bouncycastle.jce.provider.util.NullDigest; public class JDKDSASigner extends SignatureSpi implements PKCSObjectIdentifiers, X509ObjectIdentifiers { private Digest digest; private DSA signer; private SecureRandom random; protected JDKDSASigner( Digest digest, DSA signer) { this.digest = digest; this.signer = signer; } protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { CipherParameters param; if (publicKey instanceof GOST3410Key) { param = GOST3410Util.generatePublicKeyParameter(publicKey); } else if (publicKey instanceof DSAKey) { param = DSAUtil.generatePublicKeyParameter(publicKey); } else { try { byte[] bytes = publicKey.getEncoded(); publicKey = JDKKeyFactory.createPublicKeyFromDERStream(bytes); if (publicKey instanceof DSAKey) { param = DSAUtil.generatePublicKeyParameter(publicKey); } else { throw new InvalidKeyException("can't recognise key type in DSA based signer"); } } catch (Exception e) { throw new InvalidKeyException("can't recognise key type in DSA based signer"); } } digest.reset(); signer.init(false, param); } protected void engineInitSign( PrivateKey privateKey, SecureRandom random) throws InvalidKeyException { this.random = random; engineInitSign(privateKey); } protected void engineInitSign( PrivateKey privateKey) throws InvalidKeyException { CipherParameters param; if (privateKey instanceof GOST3410Key) { param = GOST3410Util.generatePrivateKeyParameter(privateKey); } else { param = DSAUtil.generatePrivateKeyParameter(privateKey); } if (random != null) { param = new ParametersWithRandom(param, random); } digest.reset(); signer.init(true, param); } protected void engineUpdate( byte b) throws SignatureException { digest.update(b); } protected void engineUpdate( byte[] b, int off, int len) throws SignatureException { digest.update(b, off, len); } protected byte[] engineSign() throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); try { BigInteger[] sig = signer.generateSignature(hash); return derEncode(sig[0], sig[1]); } catch (Exception e) { throw new SignatureException(e.toString()); } } protected boolean engineVerify( byte[] sigBytes) throws SignatureException { byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); BigInteger[] sig; try { sig = derDecode(sigBytes); } catch (Exception e) { throw new SignatureException("error decoding signature bytes."); } return signer.verifySignature(hash, sig[0], sig[1]); } protected void engineSetParameter( AlgorithmParameterSpec params) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated replaced with <a href = "#engineSetParameter(java.security.spec.AlgorithmParameterSpec)"> */ protected void engineSetParameter( String param, Object value) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } /** * @deprecated */ protected Object engineGetParameter( String param) { throw new UnsupportedOperationException("engineSetParameter unsupported"); } private byte[] derEncode( BigInteger r, BigInteger s) throws IOException { DERInteger[] rs = new DERInteger[]{ new DERInteger(r), new DERInteger(s) }; return new DERSequence(rs).getEncoded(ASN1Encodable.DER); } private BigInteger[] derDecode( byte[] encoding) throws IOException { ASN1Sequence s = (ASN1Sequence)ASN1Object.fromByteArray(encoding); return new BigInteger[]{ ((DERInteger)s.getObjectAt(0)).getValue(), ((DERInteger)s.getObjectAt(1)).getValue() }; } static public class stdDSA extends JDKDSASigner { public stdDSA() { super(new SHA1Digest(), new DSASigner()); } } static public class dsa224 extends JDKDSASigner { public dsa224() { super(new SHA224Digest(), new DSASigner()); } } static public class dsa256 extends JDKDSASigner { public dsa256() { super(new SHA256Digest(), new DSASigner()); } } static public class dsa384 extends JDKDSASigner { public dsa384() { super(new SHA384Digest(), new DSASigner()); } } static public class dsa512 extends JDKDSASigner { public dsa512() { super(new SHA512Digest(), new DSASigner()); } } static public class noneDSA extends JDKDSASigner { public noneDSA() { super(new NullDigest(), new DSASigner()); } } }
package org.nschmidt.ldparteditor.data; import java.io.Serializable; /** * @author nils * */ public final class PGDataProxy extends PGData implements Serializable { private static final long serialVersionUID = 1L; private transient PGData data; private transient boolean initialised = false; public PGDataProxy(PGData proxy) { data = proxy; } @Override public void drawBFCprimitive(int drawOnlyMode) { if (initialised) { data.drawBFCprimitive(drawOnlyMode); } else { initialised = true; switch (data.type()) { case 2: data = PGData2.clone((PGData2) data); break; case 3: data = PGData3.clone((PGData3) data); break; case 4: data = PGData4.clone((PGData4) data); break; case 5: data = PGData5.clone((PGData5) data); break; case 6: data = PGDataBFC.clone((PGDataBFC) data); break; default: initialised = false; } } } @Override public int type() { return data.type(); } @Override public PGData data() { return data; } }
package org.nutz.ioc.aop.impl; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.nutz.aop.ClassAgent; import org.nutz.aop.ClassDefiner; import org.nutz.aop.DefaultClassDefiner; import org.nutz.aop.MethodInterceptor; import org.nutz.aop.asm.AsmClassAgent; import org.nutz.ioc.Ioc; import org.nutz.ioc.aop.MirrorFactory; import org.nutz.ioc.aop.config.AopConfigration; import org.nutz.ioc.aop.config.InterceptorPair; import org.nutz.ioc.aop.config.impl.AnnotationAopConfigration; import org.nutz.ioc.aop.config.impl.ComboAopConfigration; import org.nutz.lang.Mirror; import org.nutz.log.Log; import org.nutz.log.Logs; /** * AopConfigration, * * @author zozoh(zozohtnt@gmail.com) * @author Wendal(wendal1985@gmail.com) */ public class DefaultMirrorFactory implements MirrorFactory { private static final Log log = Logs.get(); private Ioc ioc; private ClassDefiner cd; private List<AopConfigration> list; private static final Object lock = new Object(); public DefaultMirrorFactory(Ioc ioc) { this.ioc = ioc; } public <T> Mirror<T> getMirror(Class<T> type, String name) { if (MethodInterceptor.class.isAssignableFrom(type) || type.getName().endsWith(ClassAgent.CLASSNAME_SUFFIX) || (name != null && name.startsWith(AopConfigration.IOCNAME)) || AopConfigration.class.isAssignableFrom(type) || Modifier.isAbstract(type.getModifiers())) { return Mirror.me(type); } if (list == null) { List<AopConfigration> tmp = new ArrayList<AopConfigration>(); boolean flag = true; String[] names = ioc.getNames(); Arrays.sort(names); for (String beanName : names) { if (!beanName.startsWith(AopConfigration.IOCNAME)) continue; AopConfigration cnf = ioc.get(AopConfigration.class, beanName); tmp.add(cnf); if (cnf instanceof AnnotationAopConfigration) flag = false; if (cnf instanceof ComboAopConfigration) { if (((ComboAopConfigration) cnf).hasAnnotationAop()) { flag = false; } } } if (flag) tmp.add(new AnnotationAopConfigration()); list = tmp; } List<InterceptorPair> interceptorPairs = new ArrayList<InterceptorPair>(); for (AopConfigration cnf : list) { List<InterceptorPair> tmp = cnf.getInterceptorPairList(ioc, type); if (tmp != null) interceptorPairs.addAll(tmp); } if (interceptorPairs.isEmpty()) { if (log.isDebugEnabled()) log.debugf("%s , no config to enable AOP for this type.", type); return Mirror.me(type); } int mod = type.getModifiers(); if (Modifier.isFinal(mod) || Modifier.isAbstract(mod)) { log.info("%s configure to use aop, but it is final/abstract, skip it"); return Mirror.me(type); } synchronized (lock) { // nutz.jarjava.ext.dirs,DefaultMirrorFactoryclassloader if (cd == null) { cd = DefaultClassDefiner.defaultOne(); } ClassAgent agent = new AsmClassAgent(); for (InterceptorPair interceptorPair : interceptorPairs) agent.addInterceptor(interceptorPair.getMethodMatcher(), interceptorPair.getMethodInterceptor()); return Mirror.me(agent.define(cd, type)); } } public void setAopConfigration(AopConfigration aopConfigration) { this.list = new ArrayList<AopConfigration>(); this.list.add(aopConfigration); } }
package org.opencms.importexport; import org.opencms.main.OpenCms; import org.opencms.report.I_CmsReport; import org.opencms.util.CmsUUID; import com.opencms.core.CmsException; import com.opencms.core.I_CmsConstants; import com.opencms.file.CmsObject; import com.opencms.file.CmsResource; import com.opencms.file.CmsResourceTypeFolder; import com.opencms.file.CmsResourceTypeLink; import com.opencms.file.CmsResourceTypePage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.zip.ZipFile; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Implementation of the OpenCms Import Interface (@see org.opencms.importexport.I_CmsImport) for * the import version 4. <p> * * This import format is used in OpenCms since 5.1.6. * @see org.opencms.importexport.A_CmsImport * * @author Michael Emmerich (m.emmerich@alkacon.com) */ public class CmsImportVersion4 extends A_CmsImport { /** * Creates a new CmsImportVerion4 object.<p> */ public CmsImportVersion4() { m_importVersion = 4; } /** * Returns the import version of the import implementation.<p> * * @return import version */ public int getVersion() { return 4; } /** * Imports the resources for a module.<p> * @param cms the current cms object * @param importPath the path in the cms VFS to import into * @param report a report object to output the progress information to * @param digest digest for taking a fingerprint of the files * @param importResource the import-resource (folder) to load resources from * @param importZip the import-resource (zip) to load resources from * @param docXml the xml manifest-file * @param excludeList filenames of files and folders which should not * be (over)written in the virtual file system (not used when null) * @param writtenFilenames filenames of the files and folder which have actually been * successfully written (not used when null) * @param fileCodes code of the written files (for the registry) * (not used when null) * @param propertyName name of a property to be added to all resources * @param propertyValue value of that property * @throws CmsException if something goes wrong */ public void importResources(CmsObject cms, String importPath, I_CmsReport report, MessageDigest digest, File importResource, ZipFile importZip, Document docXml, Vector excludeList, Vector writtenFilenames, Vector fileCodes, String propertyName, String propertyValue) throws CmsException { // initialize the import m_cms = cms; m_importPath = importPath; m_report = report; m_digest = digest; m_importResource = importResource; m_importZip = importZip; m_docXml = docXml; m_importingChannelData = false; m_linkStorage = new HashMap(); m_linkPropertyStorage = new HashMap(); try { // first import the user information if (m_cms.isAdmin()) { importGroups(); importUsers(); } // now import the VFS resources importAllResources(excludeList, propertyName, propertyValue); convertPointerToLinks(); } catch (CmsException e) { throw e; } } /** * Imports the groups and writes them to the cms.<p> * * @throws CmsException if something goes wrong */ private void importGroups() throws CmsException { NodeList groupNodes; Element currentElement; String name, description, flags, parentgroup; try { // getAll group nodes groupNodes = m_docXml.getElementsByTagName(I_CmsConstants.C_EXPORT_TAG_GROUPDATA); // walk through all groups in manifest for (int i = 0; i < groupNodes.getLength(); i++) { currentElement = (Element)groupNodes.item(i); name = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_NAME); name = OpenCms.getDefaultUsers().translateGroup(name); description = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DESCRIPTION); flags = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_FLAGS); parentgroup = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_PARENTGROUP); if ((parentgroup!=null) && (parentgroup.length()>0)) { parentgroup = OpenCms.getDefaultUsers().translateGroup(parentgroup); } // import this group importGroup(null, name, description, flags, parentgroup); } // now try to import the groups in the stack while (!m_groupsToCreate.empty()) { Stack tempStack = m_groupsToCreate; m_groupsToCreate = new Stack(); while (tempStack.size() > 0) { Hashtable groupdata = (Hashtable)tempStack.pop(); name = (String)groupdata.get(I_CmsConstants.C_EXPORT_TAG_NAME); description = (String)groupdata.get(I_CmsConstants.C_EXPORT_TAG_DESCRIPTION); flags = (String)groupdata.get(I_CmsConstants.C_EXPORT_TAG_FLAGS); parentgroup = (String)groupdata.get(I_CmsConstants.C_EXPORT_TAG_PARENTGROUP); // try to import the group importGroup(null, name, description, flags, parentgroup); } } } catch (Exception exc) { m_report.println(exc); throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc); } } /** * Imports the users and writes them to the cms.<p> * * @throws CmsException if something goes wrong */ private void importUsers() throws CmsException { NodeList userNodes; NodeList groupNodes; Element currentElement, currentGroup; Vector userGroups; Hashtable userInfo = new Hashtable(); sun.misc.BASE64Decoder dec; String name, description, flags, password, recoveryPassword, firstname, lastname, email, address, section, defaultGroup, type, pwd, infoNode; // try to get the import resource //getImportResource(); try { // getAll user nodes userNodes = m_docXml.getElementsByTagName(I_CmsConstants.C_EXPORT_TAG_USERDATA); // walk threw all groups in manifest for (int i = 0; i < userNodes.getLength(); i++) { currentElement = (Element)userNodes.item(i); name = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_NAME); name = OpenCms.getDefaultUsers().translateUser(name); // decode passwords using base 64 decoder dec = new sun.misc.BASE64Decoder(); pwd = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_PASSWORD); password = new String(dec.decodeBuffer(pwd.trim())); dec = new sun.misc.BASE64Decoder(); pwd = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_RECOVERYPASSWORD); recoveryPassword = new String(dec.decodeBuffer(pwd.trim())); description = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DESCRIPTION); flags = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_FLAGS); firstname = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_FIRSTNAME); lastname = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_LASTNAME); email = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_EMAIL); address = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_ADDRESS); section = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_SECTION); defaultGroup = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DEFAULTGROUP); type = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_TYPE); // get the userinfo and put it into the hashtable infoNode = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_USERINFO); try { // read the userinfo from the dat-file byte[] value = getFileBytes(infoNode); // deserialize the object ByteArrayInputStream bin = new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); userInfo = (Hashtable)oin.readObject(); } catch (IOException ioex) { m_report.println(ioex); } // get the groups of the user and put them into the vector groupNodes = currentElement.getElementsByTagName(I_CmsConstants.C_EXPORT_TAG_GROUPNAME); userGroups = new Vector(); for (int j = 0; j < groupNodes.getLength(); j++) { currentGroup = (Element)groupNodes.item(j); String userInGroup=getTextNodeValue(currentGroup, I_CmsConstants.C_EXPORT_TAG_NAME); userInGroup = OpenCms.getDefaultUsers().translateGroup(userInGroup); userGroups.addElement(userInGroup); } // import this user importUser(null, name, description, flags, password, recoveryPassword, firstname, lastname, email, address, section, defaultGroup, type, userInfo, userGroups); } } catch (Exception exc) { m_report.println(exc); throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc); } } /** * Imports the resources and writes them to the cms.<p> * * * @param excludeList filenames of files and folders which should not * be (over)written in the virtual file system (not used when null) * @param propertyName name of a property to be added to all resources * @param propertyValue value of that property * @throws CmsException if something goes wrong */ private void importAllResources(Vector excludeList, String propertyName, String propertyValue) throws CmsException { String source, destination, type, uuidresource, uuidcontent, userlastmodified, usercreated, flags, timestamp; long datelastmodified, datecreated; int resType; NodeList fileNodes, acentryNodes; Element currentElement, currentEntry; Map properties = null; if (m_importingChannelData) { m_cms.getRequestContext().saveSiteRoot(); m_cms.setContextToCos(); } // clear some required structures at the init phase of the import if (excludeList == null) { excludeList = new Vector(); } // get list of unwanted properties List deleteProperties = (List)OpenCms.getRuntimeProperty("compatibility.support.import.remove.propertytags"); if (deleteProperties == null) { deleteProperties = new ArrayList(); } // get list of immutable resources List immutableResources = (List)OpenCms.getRuntimeProperty("import.immutable.resources"); if (immutableResources == null) { immutableResources = new ArrayList(); } try { // get all file-nodes fileNodes = m_docXml.getElementsByTagName(I_CmsConstants.C_EXPORT_TAG_FILE); int importSize = fileNodes.getLength(); // walk through all files in manifest for (int i = 0; i < fileNodes.getLength(); i++) { m_report.print(" ( " + (i + 1) + " / " + importSize + " ) ", I_CmsReport.C_FORMAT_NOTE); currentElement = (Element)fileNodes.item(i); // get all information for a file-import // <source> source = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_SOURCE); // <destintion> destination = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DESTINATION); // <type> type = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_TYPE); resType = m_cms.getResourceTypeId(type); // <uuidresource> uuidresource = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_UUIDRESOURCE); // <uuidcontent> uuidcontent = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_UUIDCONTENT); // <datelastmodified> if ((timestamp = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DATELASTMODIFIED)) != null) { datelastmodified = Long.parseLong(timestamp); } else { datelastmodified = System.currentTimeMillis(); } // <userlastmodified> userlastmodified = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_USERLASTMODIFIED); userlastmodified = OpenCms.getDefaultUsers().translateUser(userlastmodified); // <datecreated> if ((timestamp = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DATECREATED)) != null) { datecreated = Long.parseLong(timestamp); } else { datecreated = System.currentTimeMillis(); } // <usercreated> usercreated = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_USERCREATED); usercreated = OpenCms.getDefaultUsers().translateUser(usercreated); // <flags> flags = getTextNodeValue(currentElement, I_CmsConstants.C_EXPORT_TAG_FLAGS); String translatedName = m_cms.getRequestContext().addSiteRoot(m_importPath + destination); if (CmsResourceTypeFolder.C_RESOURCE_TYPE_NAME.equals(type)) { translatedName += I_CmsConstants.C_FOLDER_SEPARATOR; } // translate the name during import translatedName = m_cms.getRequestContext().getDirectoryTranslator().translateResource(translatedName); // check if this resource is immutable boolean resourceNotImmutable = checkImmutable(translatedName, immutableResources); translatedName = m_cms.getRequestContext().removeSiteRoot(translatedName); // if the resource is not immutable and not on the exclude list, import it if (resourceNotImmutable && (!excludeList.contains(translatedName))) { // print out the information to the report m_report.print(m_report.key("report.importing"), I_CmsReport.C_FORMAT_NOTE); m_report.print(translatedName); m_report.print(m_report.key("report.dots"), I_CmsReport.C_FORMAT_NOTE); // get all properties properties = getPropertiesFromXml(currentElement, resType, propertyName, propertyValue, deleteProperties); // import the resource CmsResource res = importResource(source, destination, resType, uuidresource, uuidcontent, datelastmodified, userlastmodified, datecreated, usercreated, flags, properties); // if the resource was imported add the access control entrys if available if (res != null) { // write all imported access control entries for this file acentryNodes = currentElement.getElementsByTagName(I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_ENTRY); // collect all access control entries for (int j = 0; j < acentryNodes.getLength(); j++) { currentEntry = (Element)acentryNodes.item(j); // get the data of the access control entry String id = getTextNodeValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_PRINCIPAL); String principalId=new CmsUUID().toString(); String principal=id.substring(id.indexOf(".")+1, id.length()); if (id.startsWith(I_CmsConstants.C_EXPORT_ACEPRINCIPAL_GROUP)) { principal = OpenCms.getDefaultUsers().translateGroup(principal); principalId=m_cms.readGroup(principal).getId().toString(); } else { principal = OpenCms.getDefaultUsers().translateUser(principal); principalId=m_cms.readUser(principal).getId().toString(); } String acflags = getTextNodeValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_FLAGS); String allowed = getTextNodeValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_ALLOWEDPERMISSIONS); String denied = getTextNodeValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_DENIEDPERMISSIONS); // add the entry to the list addImportAccessControlEntry(res, principalId, allowed, denied, acflags); } importAccessControlEntries(res); } else { // resource import failed, since no CmsResource was created m_report.print(m_report.key("report.skipping"), I_CmsReport.C_FORMAT_NOTE); m_report.println(translatedName); } } else { // skip the file import, just print out the information to the report m_report.print(m_report.key("report.skipping"), I_CmsReport.C_FORMAT_NOTE); m_report.println(translatedName); } } } catch (Exception exc) { m_report.println(exc); throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if (m_importingChannelData) { m_cms.getRequestContext().restoreSiteRoot(); } } } /** * Imports a resource (file or folder) into the cms.<p> * * @param source the path to the source-file * @param destination the path to the destination-file in the cms * @param resType the resource-type of the file * @param uuidresource the resource uuid of the resource * @param uuidcontent the file uuid of the resource * @param datelastmodified the last modification date of the resource * @param userlastmodified the user who made the last modifications to the resource * @param datecreated the creation date of the resource * @param usercreated the user who created * @param flags the flags of the resource * @param properties a hashtable with properties for this resource * @return imported resource */ private CmsResource importResource( String source, String destination, int resType, String uuidresource, String uuidcontent, long datelastmodified, String userlastmodified, long datecreated, String usercreated, String flags, Map properties ) { byte[] content = null; CmsResource res = null; try { // get the file content if (source != null) { content = getFileBytes(source); } int size = 0; if (content != null) { size = content.length; } // get UUIDs for the user CmsUUID newUserlastmodified; CmsUUID newUsercreated; // check if user created and user lastmodified are valid users in this system. // if not, use the current user try { newUserlastmodified = m_cms.readUser(userlastmodified).getId(); } catch (CmsException e) { newUserlastmodified = m_cms.getRequestContext().currentUser().getId(); // datelastmodified = System.currentTimeMillis(); } try { newUsercreated = m_cms.readUser(usercreated).getId(); } catch (CmsException e) { newUsercreated = m_cms.getRequestContext().currentUser().getId(); // datecreated = System.currentTimeMillis(); } // get UUIDs for the resource and content CmsUUID newUuidresource; if ((uuidresource != null) && (resType != CmsResourceTypeFolder.C_RESOURCE_TYPE_ID)) { newUuidresource = new CmsUUID(uuidresource); } else { newUuidresource = new CmsUUID(); } CmsUUID newUuidcontent; if (uuidcontent != null) { newUuidcontent = new CmsUUID(uuidcontent); } else { newUuidcontent = new CmsUUID(); } // extract the name of the resource form the destination String resname = destination; if (resname.endsWith("/")) { resname = resname.substring(0, resname.length() - 1); } if (resname.lastIndexOf("/") > 0) { resname = resname.substring(resname.lastIndexOf("/") + 1, resname.length()); } // create a new CmsResource CmsResource resource = new CmsResource( new CmsUUID(), // structure ID is always a new UUID newUuidresource, CmsUUID.getNullUUID(), newUuidcontent, resname, resType, new Integer(flags).intValue(), m_cms.getRequestContext().currentProject().getId(), I_CmsConstants.C_STATE_NEW, m_cms.getResourceType(resType).getLoaderId(), datecreated, newUsercreated, datelastmodified, newUserlastmodified, size, 1 ); if (resType==CmsResourceTypeLink.C_RESOURCE_TYPE_ID) { // store links for later conversion m_report.print(m_report.key("report.storing_link"), I_CmsReport.C_FORMAT_NOTE); m_linkStorage.put(m_importPath + destination, new String(content)); m_linkPropertyStorage.put(m_importPath + destination, properties); res = resource; } else { // import this resource in the VFS res = m_cms.importResource(resource, content, properties, m_importPath + destination); } if (res != null) { if (CmsResourceTypePage.C_RESOURCE_TYPE_ID == resType) { m_importedPages.add(I_CmsConstants.C_FOLDER_SEPARATOR + destination); } m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK); } } catch (Exception exc) { // an error while importing the file m_report.println(exc); try { // Sleep some time after an error so that the report output has a chance to keep up Thread.sleep(1000); } catch (Exception e) { } } return res; } }
package org.opencms.workplace.tools; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsResource; import org.opencms.i18n.CmsEncoder; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.util.CmsRequestUtil; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsDialog; import org.opencms.workplace.CmsWorkplace; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import org.apache.commons.logging.Log; /** * Manages the registered tools, actualizing its state every time the workplace is reinitialize.<p> * * Manages also the configuration settings for the administration view, and provides * several tool related methods.<p> * * @author Michael Moossen * * @version $Revision: 1.47 $ * * @since 6.0.0 */ public class CmsToolManager { /** Root location of the administration view. */ public static final String ADMINVIEW_ROOT_LOCATION = CmsWorkplace.PATH_WORKPLACE + "views/admin"; /** Property definition name to look for. */ public static final String HANDLERCLASS_PROPERTY = "admintoolhandler-class"; /** Navigation bar separator (html code). */ public static final String NAVBAR_SEPARATOR = "\n&nbsp;&gt;&nbsp;\n"; /** Tool root separator. */ public static final String ROOT_SEPARATOR = ":"; /** Key for the default tool root, if there is no configured root with this a key, a new one will be configured. */ public static final String ROOTKEY_DEFAULT = "admin"; /** Tool path separator. */ public static final String TOOLPATH_SEPARATOR = "/"; /** Location of the default admin view jsp page. */ public static final String VIEW_JSPPAGE_LOCATION = ADMINVIEW_ROOT_LOCATION + "/admin-main.jsp"; /** The static log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsToolManager.class); /** List of all available roots. */ private final CmsIdentifiableObjectContainer m_roots; /** List of all available tools. */ private final CmsIdentifiableObjectContainer m_tools; /** List of all available urls and related tool paths. */ private final CmsIdentifiableObjectContainer m_urls; /** * Default constructor.<p> */ public CmsToolManager() { m_roots = new CmsIdentifiableObjectContainer(true, false); m_tools = new CmsIdentifiableObjectContainer(true, false); m_urls = new CmsIdentifiableObjectContainer(false, false); } /** * Returns the OpenCms link for the given tool path which requires no parameters.<p> * * @param jsp the jsp action element * @param toolPath the tool path * * @return the OpenCms link for the given tool path which requires parameters */ public static String linkForToolPath(CmsJspActionElement jsp, String toolPath) { StringBuffer result = new StringBuffer(); result.append(jsp.link(VIEW_JSPPAGE_LOCATION)); result.append('?'); result.append(CmsToolDialog.PARAM_PATH); result.append('='); result.append(CmsEncoder.encode(toolPath)); return result.toString(); } /** * Returns the OpenCms link for the given tool path which requires parameters.<p> * * Please note: Don't overuse the parameter map because this will likely introduce issues * with encoding. If possible, don't pass parameters at all, or only very simple parameters * with no special chars that can easily be parsed.<p> * * @param jsp the jsp action element * @param toolPath the tool path * @param params the map of required tool parameters * * @return the OpenCms link for the given tool path which requires parameters */ public static String linkForToolPath(CmsJspActionElement jsp, String toolPath, Map params) { if (params == null) { // no parameters - take the shortcut return linkForToolPath(jsp, toolPath); } params.put(CmsToolDialog.PARAM_PATH, toolPath); return CmsRequestUtil.appendParameters(jsp.link(VIEW_JSPPAGE_LOCATION), params, true); } /** * Adds a new tool root to the tool manager.<p> * * @param toolRoot the tool root to add */ public void addToolRoot(CmsToolRootHandler toolRoot) { m_roots.addIdentifiableObject(toolRoot.getKey(), toolRoot); } /** * Called by the <code>{@link org.opencms.workplace.CmsWorkplaceManager#initialize(CmsObject)}</code> method.<p> * * @param cms the admin cms context */ public void configure(CmsObject cms) { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_TOOLMANAGER_CREATED_0)); } if (m_roots.getObject(ROOTKEY_DEFAULT) == null) { CmsToolRootHandler defToolRoot = new CmsToolRootHandler(); defToolRoot.setKey(ROOTKEY_DEFAULT); defToolRoot.setUri(CmsWorkplace.PATH_WORKPLACE + "admin/"); defToolRoot.setName("${key." + Messages.GUI_ADMIN_VIEW_ROOT_NAME_0 + "}"); defToolRoot.setHelpText("${key." + Messages.GUI_ADMIN_VIEW_ROOT_HELP_0 + "}"); addToolRoot(defToolRoot); } m_tools.clear(); m_urls.clear(); Iterator it = getToolRoots().iterator(); while (it.hasNext()) { CmsToolRootHandler toolRoot = (CmsToolRootHandler)it.next(); if (!cms.existsResource(toolRoot.getUri())) { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_ROOT_SKIPPED_2, toolRoot.getKey(), toolRoot.getUri())); } continue; } try { toolRoot.setup(cms, null, toolRoot.getUri()); configureToolRoot(cms, toolRoot); // log info if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_SETUP_1, toolRoot.getKey())); } } catch (CmsException e) { // log failure if (CmsLog.INIT.isWarnEnabled()) { CmsLog.INIT.warn(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_SETUP_ERROR_1, toolRoot.getKey()), e); } } } } /** * Returns the navigation bar html code for the given tool path.<p> * * @param toolPath the path * @param wp the jsp page * * @return the html code */ public String generateNavBar(String toolPath, CmsWorkplace wp) { if (toolPath.equals(getBaseToolPath(wp))) { return "<div class='pathbar'>&nbsp;</div>\n"; } CmsTool adminTool = resolveAdminTool(getCurrentRoot(wp).getKey(), toolPath); String html = A_CmsHtmlIconButton.defaultButtonHtml(CmsHtmlIconButtonStyleEnum.SMALL_ICON_TEXT, "nav" + adminTool.getId(), adminTool.getHandler().getName(), null, false, null, null, null); String parent = toolPath; while (!parent.equals(getBaseToolPath(wp))) { parent = getParent(wp, parent); adminTool = resolveAdminTool(getCurrentRoot(wp).getKey(), parent); String id = "nav" + adminTool.getId(); String link = linkForToolPath(wp.getJsp(), parent, adminTool.getHandler().getParameters(wp)); String onClic = "openPage('" + link + "');"; String buttonHtml = A_CmsHtmlIconButton.defaultButtonHtml( CmsHtmlIconButtonStyleEnum.SMALL_ICON_TEXT, id, adminTool.getHandler().getName(), adminTool.getHandler().getHelpText(), true, null, null, onClic); html = buttonHtml + NAVBAR_SEPARATOR + html; } html = CmsToolMacroResolver.resolveMacros(html, wp); html = CmsEncoder.decode(html); html = CmsToolMacroResolver.resolveMacros(html, wp); html = "<div class='pathbar'>\n" + html + "&nbsp;</div>\n"; return html; } /** * Returns the base tool path for the active user.<p> * * @param wp the workplace object * * @return the base tool path for the active user */ public String getBaseToolPath(CmsWorkplace wp) { CmsToolUserData userData = getUserData(wp); String path = TOOLPATH_SEPARATOR; if (userData != null) { path = userData.getBaseTool(getCurrentRoot(wp).getKey()); } return path; } /** * Returns the current user's root handler.<p> * * @param wp the workplace context * * @return the current user's root handler */ public CmsToolRootHandler getCurrentRoot(CmsWorkplace wp) { CmsToolUserData userData = getUserData(wp); String root = ROOTKEY_DEFAULT; if (userData != null) { if (m_roots.getObject(userData.getRootKey()) != null) { root = userData.getRootKey(); } else { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_NOT_CONFIGURED_ROOT_1, userData.getRootKey())); } } } return (CmsToolRootHandler)m_roots.getObject(root); } /** * Returns the current tool.<p> * * @param wp the workplace object * * @return the current tool */ public CmsTool getCurrentTool(CmsWorkplace wp) { return resolveAdminTool(getCurrentRoot(wp).getKey(), getCurrentToolPath(wp)); } /** * Returns the current tool path.<p> * * @param wp the workplace object * * @return the current tool path */ public String getCurrentToolPath(CmsWorkplace wp) { CmsToolUserData userData = getUserData(wp); String path = getBaseToolPath(wp); if (userData != null) { path = userData.getCurrentToolPath(getCurrentRoot(wp).getKey()); } return path; } /** * Returns the path to the parent of the tool identified by the given tool path.<p> * * The parent of the root is the same root.<p> * * @param wp the workplace object * @param toolPath the abstract tool path * * @return his parent */ public String getParent(CmsWorkplace wp, String toolPath) { if (toolPath.equals(getBaseToolPath(wp))) { return toolPath; } int pos = toolPath.lastIndexOf(TOOLPATH_SEPARATOR); return pos <= 0 ? TOOLPATH_SEPARATOR : toolPath.substring(0, pos); } /** * Returns a list with all registered tools.<p> * * @return list if <code>{@link CmsTool}</code> */ public List getToolHandlers() { return m_tools.elementList(); } /** * Returns a list of tool roots.<p> * * @return a list of {@link CmsToolRootHandler} objects */ public List getToolRoots() { return m_roots.elementList(); } /** * Returns a list of all tools in the given path.<p> * * @param wp the workplace context * @param baseTool the path * @param includeSubtools if the tools in subfolders should be also returned * * @return a list of {@link CmsTool} objects */ public List getToolsForPath(CmsWorkplace wp, String baseTool, boolean includeSubtools) { List toolList = new ArrayList(); String rootKey = getCurrentRoot(wp).getKey(); Iterator itTools = m_tools.elementList().iterator(); while (itTools.hasNext()) { CmsTool tool = (CmsTool)itTools.next(); String path = tool.getHandler().getPath(); if (resolveAdminTool(rootKey, path) != tool) { continue; } if (path.equals(TOOLPATH_SEPARATOR)) { continue; } // leave out everything above the base if (!path.startsWith(baseTool)) { continue; } // filter for path if (baseTool.equals(TOOLPATH_SEPARATOR) || path.startsWith(baseTool + TOOLPATH_SEPARATOR)) { // filter sub tree if (includeSubtools || (path.indexOf(TOOLPATH_SEPARATOR, baseTool.length() + 1) < 0)) { toolList.add(tool); } } } return toolList; } /** * Returns the <code>{@link CmsToolUserData}</code> object for a given user.<p> * * @param wp the workplace object * * @return the current user data */ public CmsToolUserData getUserData(CmsWorkplace wp) { CmsToolUserData userData = wp.getSettings().getToolUserData(); if (userData == null) { userData = new CmsToolUserData(); userData.setRootKey(ROOTKEY_DEFAULT); Iterator it = getToolRoots().iterator(); while (it.hasNext()) { CmsToolRootHandler root = (CmsToolRootHandler)it.next(); userData.setCurrentToolPath(root.getKey(), TOOLPATH_SEPARATOR); userData.setBaseTool(root.getKey(), TOOLPATH_SEPARATOR); } wp.getSettings().setToolUserData(userData); } return userData; } /** * Returns <code>true</code> if there is at least one tool registered using the given url.<p> * * @param url the url of the tool * * @return <code>true</code> if there is at least one tool registered using the given url */ public boolean hasToolPathForUrl(String url) { List toolPaths = (List)m_urls.getObject(url); return ((toolPaths != null) && !toolPaths.isEmpty()); } /** * This method initializes the tool manager for the current user.<p> * * @param wp the jsp page coming from */ public synchronized void initParams(CmsToolDialog wp) { setCurrentRoot(wp, wp.getParamRoot()); setCurrentToolPath(wp, wp.getParamPath()); setBaseToolPath(wp, wp.getParamBase()); // if the current tool path is not under the current root, set the current root as the current tool if (!getCurrentToolPath(wp).startsWith(getBaseToolPath(wp))) { setCurrentToolPath(wp, getBaseToolPath(wp)); } wp.setParamPath(getCurrentToolPath(wp)); wp.setParamBase(getBaseToolPath(wp)); wp.setParamRoot(getCurrentRoot(wp).getKey()); } /** * Redirects to the given page with the given parameters.<p> * * @param wp the workplace object * @param pagePath the path to the page to redirect to * @param params the parameters to send * * @throws IOException in case of errors during forwarding * @throws ServletException in case of errors during forwarding */ public void jspForwardPage(CmsWorkplace wp, String pagePath, Map params) throws IOException, ServletException { Map newParams = createToolParams(wp, pagePath, params); if (pagePath.indexOf("?") > 0) { pagePath = pagePath.substring(0, pagePath.indexOf("?")); } wp.setForwarded(true); // forward to the requested page uri CmsRequestUtil.forwardRequest( wp.getJsp().link(pagePath), CmsRequestUtil.createParameterMap(newParams), wp.getJsp().getRequest(), wp.getJsp().getResponse()); } /** * Redirects to the given tool with the given parameters.<p> * * @param wp the workplace object * @param toolPath the path to the tool to redirect to * @param params the parameters to send * * @throws IOException in case of errors during forwarding * @throws ServletException in case of errors during forwarding */ public void jspForwardTool(CmsWorkplace wp, String toolPath, Map params) throws IOException, ServletException { Map newParams; if (params == null) { newParams = new HashMap(); } else { newParams = new HashMap(params); } // update path param newParams.put(CmsToolDialog.PARAM_PATH, toolPath); jspForwardPage(wp, VIEW_JSPPAGE_LOCATION, newParams); } /** * Returns the admin tool corresponding to the given abstract path.<p> * * @param rootKey the tool root * @param toolPath the path * * @return the corresponding tool, or <code>null</code> if not found */ public CmsTool resolveAdminTool(String rootKey, String toolPath) { return (CmsTool)m_tools.getObject(rootKey + ROOT_SEPARATOR + toolPath); } /** * Sets the base tool path.<p> * * @param wp the workplace object * @param baseToolPath the base tool path to set */ public void setBaseToolPath(CmsWorkplace wp, String baseToolPath) { // use last used base if param empty if (CmsStringUtil.isEmpty(baseToolPath) || baseToolPath.trim().equals("null")) { baseToolPath = getBaseToolPath(wp); } baseToolPath = repairPath(wp, baseToolPath); // set it CmsToolUserData userData = getUserData(wp); userData.setBaseTool(userData.getRootKey(), baseToolPath); } /** * Sets the current user's root key.<p> * * @param wp the workplace context * @param key the current user's root key to set */ public void setCurrentRoot(CmsWorkplace wp, String key) { // use last used root if param empty if (CmsStringUtil.isEmpty(key) || key.trim().equals("null")) { key = getCurrentRoot(wp).getKey(); } // set it CmsToolUserData userData = getUserData(wp); userData.setRootKey(key); } /** * Sets the current tool path.<p> * * @param wp the workplace object * @param currentToolPath the current tool path to set */ public void setCurrentToolPath(CmsWorkplace wp, String currentToolPath) { // use last used path if param empty if (CmsStringUtil.isEmptyOrWhitespaceOnly(currentToolPath) || currentToolPath.trim().equals("null")) { currentToolPath = getCurrentToolPath(wp); } currentToolPath = repairPath(wp, currentToolPath); // use it CmsToolUserData userData = getUserData(wp); userData.setCurrentToolPath(userData.getRootKey(), currentToolPath); } /** * Configures a whole tool root with all its tools.<p> * * @param cms the cms context * @param toolRoot the tool root to configure * * @throws CmsException if something goes wrong */ private void configureToolRoot(CmsObject cms, CmsToolRootHandler toolRoot) throws CmsException { List handlers = new ArrayList(); // add tool root handler handlers.add(toolRoot); // look in every file under the root uri for valid // admin tools and register them List resources = cms.readResourcesWithProperty(toolRoot.getUri(), HANDLERCLASS_PROPERTY); Iterator itRes = resources.iterator(); while (itRes.hasNext()) { CmsResource res = (CmsResource)itRes.next(); CmsProperty prop = cms.readPropertyObject(res.getRootPath(), HANDLERCLASS_PROPERTY, false); if (!prop.isNullProperty()) { try { // instantiate the handler Class handlerClass = Class.forName(prop.getValue()); I_CmsToolHandler handler = (I_CmsToolHandler)handlerClass.newInstance(); if (!handler.setup(cms, toolRoot, res.getRootPath())) { // log failure if (CmsLog.INIT.isWarnEnabled()) { CmsLog.INIT.warn(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_TOOL_SETUP_ERROR_1, res.getRootPath())); } } // keep for later use handlers.add(handler); // log success if (CmsLog.INIT.isDebugEnabled()) { if (!handler.getLink().equals(VIEW_JSPPAGE_LOCATION)) { CmsLog.INIT.debug(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_NEWTOOL_FOUND_2, handler.getPath(), handler.getLink())); } else { CmsLog.INIT.debug(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_NEWTOOL_FOUND_2, handler.getPath(), res.getRootPath())); } } } catch (Exception e) { // log failure if (CmsLog.INIT.isWarnEnabled()) { CmsLog.INIT.warn(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_TOOL_SETUP_ERROR_1, res.getRootPath()), e); } } } } registerHandlerList(cms, toolRoot, 1, handlers); } /** * Creates a parameter map from the given url and additional parameters.<p> * * @param wp the workplace context * @param url the url to create the parameter map for (extracting query params) * @param params additional parameter map * * @return the new parameter map */ private Map createToolParams(CmsWorkplace wp, String url, Map params) { Map newParams = new HashMap(); // add query parameters to the parameter map if required if (url.indexOf("?") > 0) { String query = url.substring(url.indexOf("?")); Map reqParameters = CmsRequestUtil.createParameterMap(query); newParams.putAll(reqParameters); } if (params != null) { newParams.putAll(params); } // put close link if not set if (!newParams.containsKey(CmsDialog.PARAM_CLOSELINK)) { Map argMap = resolveAdminTool(getCurrentRoot(wp).getKey(), getCurrentToolPath(wp)).getHandler().getParameters( wp); newParams.put(CmsDialog.PARAM_CLOSELINK, linkForToolPath(wp.getJsp(), getCurrentToolPath(wp), argMap)); } return newParams; } /** * Registers a new tool at a given install point for the given tool root.<p> * * @param cms the cms context object * @param toolRoot the tool root * @param handler the handler to install */ private void registerAdminTool(CmsObject cms, CmsToolRootHandler toolRoot, I_CmsToolHandler handler) { String link = handler.getLink(); if (link.indexOf("?") > 0) { link = link.substring(0, link.indexOf("?")); } // check visibility if (!cms.existsResource(link)) { return; } //validate path if (!validatePath(toolRoot.getKey(), handler.getPath(), false)) { // log failure if (CmsLog.INIT.isWarnEnabled()) { CmsLog.INIT.warn(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_INCONSISTENT_PATH_2, handler.getPath(), handler.getLink())); } return; } String id = "tool" + m_tools.elementList().size(); CmsTool tool = new CmsTool(id, handler); try { // try to find problems in custom tools handler.isEnabled(cms); handler.isVisible(cms); } catch (Throwable ex) { String message = Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_INSTALL_ERROR_2, handler.getPath(), handler.getLink()); if (CmsLog.INIT.isWarnEnabled()) { CmsLog.INIT.warn(message); } else if (CmsLog.INIT.isDebugEnabled()) { CmsLog.INIT.debug(message, ex); } return; } try { // try to register, can fail if path is already used by another tool m_tools.addIdentifiableObject(toolRoot.getKey() + ROOT_SEPARATOR + handler.getPath(), tool); // just for fast association of links with tools m_urls.addIdentifiableObject(link, handler.getPath()); } catch (Throwable ex) { CmsLog.INIT.warn(Messages.get().getBundle().key( Messages.INIT_TOOLMANAGER_DUPLICATED_ERROR_3, handler.getPath(), handler.getLink(), resolveAdminTool(toolRoot.getKey(), handler.getPath()).getHandler().getLink())); } } /** * Registers all tool handlers recursively for a given tool root.<p> * * @param cms the cms context object * @param toolRoot the tool root * @param len the recursion level * @param handlers the list of handlers to register */ private void registerHandlerList(CmsObject cms, CmsToolRootHandler toolRoot, int len, List handlers) { boolean found = false; Iterator it = handlers.iterator(); while (it.hasNext()) { I_CmsToolHandler handler = (I_CmsToolHandler)it.next(); int myLen = CmsStringUtil.splitAsArray(handler.getPath(), TOOLPATH_SEPARATOR).length; if (((len == myLen) && !handler.getPath().equals(TOOLPATH_SEPARATOR)) || ((len == 1) && handler.getPath().equals(TOOLPATH_SEPARATOR))) { found = true; registerAdminTool(cms, toolRoot, handler); } } if (found) { registerHandlerList(cms, toolRoot, len + 1, handlers); } } /** * Given a string a valid and visible tool path is computed.<p> * * @param wp the workplace object * @param path the path to repair * * @return a valid and visible tool path */ private String repairPath(CmsWorkplace wp, String path) { String rootKey = getCurrentRoot(wp).getKey(); // navigate until to reach a valid path while (!validatePath(rootKey, path, true)) { // log failure LOG.warn(Messages.get().getBundle().key(Messages.LOG_MISSING_ADMIN_TOOL_1, path)); // try parent path = getParent(wp, path); } // navigate until to reach a valid tool while (resolveAdminTool(rootKey, path) == null) { // log failure LOG.warn(Messages.get().getBundle().key(Messages.LOG_MISSING_ADMIN_TOOL_1, path)); // try parent path = getParent(wp, path); } // navegate until to reach an enabled path CmsTool aTool = resolveAdminTool(rootKey, path); while (!aTool.getHandler().isEnabled(wp)) { if (aTool.getHandler().getLink().equals(VIEW_JSPPAGE_LOCATION)) { // just grouping break; } path = getParent(wp, path); aTool = resolveAdminTool(rootKey, path); } return path; } /** * Tests if the full tool path is available.<p> * * @param rootKey the root tool * @param toolPath the path * @param full if <code>true</code> the whole path is checked, if not the last part is not checked (for new tools) * * @return if valid or not */ private boolean validatePath(String rootKey, String toolPath, boolean full) { if (toolPath.equals(TOOLPATH_SEPARATOR)) { return true; } if (!toolPath.startsWith(TOOLPATH_SEPARATOR)) { return false; } List groups = CmsStringUtil.splitAsList(toolPath, TOOLPATH_SEPARATOR); Iterator itGroups = groups.iterator(); String subpath = ""; while (itGroups.hasNext()) { String group = (String)itGroups.next(); if (subpath.length() != TOOLPATH_SEPARATOR.length()) { subpath += TOOLPATH_SEPARATOR + group; } else { subpath += group; } if (itGroups.hasNext() || full) { try { // just check if the tool is available resolveAdminTool(rootKey, subpath).toString(); } catch (Exception e) { return false; } } } return true; } }
package org.openstreetmap.mappinonosm.database; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * * @author nazo */ public class RSS extends XML implements LexicalHandler, ContentHandler { /** for SAX reader */ private Stack <String> stack; private String textBuffer; private boolean inCDATA = false; private String contextEncoded = null; private boolean contextCDATA = false; private String description = null; private boolean descriptionCDATA = false; static private SimpleDateFormat rssDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",Locale.UK); static private String[] startHock = {"title","media:thumbnail","media:content"}; static private String[] endHock = {"link","category"}; /** * This function is called from only XML.getInstance() * @param uri URI indicates the file exing there. */ protected RSS(URI uri) { super(uri); } /** * This function is called from only XML.read() * @param id ID number to be set. */ protected RSS(int id) { super(id); } private URL [] getImages(String context, boolean cdata){ ArrayList<URL> urls=new ArrayList<URL>(); if(!cdata){ context=context.replaceAll("&lt;","<").replaceAll("&gt;", ">"); } int astart=0,start=0,end=0,aend=0; String before; boolean thumb=false; while((start=context.indexOf("<img ",end))>0){ before=context.substring(end, start); if((astart = before.lastIndexOf("<a "))>0 && before.indexOf("</a>",astart+3)<0){ if((aend = before.indexOf("href=", astart + 3)) > 0){ if(before.charAt(aend + 5) == '"'){ astart = aend + 6; aend = before.indexOf('"', astart); String s = before.substring(astart, aend); try { urls.add(new URL(s)); thumb=true; } catch(MalformedURLException ex) { System.out.println("Illigal URL for <a>: " + s); } } } } if((end = context.indexOf("src=", start + 5))>0){ if(context.charAt(end + 4) == '"'){ start = end + 5; end = context.indexOf('"',start); String s=context.substring(start,end); try { urls.add(new URL(s)); } catch(MalformedURLException ex) { System.out.println("Illigal URL for <img>: "+s); } } } } return urls.toArray(new URL[urls.size()]); } void read(){ XMLReader parser; try { parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(this); parser.parse(uri.toASCIIString()); } catch(SAXException ex) { System.out.println("cannot read"); } catch(IOException ex) { System.out.println("IOException"); } } @Override public void startDocument() throws SAXException { if(photoTable == null){ System.err.println("Program's Error: PhotoBase is not set."); System.exit(1); } if(uri == null){ System.err.println("Program's Error: URL of RSS is not set."); System.exit(1); } System.out.println("RSS: "+uri); stack = new Stack<String>(); } @Override public void startElement(String uri, String name, String qualifiedName, Attributes attributes) { if(photo==null){ if (qualifiedName.equals("item")) { photo = new Photo(); photo.setXML(this); System.out.println("<item> start:"); contextCDATA=false; contextEncoded=null; descriptionCDATA=false; description=null; } } else { if (qualifiedName.equals("media:thumbnail") && photo.getThumnale() == null) { photo.setThumbnale(attributes.getValue("url")); } else if(qualifiedName.equals("media:content")){ photo.setOriginal(attributes.getValue("url")); } } textBuffer=""; stack.push(qualifiedName); } @Override public void characters(char[] ch, int start, int length) { textBuffer += new String(ch, start, length); } @Override public void endElement(String uri, String name, String qualifiedName) { String fromStack=stack.pop(); if(photo==null){ if(qualifiedName.equals("title")){ title=entity(textBuffer); System.out.println("RSS title: " + title); } if(qualifiedName.equals("link")){ try { link = new URL(textBuffer); } catch(MalformedURLException ex) { link = null; } } } else { if(qualifiedName.equals("item")){ photo.setReadDate(new Date()); if(photo.getOriginal() ==null){// if media tag doesn't exist. URL[] urls; if(contextEncoded != null){ urls = getImages(contextEncoded, contextCDATA); } else { urls = getImages(description, descriptionCDATA); } /* for(URL urlPhoto: urls){ System.out.println("\timage: " + urlPhoto); }*/ if(urls.length==1){ photo.setOriginal(urls[0]); } else if(urls.length == 2){ photo.setOriginal(urls[0]); photo.setThumbnale(urls[1]); } } if(photoTable.add(photo) == false){ Photo oldPhoto = photoTable.get(photo); if(oldPhoto.getReadDate().before(photo.getPublishedDate())){ photo.setId(oldPhoto.getId()); photoTable.remove(oldPhoto); photoTable.add(photo); photo.setReread(true); photo.getEXIF(); photo.setReread(true); System.out.println("\tThe JPEG is replaced! photo ID: " + photo.getId()); } else { oldPhoto.upDate(photo); System.out.println("\tphoto ID: " + oldPhoto.getId()); } } else {// This means new photo. photo.setNewPhoto(true); photo.getEXIF(); System.out.println("\tnew photo ID: " + photo.getId()); } photo = null; } else if(qualifiedName.equals("pubDate")){ try { Date photoPublishedDate = rssDateFormat.parse(textBuffer); photo.setPublishedDate(photoPublishedDate); if(readDate == null || photoPublishedDate.after(readDate)){ readDate = photoPublishedDate; } System.out.println("\tdate:" + photo.getPublishedDate()); } catch (ParseException ex) { System.out.println("\tfail to parse date! original is :"+textBuffer); photo.setPublishedDate(new Date()); } }else if(qualifiedName.equals("gml:pos")&&stack.search("georss:where")==2){ String[] st = textBuffer.split("\\s"); photo.setLat(Double.parseDouble(st[0])); photo.setLon(Double.parseDouble(st[1])); } else if(qualifiedName.equals("georss:point")){ String[] st = textBuffer.split("\\s"); photo.setLat(Double.parseDouble(st[0])); photo.setLon(Double.parseDouble(st[1])); } else if(qualifiedName.equals("description")){ description=textBuffer; } else if(qualifiedName.equals("content:encoded")){ contextEncoded=textBuffer; } else if(qualifiedName.equals("title")){ photo.setTitle(entity(textBuffer)); System.out.println("\ttitle: " + photo.getTitle()); } else if(qualifiedName.equals("link")){ photo.setLink(textBuffer); System.out.println("\tlink: " + photo.getLink()); } else if(qualifiedName.equals("media:keywords")){ System.out.println("\tmedia:keywords: "+textBuffer); String [] delimited=textBuffer.split(", "); machineTags(delimited); } else if(qualifiedName.equals("media:category")){ System.out.println("\tmedia:category: "+textBuffer); String [] delimited=textBuffer.split(" "); machineTags(delimited); } else if(qualifiedName.equals("category")){ System.out.println("\tcategory: "+textBuffer); machineTags(textBuffer); } } textBuffer=""; } @Override public void endDocument() throws SAXException { System.out.println("RSS Done"); // readDate = new Date(); } @Override public void startCDATA(){ this.inCDATA = true; String s; if((s=stack.peek()).equals("content:encoded")){ contextCDATA=true; } else if(s.equals("description")){ descriptionCDATA=true; } } @Override public void endCDATA(){ this.inCDATA = false; } public void startDTD(String name, String publicId, String systemId) throws SAXException { } public void endDTD() throws SAXException { } public void startEntity(String name) throws SAXException { } public void endEntity(String name) throws SAXException { } public void comment(char[] ch, int start, int length) throws SAXException { } public void setDocumentLocator(Locator locator) { } public void startPrefixMapping(String prefix, String uri) throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void skippedEntity(String name) throws SAXException { } }
package org.sugarj.common.cleardep; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.sugarj.common.FileCommands; import org.sugarj.common.path.Path; import org.sugarj.common.path.RelativePath; /** * Dependency management for modules. * * @author Sebastian Erdweg */ abstract public class CompilationUnit extends PersistableEntity { public CompilationUnit() { /* for deserialization only */ } public CompilationUnit(Stamper stamper) { super(stamper); } private Map<RelativePath, Integer> sourceArtifacts = new HashMap<>(); private Map<CompilationUnit, Integer> moduleDependencies = new HashMap<>(); private Set<CompilationUnit> circularModuleDependencies = new HashSet<>(); private Map<RelativePath, Integer> externalFileDependencies = new HashMap<>(); private Map<Path, Integer> generatedFiles = new HashMap<>(); /** * Transitive closure (over module dependencies) of required and generated files. */ transient private Map<Path, Integer> transitivelyAffectedFiles = new HashMap<>(); // Methods for adding dependencies public void addSourceArtifact(RelativePath file) { addSourceArtifact(file, stamper.stampOf(file)); } public void addSourceArtifact(RelativePath file, int stampOfFile) { sourceArtifacts.put(file, stampOfFile); } public void addExternalFileDependency(RelativePath file) { addExternalFileDependency(file, stamper.stampOf(file)); } public void addExternalFileDependency(RelativePath file, int stampOfFile) { externalFileDependencies.put(file, stampOfFile); transitivelyAffectedFiles.put(file, stampOfFile); } public void addGeneratedFile(Path file) { addGeneratedFile(file, stamper.stampOf(file)); } public void addGeneratedFile(Path file, int stampOfFile) { generatedFiles.put(file, stampOfFile); transitivelyAffectedFiles.put(file, stampOfFile); } public void addCircularModuleDependency(CompilationUnit mod) { circularModuleDependencies.add(mod); } public void addModuleDependency(CompilationUnit mod) throws IOException { moduleDependencies.put(mod, mod.stamp()); transitivelyAffectedFiles.putAll(mod.getTransitivelyAffectedFileStamps()); } // Methods for querying dependencies public boolean dependsOn(CompilationUnit other) { return moduleDependencies.containsKey(other) || circularModuleDependencies.contains(other); } public boolean dependsOnTransitively(CompilationUnit other) { if (dependsOn(other)) return true; for (CompilationUnit mod : moduleDependencies.keySet()) if (mod.dependsOnTransitively(other)) return true; return false; } public Set<RelativePath> getSourceArtifacts() { return sourceArtifacts.keySet(); } public Set<CompilationUnit> getModuleDependencies() { return moduleDependencies.keySet(); } public Set<CompilationUnit> getCircularModuleDependencies() { return circularModuleDependencies; } public Set<RelativePath> getExternalFileDependencies() { return externalFileDependencies.keySet(); } public Set<Path> getGeneratedFiles() { return generatedFiles.keySet(); } public Set<Path> getTransitivelyAffectedFiles() { return getTransitivelyAffectedFileStamps().keySet(); } private Map<Path, Integer> getTransitivelyAffectedFileStamps() { if (transitivelyAffectedFiles == null) { final Map<Path, Integer> deps = new HashMap<>(); ModuleVisitor<Void> collectAffectedFileStampsVisitor = new ModuleVisitor<Void>() { @Override public Void visit(CompilationUnit mod) { deps.putAll(generatedFiles); deps.putAll(externalFileDependencies); return null; } @Override public Void combine(Void v1, Void v2) { return null; } @Override public Void init() { return null; } }; visit(collectAffectedFileStampsVisitor); synchronized(this) { transitivelyAffectedFiles = deps; } } return transitivelyAffectedFiles; } public Set<Path> getCircularFileDependencies() throws IOException { Set<Path> dependencies = new HashSet<Path>(); Set<CompilationUnit> visited = new HashSet<>(); LinkedList<CompilationUnit> queue = new LinkedList<>(); queue.add(this); while (!queue.isEmpty()) { CompilationUnit res = queue.pop(); visited.add(res); for (Path p : res.generatedFiles.keySet()) if (!dependencies.contains(p) && FileCommands.exists(p)) dependencies.add(p); for (Path p : res.externalFileDependencies.keySet()) if (!dependencies.contains(p) && FileCommands.exists(p)) dependencies.add(p); for (CompilationUnit nextDep: res.moduleDependencies.keySet()) if (!visited.contains(nextDep) && !queue.contains(nextDep)) queue.addFirst(nextDep); for (CompilationUnit nextDep : res.circularModuleDependencies) if (!visited.contains(nextDep) && !queue.contains(nextDep)) queue.addFirst(nextDep); } return dependencies; } // Methods for checking compilation consistency protected abstract boolean isConsistentExtend(); protected boolean isConsistentWithSourceArtifacts() { for (Entry<RelativePath, Integer> e : sourceArtifacts.entrySet()) if (!FileCommands.exists(e.getKey()) || e.getValue() != stamper.stampOf(e.getKey())) return false; return true; } public boolean isConsistentShallow() { if (hasPersistentVersionChanged()) return false; if (!isConsistentWithSourceArtifacts()) return false; for (Entry<Path, Integer> e : generatedFiles.entrySet()) if (stamper.stampOf(e.getKey()) != e.getValue()) return false; for (Entry<? extends Path, Integer> e : externalFileDependencies.entrySet()) if (stamper.stampOf(e.getKey()) != e.getValue()) return false; for (Entry<CompilationUnit, Integer> e : moduleDependencies.entrySet()) if (e.getKey().stamp() != e.getValue()) return false; if (!isConsistentExtend()) return false; return true; } private final ModuleVisitor<Boolean> isConsistentVisitor = new ModuleVisitor<Boolean>() { @Override public Boolean visit(CompilationUnit mod) { return mod.isConsistentShallow(); } @Override public Boolean combine(Boolean t1, Boolean t2) { return t1 && t2; } @Override public Boolean init() { return true; } }; public boolean isConsistent() { return visit(isConsistentVisitor); } // Methods for visiting the module graph public static interface ModuleVisitor<T> { public T visit(CompilationUnit mod); public T combine(T t1, T t2); public T init(); } private Map<CompilationUnit, Integer> computeRanks() { LinkedList<CompilationUnit> queue = new LinkedList<>(); Map<CompilationUnit, Integer> ranks = new HashMap<>(); queue.add(this); ranks.put(this, 0); while (!queue.isEmpty()) { CompilationUnit mod = queue.remove(); int rMod = ranks.get(mod); Set<CompilationUnit> deps = new HashSet<>(); deps.addAll(mod.getModuleDependencies()); deps.addAll(mod.getCircularModuleDependencies()); for (CompilationUnit dep : deps) { Integer rDep = ranks.get(dep); if (rDep != null) ranks.put(dep, Math.min(rDep, rMod)); else { rDep = rMod + 1; if (!queue.contains(dep)) queue.addFirst(dep); } } } return ranks; } /** * Visits the module graph starting from this module, satisfying the following properties: * - every module reachable from `this` module is visited exactly once * - if a module M1 is visited before a module M2, * then M1 is not reachable from M2 or M1 and M2 are mutually reachable. */ public <T> T visit(ModuleVisitor<T> visitor) { final Map<CompilationUnit, Integer> ranks = computeRanks(); Comparator<CompilationUnit> comparator = new Comparator<CompilationUnit>() { public int compare(CompilationUnit m1, CompilationUnit m2) { return ranks.get(m1).compareTo(ranks.get(m2)); } }; CompilationUnit[] mods = ranks.keySet().toArray(new CompilationUnit[ranks.size()]); Arrays.sort(mods, comparator); T result = visitor.init(); for (CompilationUnit mod : mods) { T newResult = visitor.visit(mod); result = visitor.combine(result, newResult); } return result; } // Methods for serialization @Override @SuppressWarnings("unchecked") protected void readEntity(ObjectInputStream in) throws IOException, ClassNotFoundException { sourceArtifacts = (Map<RelativePath, Integer>) in.readObject(); moduleDependencies = (Map<CompilationUnit, Integer>) in.readObject(); circularModuleDependencies = (Set<CompilationUnit>) in.readObject(); generatedFiles = (Map<Path, Integer>) in.readObject(); externalFileDependencies = (Map<RelativePath, Integer>) in.readObject(); } @Override protected void writeEntity(ObjectOutputStream out) throws IOException { out.writeObject(sourceArtifacts = Collections.unmodifiableMap(sourceArtifacts)); out.writeObject(moduleDependencies = Collections.unmodifiableMap(moduleDependencies)); out.writeObject(circularModuleDependencies = Collections.unmodifiableSet(circularModuleDependencies)); out.writeObject(generatedFiles = Collections.unmodifiableMap(generatedFiles)); out.writeObject(externalFileDependencies = Collections.unmodifiableMap(externalFileDependencies)); } }
package com.bridge; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import android.net.Uri; import android.webkit.MimeTypeMap; import android.webkit.CookieManager; import android.content.Context; import android.content.Intent; import android.content.ActivityNotFoundException; import android.os.AsyncTask; /** * This class starts an activity for an intent to view files */ public class Open extends CordovaPlugin { public static final String OPEN_ACTION = "open"; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals(OPEN_ACTION)) { String path = args.getString(0); if (path != null && path.length() > 0) { new FileDownloadAsyncTask(path, callbackContext).execute(); return true; } else { return false; } } else { return false; } } /** * Returns the MIME type of the file. * * @param path * @return */ private static String getMimeType(String path) { // infer mime type from uri String mimeType = HttpURLConnection.guessContentTypeFromName(path); // if mime guess fails, do legwork if (mimeType == null) { String extension = MimeTypeMap.getFileExtensionFromUrl(path); if (extension != null) { MimeTypeMap mime = MimeTypeMap.getSingleton(); mimeType = mime.getMimeTypeFromExtension(extension); } } return mimeType; } /** * Creates an intent for the data of mime type * * @param path * @param callbackContext */ private void previewFile(String path, CallbackContext callbackContext) { try { File file = new File(path); Uri uri = Uri.fromFile(file); String mime = getMimeType(path); Intent intent = new Intent(Intent.ACTION_VIEW); Context activity = cordova.getActivity(); intent.setDataAndTypeAndNormalize(uri, mime); activity.startActivity(intent); callbackContext.success(); } catch (ActivityNotFoundException e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } } private File downloadFile(String url, CallbackContext callbackContext) { try { Uri uri = Uri.parse(url); uri = uri.normalizeScheme(); String Filename = uri.getLastPathSegment(); CookieManager cookieManager = CookieManager.getInstance(); String cookie = null; if (cookieManager.getCookie(url) != null) { cookie = cookieManager.getCookie(url).toString(); } URL tempUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) tempUrl.openConnection(); if (cookie != null) { connection.setRequestProperty("Cookie", cookie); } Context context = cordova.getActivity().getApplicationContext(); InputStream inputStream = connection.getInputStream(); String ext = MimeTypeMap.getFileExtensionFromUrl(url); File file = File.createTempFile(Filename, "." + ext, context.getExternalCacheDir()); file.setReadable(true, false); OutputStream outputStream = new FileOutputStream(file); byte[] data = new byte[1024]; int buffer = 0; while ((buffer = inputStream.read(data)) > 0) { outputStream.write(data, 0, buffer); outputStream.flush(); } outputStream.close(); inputStream.close(); return file; } catch(IOException e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } return null; } private class FileDownloadAsyncTask extends AsyncTask<Void, Void, File> { private final CallbackContext callbackContext; private final String url; public FileDownloadAsyncTask(String url, CallbackContext callbackContext) { super(); this.callbackContext = callbackContext; this.url = url; } @Override protected File doInBackground(Void... arg0) { File file = downloadFile(url, callbackContext); return file; } @Override protected void onPostExecute(File result) { String path = result.toString(); previewFile(path, callbackContext); } } }
package pitt.search.semanticvectors; import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Enumeration; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorSearcher; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.VectorUtils; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher{ private VectorStore queryVecStore; private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract float getScore(float[] testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils) { this.queryVecStore = queryVecStore; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); float score, threshold = -1; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Initialize result list if just starting. if (results.size() == 0) { ObjectVector firstElement = vecEnum.nextElement(); score = getScore(firstElement.getVector()); results.add(new SearchResult(score, firstElement)); continue; } // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } return results; } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { float[] queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, queryTerms); if (VectorUtils.isZeroVector(this.queryVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public float getScore(float[] testVector) { //testVector = VectorUtils.getNormalizedVector(testVector); return VectorUtils.scalarProduct(this.queryVector, testVector); } } /** * Class for searching a vector store using sparse cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosineSparse extends VectorSearcher { float[] queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosineSparse(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); float[] fullQueryVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, queryTerms); if (VectorUtils.isZeroVector(fullQueryVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } short[] sparseQueryVector = VectorUtils.floatVectorToSparseVector(fullQueryVector, 20); this.queryVector = VectorUtils.sparseVectorToFloatVector(sparseQueryVector, Flags.dimension); } public float getScore(float[] testVector) { //testVector = VectorUtils.getNormalizedVector(testVector); short[] sparseTestVector = VectorUtils.floatVectorToSparseVector(testVector, 40); testVector = VectorUtils.sparseVectorToFloatVector(sparseTestVector, Flags.dimension); return VectorUtils.scalarProduct(this.queryVector, testVector); } } /** * Class for searching a vector store using tensor product * similarity. The class takes a seed tensor as a training * example. This tensor should be entangled (a superposition of * several individual products A * B) for non-trivial results. */ static public class VectorSearcherTensorSim extends VectorSearcher { private float[][] trainingTensor; private float[] partnerVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. This should be a list of one or more * tilde-separated training pairs, e.g., <code>paris~france * berlin~germany</code> followed by a list of one or more search * terms, e.g., <code>london birmingham</code>. */ public VectorSearcherTensorSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.trainingTensor = VectorUtils.createZeroTensor(Flags.dimension); // Collect tensor training relations. int i = 0; while (queryTerms[i].indexOf("~") > 0) { System.err.println("Training pair: " + queryTerms[i]); String[] trainingTerms = queryTerms[i].split("~"); if (trainingTerms.length != 2) { System.err.println("Tensor training terms must be pairs split by individual" + " '~' character. Error with: '" + queryTerms[i] + "'"); } float[] trainingVec1 = queryVecStore.getVector(trainingTerms[0]); float[] trainingVec2 = queryVecStore.getVector(trainingTerms[1]); if (trainingVec1 != null && trainingVec2 != null) { float[][] trainingPair = VectorUtils.getOuterProduct(trainingVec1, trainingVec2); this.trainingTensor = VectorUtils.getTensorSum(trainingTensor, trainingPair); } ++i; } // Check to see that we got a non-zero training tensor before moving on. if (VectorUtils.isZeroTensor(trainingTensor)) { throw new ZeroVectorException("Tensor training relation is zero ... no results."); } this.trainingTensor = VectorUtils.getNormalizedTensor(trainingTensor); // This is an explicit way of taking a slice of the last i // terms. There may be a quicker way of doing this. String[] partnerTerms = new String[queryTerms.length - i]; for (int j = 0; j < queryTerms.length - i; ++j) { partnerTerms[j] = queryTerms[i + j]; } this.partnerVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, partnerTerms); if (VectorUtils.isZeroVector(this.partnerVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param testVector Vector being tested. * Scores are hopefully high when the relationship between queryVector * and testVector is analogous to the relationship between rel1 and rel2. */ public float getScore(float[] testVector) { float[][] testTensor = VectorUtils.getOuterProduct(this.partnerVector, testVector); return VectorUtils.getInnerProduct(this.trainingTensor, testTensor); } } /** * Class for searching a vector store using convolution similarity. * Interface is similar to that for VectorSearcherTensorSim. */ static public class VectorSearcherConvolutionSim extends VectorSearcher { private float[] trainingConvolution; private float[] partnerVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. This should be a list of one or more * tilde-separated training pairs, e.g., <code>paris~france * berlin~germany</code> followed by a list of one or more search * terms, e.g., <code>london birmingham</code>. */ public VectorSearcherConvolutionSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.trainingConvolution = new float[2 * Flags.dimension - 1]; for (int i = 0; i < 2 * Flags.dimension - 1; ++i) { this.trainingConvolution[i] = 0; } // Collect tensor training relations. int i = 0; while (queryTerms[i].indexOf("~") > 0) { System.err.println("Training pair: " + queryTerms[i]); String[] trainingTerms = queryTerms[i].split("~"); if (trainingTerms.length != 2) { System.err.println("Tensor training terms must be pairs split by individual" + " '~' character. Error with: '" + queryTerms[i] + "'"); } float[] trainingVec1 = queryVecStore.getVector(trainingTerms[0]); float[] trainingVec2 = queryVecStore.getVector(trainingTerms[1]); if (trainingVec1 != null && trainingVec2 != null) { float[] trainingPair = VectorUtils.getConvolutionFromVectors(trainingVec1, trainingVec2); for (int j = 0; j < 2 * Flags.dimension - 1; ++j) { this.trainingConvolution[j] += trainingPair[j]; } } ++i; } // Check to see that we got a non-zero training tensor before moving on. if (VectorUtils.isZeroVector(trainingConvolution)) { throw new ZeroVectorException("Convolution training relation is zero ... no results."); } this.trainingConvolution = VectorUtils.getNormalizedVector(trainingConvolution); String[] partnerTerms = new String[queryTerms.length - i]; for (int j = 0; j < queryTerms.length - i; ++j) { partnerTerms[j] = queryTerms[i + j]; } this.partnerVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, partnerTerms); if (VectorUtils.isZeroVector(this.partnerVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param testVector Vector being tested. * Scores are hopefully high when the relationship between queryVector * and testVector is analogoues to the relationship between rel1 and rel2. */ public float getScore(float[] testVector) { float[] testConvolution = VectorUtils.getConvolutionFromVectors(this.partnerVector, testVector); testConvolution = VectorUtils.getNormalizedVector(testConvolution); return VectorUtils.scalarProduct(this.trainingConvolution, testConvolution); } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<float[]> disjunctSpace; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctSpace = new ArrayList(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); float[] tmpVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } if (this.disjunctSpace.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } VectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ public float getScore(float[] testVector) { return VectorUtils.getSumScalarProduct(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<float[]> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctVectors = new ArrayList(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); float[] tmpVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ public float getScore(float[] testVector) { float score = -1; float max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = VectorUtils.scalarProduct(this.disjunctVectors.get(i), testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ static public class VectorSearcherPerm extends VectorSearcher { float[] theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); try { theAvg = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore,luceneUtils,queryTerms); } catch (IllegalArgumentException e) { System.err.println("Couldn't create permutation VectorSearcher ..."); throw e; } if (VectorUtils.isZeroVector(theAvg)) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } public float getScore(float[] testVector) { return VectorUtils.scalarProduct(theAvg, testVector); } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" * This is a variant that takes into account differt results obtained when using either * permuted or random index vectors as the cue terms, by taking the mean of the results * obtained with each of these options */ static public class BalancedVectorSearcherPerm extends VectorSearcher { float[] oneDirection; float[] otherDirection; VectorStore searchVecStore, queryVecStore; LuceneUtils luceneUtils; String[] queryTerms; /** * @param queryVecStore Vector store to use for query generation (this is also reversed). * @param searchVecStore The vector store to search (this is also reversed). * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public BalancedVectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVecStore = queryVecStore; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; try { oneDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore,luceneUtils,queryTerms); otherDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(searchVecStore,luceneUtils,queryTerms); } catch (IllegalArgumentException e) { System.err.println("Couldn't create permutation VectorSearcher ..."); throw e; } if (VectorUtils.isZeroVector(oneDirection)) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } /** * This overides the nearest neighbor class implemented in the abstract * VectorSearcher class * @param numResults the number of results / length of the result list. */ public LinkedList getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList(); float score,score1, score2, threshold = -1; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); Enumeration<ObjectVector> vecEnum2 = queryVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Initialize result list if just starting. if (results.size() == 0) { ObjectVector firstElement = vecEnum.nextElement(); score = getScore(firstElement.getVector()); score2= getScore(vecEnum2.nextElement().getVector()); results.add(new SearchResult(Math.max(score,score2), firstElement)); continue; } // Test this element. ObjectVector testElement = vecEnum.nextElement(); ObjectVector testElement2 = vecEnum2.nextElement(); score1 = getScore(testElement.getVector()); score2 = getScore2(VectorUtils.getNormalizedVector(testElement2.getVector())); score = Math.max(score1,score2); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } }} return results; } public float getScore(float[] testVector) { return VectorUtils.scalarProduct(oneDirection, testVector); } public float getScore2(float[] testVector) { return VectorUtils.scalarProduct(otherDirection, VectorUtils.getNormalizedVector(testVector)); } } }
package ch.ice.controller; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.json.JSONArray; import org.json.JSONObject; import ch.ice.controller.file.ExcelParser; import ch.ice.controller.file.ExcelWriter; import ch.ice.controller.web.BingSearchEngine; import ch.ice.controller.web.WebCrawler; import ch.ice.exceptions.IllegalFileExtensionException; import ch.ice.model.Customer; import ch.ice.utils.JSONUtil; /** * @author Oliver * */ public class MainController { private static final Logger logger = LogManager .getLogger(MainController.class.getName()); ExcelParser excelParserInstance; public static File file; private Integer limitSearchResults = 4; public void startMainController() { PropertiesConfiguration config; List<String> metaTagElements = new ArrayList<String>(); LinkedList<Customer> customerList; //For testing if used without GUI if(file==null) { customerList = retrieveCustomerFromFile(new File("posTest.xlsx")); }else{ customerList = retrieveCustomerFromFile(file); // retrieve all customers from file logger.info("Retrieve Customers from File "+file.getAbsolutePath()); } // Core settings boolean isSearchAvail = false; URL defaultUrl = null; /* * Load Configuration File */ try { config = new PropertiesConfiguration("conf/app.properties"); isSearchAvail = config.getBoolean("core.search.isEnabled"); defaultUrl = new URL(config.getString("core.search.defaultUrl")); //this.limitSearchResults = config.getInteger("searchEngine.bing.limitSearchResults", 15); metaTagElements = Arrays.asList(config .getStringArray("crawler.searchForMetaTags")); } catch (ConfigurationException | MalformedURLException e) { logger.error("Faild to load config file"); System.out.println(e.getLocalizedMessage()); e.printStackTrace(); } WebCrawler wc = new WebCrawler(); for (Customer customer : customerList) { // only search via SearchEngine if search is enabled. Disable search // for testing purpose if (isSearchAvail) { // Add url for customer URL retrivedUrl = searchForUrl(customer); customer.getWebsite().setUrl(retrivedUrl); } else { customer.getWebsite().setUrl(defaultUrl); } // add metadata try { wc.connnect(customer.getWebsite().getUrl().toString()); customer.getWebsite().setMetaTags( wc.getMetaTags(metaTagElements)); } catch (IOException e) { e.printStackTrace(); } logger.info(customer.getWebsite().toString()); } /* * Write every enhanced customer object into a new file */ this.startWriter(customerList); logger.info("end"); } public URL searchForUrl(Customer c) { ArrayList<String> params = new ArrayList<String>(); params.add(c.getFullName().toLowerCase()); params.add(c.getCountryName().toLowerCase()); //params.add("loc:"+c.getCountryCode().toLowerCase()); -> delivers 0 results sometimes. we have to TEST this!!!! String query = BingSearchEngine.buildQuery(params); logger.info("start searchEngine for URL with query: " + query); try { // Start Search JSONArray results = BingSearchEngine.Search(query, this.limitSearchResults); // logger.debug(results.toString()); // logic to pick the first record ; here should be the search logic! results = JSONUtil.cleanUp(results); System.out.println(results); JSONObject aResult = results.getJSONObject(0); // return only the URL form first object return new URL((String) aResult.get("Url")); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Each Row returns a customer object. These customers are saved in an * List-Object. * * @param file * @return LinkedList<Customer> */ public LinkedList<Customer> retrieveCustomerFromFile(File file) { this.excelParserInstance = new ExcelParser(); try { return this.excelParserInstance.readFile(file); } catch (IOException | IllegalFileExtensionException | EncryptedDocumentException | InvalidFormatException e) { System.out.println(e.getMessage()); e.printStackTrace(); } return new LinkedList<Customer>(); } public void startWriter(List<Customer> customerList) { // TODO Check if user demands CSV or EXCEL -> if(excel)->getWorkbook, // Else ->write normal // ExcelWriter ew = new // ExcelWriter(this.excelParserInstance.getWorkbook()); logger.info("Start writing customers to File"); ExcelWriter ew = new ExcelWriter(); ew.writeFile(customerList, this.excelParserInstance.getWorkbook()); } }
package pl.pwr.hiervis.ui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import java.util.Map.Entry; import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JViewport; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.JTextComponent; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import basic_hierarchy.interfaces.Hierarchy; import basic_hierarchy.interfaces.Node; import internal_measures.statistics.AvgWithStdev; import pl.pwr.hiervis.core.HVConfig; import pl.pwr.hiervis.core.HVContext; import pl.pwr.hiervis.hierarchy.LoadedHierarchy; import pl.pwr.hiervis.measures.MeasureManager; import pl.pwr.hiervis.measures.MeasureTask; import pl.pwr.hiervis.util.HierarchyUtils; /* * TODO: * This class uses a somewhat hacky solution to make the frame always-on-top ONLY * within the application. Normally we could use a JDialog for this, however we * also want the user to be able to disable this functionality at will. * * Another possible solution to this problem would be having shared GUI-creation code, * and then calling it inside of a JFrame or a JDialog, depending on the user-selected setting. * Changing the setting while the frame was open would close the old frame and create the new one. */ @SuppressWarnings("serial") public class HierarchyStatisticsFrame extends JFrame { private static final Logger log = LogManager.getLogger( HierarchyStatisticsFrame.class ); private HVContext context; private Window owner; private JTabbedPane tabPane; private JMenuItem mntmDump; private WindowListener ownerListener; private int verticalScrollValue = 0; private DecimalFormat format; public HierarchyStatisticsFrame( HVContext context, Window frame, String subtitle ) { super( "Statistics Frame" + ( subtitle == null ? "" : ( " [ " + subtitle + " ]" ) ) ); this.context = context; this.owner = frame; setDefaultCloseOperation( HIDE_ON_CLOSE ); setMinimumSize( new Dimension( 400, 200 ) ); setSize( 400, 350 ); format = (DecimalFormat)NumberFormat.getInstance( Locale.ENGLISH ); format.setMinimumFractionDigits( 0 ); format.setMaximumFractionDigits( context.getConfig().getDoubleFormatPrecision() ); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); symbols.setGroupingSeparator( ' ' ); format.setDecimalFormatSymbols( symbols ); ownerListener = new WindowAdapter() { @Override public void windowActivated( WindowEvent e ) { HierarchyStatisticsFrame.this.setAlwaysOnTop( true ); } @Override public void windowDeactivated( WindowEvent e ) { if ( e.getOppositeWindow() == null ) { // Disable 'always on top' ONLY when the opposite window // (the one that stole focus from us) is not part of our // own application. HierarchyStatisticsFrame.this.setAlwaysOnTop( false ); } } }; addWindowListener( new WindowAdapter() { @Override public void windowDeactivated( WindowEvent e ) { if ( e.getOppositeWindow() == null ) { // Disable 'always on top' ONLY when the opposite window // (the one that stole focus from us) is not part of our // own application. HierarchyStatisticsFrame.this.setAlwaysOnTop( false ); } } } ); createMenu(); createGUI(); VisualizerFrame.createFileDrop( this, log, "csv", file -> context.loadFile( this, file ) ); if ( context.isHierarchyDataLoaded() ) { LoadedHierarchy lh = context.getHierarchy(); createMeasurePanels( lh.getMainHierarchy() ); if ( tabPane.getSelectedIndex() == 1 ) { initializeNodePanel(); } } MeasureManager measureManager = context.getMeasureManager(); measureManager.measureComputing.addListener( this::onMeasureComputing ); measureManager.measureComputed.addListener( this::onMeasureComputed ); measureManager.taskFailed.addListener( this::onTaskFailed ); context.hierarchyChanging.addListener( this::onHierarchyChanging ); context.hierarchyChanged.addListener( this::onHierarchyChanged ); context.nodeSelectionChanging.addListener( this::nodeSelectionChanging ); context.nodeSelectionChanged.addListener( this::nodeSelectionChanged ); context.configChanged.addListener( this::onConfigChanged ); if ( context.isHierarchyDataLoaded() ) { context.getHierarchy().measureHolder.forComputedMeasures( set -> { set.stream().forEach( this::updateMeasurePanel ); } ); } } public void setKeepOnTop( boolean onTop ) { setAlwaysOnTop( onTop ); if ( onTop ) { owner.addWindowListener( ownerListener ); } else { owner.removeWindowListener( ownerListener ); } } private void createMenu() { JMenuBar menuBar = new JMenuBar(); setJMenuBar( menuBar ); JMenu mnOptions = new JMenu( "Options" ); menuBar.add( mnOptions ); mntmDump = new JMenuItem( "Dump Measures" ); mntmDump.setEnabled( context.isHierarchyDataLoaded() ); mnOptions.add( mntmDump ); mntmDump.addActionListener( ( e ) -> { JFileChooser fileDialog = new JFileChooser(); fileDialog.setCurrentDirectory( new File( "." ) ); fileDialog.setDialogTitle( "Choose a file" ); fileDialog.setFileSelectionMode( JFileChooser.FILES_ONLY ); fileDialog.setAcceptAllFileFilterUsed( false ); fileDialog.setFileFilter( new FileNameExtensionFilter( "*.csv", "csv" ) ); fileDialog.setSelectedFile( new File( "dump.csv" ) ); if ( fileDialog.showSaveDialog( this ) == JFileChooser.APPROVE_OPTION ) { context.getMeasureManager().dumpMeasures( Paths.get( fileDialog.getSelectedFile().getAbsolutePath() ), context.getHierarchy() ); } } ); JCheckBoxMenuItem mntmAlwaysOnTop = new JCheckBoxMenuItem( "Always On Top" ); mnOptions.add( mntmAlwaysOnTop ); mntmAlwaysOnTop.addActionListener( ( e ) -> { setKeepOnTop( mntmAlwaysOnTop.isSelected() ); } ); } private void createGUI() { tabPane = new JTabbedPane(); tabPane.addTab( "Hierarchy Statistics", createScrollableMeasurePanel() ); tabPane.addTab( "Node Statistics", createScrollableMeasurePanel() ); tabPane.addChangeListener( e -> { if ( !context.isHierarchyDataLoaded() ) return; int index = tabPane.getSelectedIndex(); if ( index == 1 && !isNodePanelInitialized() ) { initializeNodePanel(); } if ( index >= 0 ) { int otherIndex = 1 - index; JScrollPane otherPane = (JScrollPane)tabPane.getComponentAt( otherIndex ); int scrollValue = otherPane.getVerticalScrollBar().getValue(); SwingUtilities.invokeLater( () -> { JScrollPane currentsPane = (JScrollPane)tabPane.getComponentAt( index ); currentsPane.getVerticalScrollBar().setValue( scrollValue ); } ); } } ); getContentPane().add( tabPane, BorderLayout.CENTER ); } private JScrollPane createScrollableMeasurePanel() { JScrollPane scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); scrollPane.getVerticalScrollBar().setUnitIncrement( 8 ); scrollPane.setBorder( BorderFactory.createEmptyBorder() ); scrollPane.setAutoscrolls( false ); scrollPane.setViewportView( createRootMeasurePanel() ); return scrollPane; } private JPanel createRootMeasurePanel() { JPanel p = new JPanel(); GridBagLayout layout = new GridBagLayout(); layout.columnWidths = new int[] { 0 }; layout.rowHeights = new int[] { 0 }; layout.columnWeights = new double[] { 1.0 }; layout.rowWeights = new double[] { Double.MIN_VALUE }; p.setLayout( layout ); return p; } private void createMeasurePanels( Hierarchy h ) { MeasureManager measureManager = context.getMeasureManager(); Collection<MeasureTask> validMeasureTasks = measureManager.getMeasureTasks( task -> task.applicabilityFunction.apply( h ) ); addMeasurePanels( h, createBulkTaskPanel( "Calculate All", h, validMeasureTasks ) ); for ( String groupPath : measureManager.listMeasureTaskGroups() ) { Collection<MeasureTask> measureTasks = measureManager.getMeasureTaskGroup( groupPath ).stream() .sorted() .filter( task -> task.applicabilityFunction.apply( h ) ) .collect( Collectors.toList() ); if ( !measureTasks.isEmpty() ) { String friendlyGroupName = groupPath.contains( "/" ) ? groupPath.substring( groupPath.lastIndexOf( "/" ) + 1 ) : groupPath; friendlyGroupName = toCamelCase( friendlyGroupName.replaceAll( "_([a-z])", " $1" ), " " ); addMeasurePanels( h, createFillerPanel( 10 ), createSeparatorPanel( friendlyGroupName ) ); if ( measureTasks.size() > 1 ) { addMeasurePanels( h, createBulkTaskPanel( "Calculate All " + friendlyGroupName, h, measureTasks ) ); } for ( MeasureTask task : measureTasks ) { addMeasurePanels( h, createMeasurePanel( h, task ) ); } } } } private void addMeasurePanels( Hierarchy h, JPanel... panels ) { JPanel mainPanel = getPanel( h ); int curItems = mainPanel.getComponentCount(); int newItems = curItems + panels.length; GridBagLayout layout = (GridBagLayout)mainPanel.getLayout(); layout.rowHeights = new int[newItems + 1]; layout.rowWeights = new double[newItems + 1]; layout.rowWeights[newItems] = Double.MIN_VALUE; mainPanel.setLayout( layout ); int i = curItems; for ( JPanel panel : panels ) { GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0; constraints.gridy = i; constraints.insets = new Insets( 5, 5, 0, 5 ); mainPanel.add( panel, constraints ); ++i; } mainPanel.revalidate(); mainPanel.repaint(); } private JPanel createFillerPanel( int height ) { JPanel cFiller = new JPanel(); cFiller.add( Box.createVerticalStrut( height ) ); return cFiller; } private JPanel createSeparatorPanel( String title ) { JPanel cSeparator = new JPanel(); GridBagLayout layout = new GridBagLayout(); layout.columnWidths = new int[] { 0, 0, 0, 0 }; layout.rowHeights = new int[] { 0, 0 }; layout.columnWeights = new double[] { 1.0, 0.0, 1.0, Double.MIN_VALUE }; layout.rowWeights = new double[] { 0.0, Double.MIN_VALUE }; cSeparator.setLayout( layout ); JSeparator sepLeft = new JSeparator(); GridBagConstraints constraintsSepLeft = new GridBagConstraints(); constraintsSepLeft.insets = new Insets( 0, 5, 5, 5 ); constraintsSepLeft.fill = GridBagConstraints.HORIZONTAL; constraintsSepLeft.gridx = 0; constraintsSepLeft.gridy = 0; cSeparator.add( sepLeft, constraintsSepLeft ); JLabel lblTitle = new JLabel( title ); GridBagConstraints constraintsLabel = new GridBagConstraints(); constraintsLabel.insets = new Insets( 0, 0, 5, 0 ); constraintsLabel.fill = GridBagConstraints.VERTICAL; constraintsLabel.gridx = 1; constraintsLabel.gridy = 0; cSeparator.add( lblTitle, constraintsLabel ); JSeparator sepRight = new JSeparator(); GridBagConstraints constraintsSepRight = new GridBagConstraints(); constraintsSepRight.insets = new Insets( 0, 5, 5, 5 ); constraintsSepRight.fill = GridBagConstraints.HORIZONTAL; constraintsSepRight.gridx = 2; constraintsSepRight.gridy = 0; cSeparator.add( sepRight, constraintsSepRight ); return cSeparator; } private JPanel createMeasurePanel( Hierarchy h, MeasureTask task ) { JPanel cMeasure = new JPanel(); cMeasure.setBorder( new TitledBorder( null, task.identifier, TitledBorder.LEADING, TitledBorder.TOP, null, null ) ); cMeasure.setLayout( new BorderLayout( 0, 0 ) ); if ( context.getHierarchy().measureHolder.isMeasureComputed( h, task ) ) { cMeasure.add( createMeasureContent( task, context.getHierarchy().measureHolder.getMeasureResult( h, task ) ), BorderLayout.NORTH ); } else { cMeasure.add( createTaskButton( Pair.of( h, task ) ), BorderLayout.NORTH ); } return cMeasure; } private JPanel createBulkTaskPanel( String title, Hierarchy h, Collection<MeasureTask> tasks ) { JPanel cMeasure = new JPanel(); cMeasure.setLayout( new BorderLayout( 0, 0 ) ); cMeasure.add( createTaskButton( title, h, tasks ), BorderLayout.NORTH ); return cMeasure; } private JButton createTaskButton( String title, Hierarchy h, Collection<MeasureTask> tasks ) { JButton button = new JButton(); button.addActionListener( ( e ) -> { button.setEnabled( false ); MeasureManager measureManager = context.getMeasureManager(); LoadedHierarchy lh = context.getHierarchy(); for ( MeasureTask task : tasks ) { if ( !lh.measureHolder.isMeasureComputed( h, task ) && !measureManager.isMeasurePending( h, task ) ) { measureManager.postTask( lh.measureHolder, h, task ); } } } ); LoadedHierarchy lh = context.getHierarchy(); boolean allComplete = !tasks.stream() .filter( task -> !lh.measureHolder.isMeasureComputed( h, task ) ) .findAny().isPresent(); button.setEnabled( context.isHierarchyDataLoaded() && !allComplete ); button.setText( title ); return button; } private JButton createTaskButton( Pair<Hierarchy, MeasureTask> task ) { JButton button = new JButton(); button.addActionListener( ( e ) -> { MeasureManager measureManager = context.getMeasureManager(); boolean pending = measureManager.isMeasurePending( task.getLeft(), task.getRight() ); updateTaskButton( button, !pending ); if ( pending ) { measureManager.removeTask( task ); } else { measureManager.postTask( context.getHierarchy().measureHolder, task.getLeft(), task.getRight() ); } } ); updateTaskButton( button, false ); return button; } private void updateTaskButton( JButton button, boolean pending ) { button.setEnabled( context.isHierarchyDataLoaded() ); button.setText( pending ? "Abort" : "Calculate" ); } /** * Creates a GUI component used to represent the specified measure computation result. * * @param result * the measure computation result to create the component for * @return the GUI component */ private JComponent createMeasureContent( MeasureTask measure, Object result ) { if ( result == null ) { throw new IllegalArgumentException( "Result must not be null!" ); } StringBuilder buf = new StringBuilder(); if ( result instanceof double[] ) { // Histogram data // TODO double[] data = (double[])result; for ( int i = 0; i < data.length; ++i ) { buf.append( Integer.toString( i ) ) .append( ":\t" ) .append( formatDoubleValue( data[i] ) ); if ( i + 1 < data.length ) buf.append( "\n" ); } return createFixedTextComponent( buf.toString() ); } else if ( result instanceof AvgWithStdev ) { AvgWithStdev avg = (AvgWithStdev)result; buf.append( formatDoubleValue( avg.getAvg() ) ) .append( " ± " ) .append( formatDoubleValue( avg.getStdev() ) ); if ( measure.isQualityMeasure() ) { buf.insert( 0, "Value: " ).append( '\n' ) .append( "Desired:\t" ).append( formatDesiredValue( measure.getDesiredValue() ) ).append( '\n' ) .append( "Undesired:\t" ).append( formatDesiredValue( measure.getNotDesiredValue() ) ); } return createFixedTextComponent( buf.toString() ); } else if ( result instanceof Double ) { Double v = (Double)result; buf.append( formatDoubleValue( v ) ); if ( measure.isQualityMeasure() ) { buf.insert( 0, "Value:\t" ).append( '\n' ) .append( "Desired:\t" ).append( formatDesiredValue( measure.getDesiredValue() ) ).append( '\n' ) .append( "Undesired:\t" ).append( formatDesiredValue( measure.getNotDesiredValue() ) ); } return createFixedTextComponent( buf.toString() ); } else if ( result instanceof String ) { return createFixedTextComponent( (String)result ); } else { throw new IllegalArgumentException( String.format( "No case defined for data type '%s'", result.getClass().getSimpleName() ) ); } } private String formatDesiredValue( double value ) { if ( value == Double.MAX_VALUE ) return Double.toString( Double.POSITIVE_INFINITY ); if ( value == Double.MIN_VALUE ) return Double.toString( Double.NEGATIVE_INFINITY ); if ( value == 0 ) return "0"; return formatDoubleValue( value ); } private String formatDoubleValue( double value ) { return format.format( value ); } private JTextComponent createFixedTextComponent( String msg ) { JTextArea result = new JTextArea( msg ); result.setEditable( false ); result.setBorder( UIManager.getBorder( "TextField.border" ) ); return result; } private boolean isNodePanelInitialized() { return getPanel( 1 ).getComponentCount() > 0; } private void initializeNodePanel() { LoadedHierarchy lh = context.getHierarchy(); Node n = HierarchyUtils.findGroup( lh, lh.getSelectedRow() ); Hierarchy nh = lh.getNodeHierarchy( n ); createMeasurePanels( nh ); context.getMeasureManager().postAutoComputeTasksFor( lh.measureHolder, nh ); } private JPanel getPanel( Hierarchy h ) { if ( !context.getHierarchy().isOwnerOf( h ) ) { throw new IllegalArgumentException( "Hierarchy does not belong to the currently active LoadedHierarchy object." ); } int tabIndex = context.getHierarchy().getMainHierarchy() == h ? 0 : 1; return getPanel( tabIndex ); } private JPanel getPanel( int tabIndex ) { JScrollPane hierarchyPane = (JScrollPane)tabPane.getComponentAt( tabIndex ); return (JPanel)hierarchyPane.getViewport().getView(); } private JPanel findMeasurePanel( Hierarchy h, String title ) { if ( !context.getHierarchy().isOwnerOf( h ) ) { throw new IllegalArgumentException( "Hierarchy does not belong to the currently active LoadedHierarchy object." ); } int tabIndex = context.getHierarchy().getMainHierarchy() == h ? 0 : 1; return findMeasurePanel( tabIndex, title ); } private JPanel findMeasurePanel( int tabIndex, String title ) { return findMeasurePanel( getPanel( tabIndex ), title ); } private JPanel findMeasurePanel( JPanel panel, String title ) { for ( Component c : panel.getComponents() ) { if ( c instanceof JPanel ) { JPanel p = (JPanel)c; Border b = p.getBorder(); if ( b instanceof TitledBorder ) { TitledBorder tb = (TitledBorder)b; if ( tb.getTitle().equals( title ) ) { return p; } } } } return null; } private void updateMeasurePanel( Hierarchy h, MeasureTask measure, Object measureResult ) { // Inserting components into a JScrollPane tends to trigger its // autoscrolling functionality, even when it has been explicitly disabled. // Bandaid fix is to re-set the scrollbar ourselves when we're done. JScrollPane scrollPane = getScrollPane( getPanel( h ) ); JScrollBar vertical = scrollPane.getVerticalScrollBar(); int scrollValue = vertical.getValue(); JPanel panel = findMeasurePanel( h, measure.identifier ); panel.removeAll(); panel.add( createMeasureContent( measure, measureResult ), BorderLayout.NORTH ); panel.revalidate(); panel.repaint(); SwingUtilities.invokeLater( () -> vertical.setValue( scrollValue ) ); } private void updateMeasurePanel( Entry<Pair<Hierarchy, MeasureTask>, Object> result ) { updateMeasurePanel( result.getKey().getLeft(), result.getKey().getRight(), result.getValue() ); } private void recreateMeasurePanel( Pair<Hierarchy, MeasureTask> task ) { JPanel panel = findMeasurePanel( task.getLeft(), task.getRight().identifier ); panel.removeAll(); panel.add( createTaskButton( task ), BorderLayout.NORTH ); panel.revalidate(); panel.repaint(); } private static String toCamelCase( String input, String delimiter ) { String[] words = input.split( delimiter ); for ( int i = 0; i < words.length; ++i ) { String word = words[i]; words[i] = Character.toUpperCase( word.charAt( 0 ) ) + word.substring( 1 ).toLowerCase(); } return String.join( " ", words ); } private static JScrollPane getScrollPane( JPanel viewportPanel ) { JViewport v = (JViewport)viewportPanel.getParent(); return (JScrollPane)v.getParent(); } // Listeners private void onMeasureComputing( Pair<Hierarchy, MeasureTask> task ) { if ( !context.getHierarchy().isOwnerOf( task.getLeft() ) ) { return; } SwingUtilities.invokeLater( () -> { LoadedHierarchy lh = context.getHierarchy(); Hierarchy h = task.getLeft(); MeasureTask measure = task.getRight(); // This code is deferred, check hierarchies again. if ( !lh.isOwnerOf( h ) ) return; // This code is deferred and executed on the main thread, so there's no guarantee that // it will actually get to run before the measure is computed. // If the measure was computed before we got here, then there's nothing for us to do. if ( !lh.measureHolder.isMeasureComputed( h, measure ) ) { JPanel panel = findMeasurePanel( h, measure.identifier ); JButton button = (JButton)panel.getComponent( 0 ); button.setEnabled( false ); button.setText( "Calculating..." ); } } ); } private void onMeasureComputed( Triple<Hierarchy, MeasureTask, Object> result ) { if ( context.getHierarchy().isOwnerOf( result.getLeft() ) ) { SwingUtilities.invokeLater( () -> updateMeasurePanel( result.getLeft(), result.getMiddle(), result.getRight() ) ); } } private void onTaskFailed( Pair<Hierarchy, MeasureTask> task ) { if ( context.getHierarchy().isOwnerOf( task.getLeft() ) ) { SwingUtilities.invokeLater( () -> recreateMeasurePanel( task ) ); } } private void onConfigChanged( HVConfig cfg ) { format.setMaximumFractionDigits( cfg.getDoubleFormatPrecision() ); } private void onHierarchyChanging( LoadedHierarchy oldHierarchy ) { // Store the current scroll before the hierarchy is changed, so that we can // restore it when the new hierarchy is loaded. JScrollPane scrollPane = (JScrollPane)tabPane.getComponentAt( tabPane.getSelectedIndex() ); verticalScrollValue = scrollPane.getVerticalScrollBar().getValue(); JPanel p = getPanel( 0 ); p.removeAll(); p = getPanel( 1 ); p.removeAll(); tabPane.revalidate(); tabPane.repaint(); } private void onHierarchyChanged( LoadedHierarchy newHierarchy ) { mntmDump.setEnabled( newHierarchy != null ); createMeasurePanels( newHierarchy.getMainHierarchy() ); initializeNodePanel(); if ( newHierarchy != null ) { SwingUtilities.invokeLater( () -> { JScrollPane scrollPane = (JScrollPane)tabPane.getComponentAt( tabPane.getSelectedIndex() ); scrollPane.getVerticalScrollBar().setValue( verticalScrollValue ); } ); } tabPane.revalidate(); tabPane.repaint(); } private void nodeSelectionChanging( int selectedRow ) { // Store the current scroll before the hierarchy is changed, so that we can // restore it when the new hierarchy is loaded. JScrollPane scrollPane = (JScrollPane)tabPane.getComponentAt( tabPane.getSelectedIndex() ); verticalScrollValue = scrollPane.getVerticalScrollBar().getValue(); JPanel p = getPanel( 1 ); p.removeAll(); tabPane.revalidate(); tabPane.repaint(); } private void nodeSelectionChanged( int selectedRow ) { if ( tabPane.getSelectedIndex() == 0 ) { // Only proceed if the node stats tab is active, to prevent creating // components & wrapper hierarchies every time the user changes selection return; } initializeNodePanel(); SwingUtilities.invokeLater( () -> { JScrollPane scrollPane = (JScrollPane)tabPane.getComponentAt( tabPane.getSelectedIndex() ); scrollPane.getVerticalScrollBar().setValue( verticalScrollValue ); } ); tabPane.revalidate(); tabPane.repaint(); } }
package org.pocketcampus.plugin.map; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.pocketcampus.core.plugin.Core; import org.pocketcampus.core.plugin.IPlugin; import org.pocketcampus.core.plugin.PublicMethod; import org.pocketcampus.provider.mapelements.IMapElementsProvider; import org.pocketcampus.shared.plugin.map.MapElementBean; import org.pocketcampus.shared.plugin.map.MapLayerBean; import org.pocketcampus.shared.plugin.map.Position; public class Map implements IPlugin { @PublicMethod public List<MapLayerBean> layers(HttpServletRequest request) { return getExternalLayers(); } @PublicMethod public List<MapLayerBean> getLayers(HttpServletRequest request) { ArrayList<MapLayerBean> layers = new ArrayList<MapLayerBean>(); layers.addAll(getInternalLayers()); layers.addAll(getExternalLayers()); return getInternalLayers(); } @PublicMethod public List<MapElementBean> getItems(HttpServletRequest request) { if(request == null) { return null; } ArrayList<MapElementBean> items = new ArrayList<MapElementBean>(); String layerId = request.getParameter("layer_id"); int id; try { id = Integer.parseInt(layerId); items.addAll(getInternalItems(id)); } catch (Exception e) { return null; } items.addAll(getExternalItems(id)); return items; } @PublicMethod public List<Position> routing(HttpServletRequest request) { double lat = 46.520101; double lon = 6.565189; try { lat = Double.parseDouble(request.getParameter("latitude")); } catch (Exception e) {} try { lon = Double.parseDouble(request.getParameter("longitude")); } catch (Exception e) {} Position p = new Position(lat, lon, 0); List<Position> path = Search.searchPathBetween(p, 6718, false); return path; } private List<MapLayerBean> getInternalLayers() { List<MapLayerBean> layers = new LinkedList<MapLayerBean>(); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.err.println("Server error: unable to load jdbc Drivers"); e.printStackTrace(); return layers; } Connection dbConnection = null; try { dbConnection = DriverManager.getConnection("jdbc:mysql:///pocketcampus", "root", "fyInjhWO"); Statement statement = dbConnection.createStatement(); ResultSet rs = statement.executeQuery("select * from MAP_LAYERS"); while (rs.next()) { MapLayerBean mlb = new MapLayerBean(); mlb.setId(rs.getInt("id")); mlb.setName(rs.getString("title")); mlb.setCache(rs.getInt("cache")); mlb.setDrawable_url(rs.getString("image_url")); mlb.setDisplayable(rs.getBoolean("displayable")); layers.add(mlb); } statement.close(); dbConnection.close(); } catch (SQLException e) { System.err.println("Error with SQL"); e.printStackTrace(); } return layers; } private List<MapLayerBean> getExternalLayers() { HashSet<IPlugin> providers = Core.getInstance().getProvidersOf(IMapElementsProvider.class); Iterator<IPlugin> iter = providers.iterator(); IMapElementsProvider provider; ArrayList<MapLayerBean> layers = new ArrayList<MapLayerBean>(); while(iter.hasNext()) { provider = (IMapElementsProvider)iter.next(); layers.add(provider.getLayer()); } return layers; } private List<MapElementBean> getExternalItems(int id) { HashSet<IPlugin> providers = Core.getInstance().getProvidersOf(IMapElementsProvider.class); Iterator<IPlugin> iter = providers.iterator(); IMapElementsProvider provider; while(iter.hasNext()) { provider = (IMapElementsProvider)iter.next(); } return new ArrayList<MapElementBean>(); } public List<MapElementBean> getInternalItems(int layerId) { List<MapElementBean> elements = new LinkedList<MapElementBean>(); int id = layerId; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.err.println("Server error: unable to load jdbc Drivers"); e.printStackTrace(); return elements; } Connection dbConnection = null; try { dbConnection = DriverManager.getConnection("jdbc:mysql:///pocketcampus", "root", "fyInjhWO"); PreparedStatement statement = dbConnection.prepareStatement("select * from MAP_POIS where layer_id=?"); statement.setInt(1, id); ResultSet rs = statement.executeQuery(); while (rs.next()) { MapElementBean meb = new MapElementBean(); meb.setTitle(rs.getString("title")); meb.setDescription(rs.getString("description")); meb.setLatitude(rs.getDouble("centerX")); meb.setLongitude(rs.getDouble("centerY")); meb.setAltitude(rs.getDouble("altitude")); elements.add(meb); } statement.close(); dbConnection.close(); } catch (SQLException e) { System.err.println("Error with SQL"); e.printStackTrace(); } return elements; } }
package aQute.bnd.osgi; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.osgi.annotation.versioning.ProviderType; import aQute.bnd.signatures.ClassSignature; import aQute.bnd.signatures.FieldSignature; import aQute.bnd.signatures.MethodSignature; import aQute.libg.generics.Create; public class Descriptors { private final Map<String, TypeRef> typeRefCache = new HashMap<>(); private final Map<String, Descriptor> descriptorCache = new HashMap<>(); private final Map<String, PackageRef> packageRefCache = new HashMap<>(); private final Map<String, ClassSignature> classSignatureCache = new HashMap<>(); private final Map<String, MethodSignature> methodSignatureCache = new HashMap<>(); private final Map<String, FieldSignature> fieldSignatureCache = new HashMap<>(); // MUST BE BEFORE PRIMITIVES, THEY USE THE DEFAULT PACKAGE!! final static PackageRef DEFAULT_PACKAGE = new PackageRef(); final static PackageRef PRIMITIVE_PACKAGE = new PackageRef(); final static TypeRef VOID = new ConcreteRef("V", "void", PRIMITIVE_PACKAGE); final static TypeRef BOOLEAN = new ConcreteRef("Z", "boolean", PRIMITIVE_PACKAGE); final static TypeRef BYTE = new ConcreteRef("B", "byte", PRIMITIVE_PACKAGE); final static TypeRef CHAR = new ConcreteRef("C", "char", PRIMITIVE_PACKAGE); final static TypeRef SHORT = new ConcreteRef("S", "short", PRIMITIVE_PACKAGE); final static TypeRef INTEGER = new ConcreteRef("I", "int", PRIMITIVE_PACKAGE); final static TypeRef LONG = new ConcreteRef("J", "long", PRIMITIVE_PACKAGE); final static TypeRef DOUBLE = new ConcreteRef("D", "double", PRIMITIVE_PACKAGE); final static TypeRef FLOAT = new ConcreteRef("F", "float", PRIMITIVE_PACKAGE); @Deprecated public enum SignatureType { TYPEVAR, METHOD, FIELD; } @Deprecated public class Signature { public Map<String, Signature> typevariables = new HashMap<>(); public Signature type; public List<Signature> parameters; } public Descriptors() { packageRefCache.put("", DEFAULT_PACKAGE); } @ProviderType public interface TypeRef extends Comparable<TypeRef> { String getBinary(); String getShorterName(); String getFQN(); String getPath(); boolean isPrimitive(); TypeRef getComponentTypeRef(); TypeRef getClassRef(); PackageRef getPackageRef(); String getShortName(); boolean isJava(); boolean isObject(); String getSourcePath(); String getDottedOnly(); boolean isArray(); } public static class PackageRef implements Comparable<PackageRef> { final String binaryName; final String fqn; final boolean java; PackageRef(String binaryName) { this.binaryName = fqnToBinary(binaryName); this.fqn = binaryToFQN(binaryName); this.java = this.fqn.startsWith("java."); // !this.fqn.equals("java.sql)" // For some reason I excluded java.sql but the classloader will // delegate anyway. So lost the understanding why I did it?? } PackageRef() { this.binaryName = ""; this.fqn = "."; this.java = false; } public PackageRef getDuplicate() { return new PackageRef(binaryName + Constants.DUPLICATE_MARKER); } public String getFQN() { return fqn; } public String getBinary() { return binaryName; } public String getPath() { return binaryName; } public boolean isJava() { return java; } @Override public String toString() { return fqn; } boolean isDefaultPackage() { return this.fqn.equals("."); } boolean isPrimitivePackage() { return this == PRIMITIVE_PACKAGE; } @Override public int compareTo(PackageRef other) { return fqn.compareTo(other.fqn); } @Override public boolean equals(Object o) { assert o instanceof PackageRef; return o == this; } @Override public int hashCode() { return super.hashCode(); } /** * Decide if the package is a metadata package. */ public boolean isMetaData() { if (isDefaultPackage()) return true; return Arrays.stream(Constants.METAPACKAGES) .anyMatch(meta -> binaryName.startsWith(meta) && ((binaryName.length() == meta.length()) || (binaryName.charAt(meta.length()) == '/'))); } } // We "intern" the private static class ConcreteRef implements TypeRef { final String binaryName; final String fqn; final boolean primitive; final PackageRef packageRef; ConcreteRef(PackageRef packageRef, String binaryName) { this.binaryName = binaryName; this.fqn = binaryToFQN(binaryName); this.primitive = false; this.packageRef = packageRef; } ConcreteRef(String binaryName, String fqn, PackageRef pref) { this.binaryName = binaryName; this.fqn = fqn; this.primitive = true; this.packageRef = pref; } @Override public String getBinary() { return binaryName; } @Override public String getPath() { return binaryName + ".class"; } @Override public String getSourcePath() { return binaryName + ".java"; } @Override public String getFQN() { return fqn; } @Override public String getDottedOnly() { return fqn.replace('$', '.'); } @Override public boolean isPrimitive() { return primitive; } @Override public TypeRef getComponentTypeRef() { return null; } @Override public TypeRef getClassRef() { return this; } @Override public PackageRef getPackageRef() { return packageRef; } @Override public String getShortName() { int n = binaryName.lastIndexOf('/'); return binaryName.substring(n + 1); } @Override public String getShorterName() { String name = getShortName(); int n = name.lastIndexOf('$'); if (n <= 0) return name; return name.substring(n + 1); } @Override public boolean isJava() { return packageRef.isJava(); } /** * Returning {@link #getFQN()} is relied upon by other classes. */ @Override public String toString() { return fqn; } @Override public boolean isObject() { return fqn.equals("java.lang.Object"); } @Override public boolean equals(Object other) { assert other instanceof TypeRef; return this == other; } @Override public int compareTo(TypeRef other) { if (this == other) return 0; return fqn.compareTo(other.getFQN()); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean isArray() { return false; } } private static class ArrayRef implements TypeRef { final TypeRef component; ArrayRef(TypeRef component) { this.component = component; } @Override public String getBinary() { return "[" + component.getBinary(); } @Override public String getFQN() { return component.getFQN() + "[]"; } @Override public String getPath() { return component.getPath(); } @Override public String getSourcePath() { return component.getSourcePath(); } @Override public boolean isPrimitive() { return false; } @Override public TypeRef getComponentTypeRef() { return component; } @Override public TypeRef getClassRef() { return component.getClassRef(); } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return component.equals(((ArrayRef) other).component); } @Override public PackageRef getPackageRef() { return component.getPackageRef(); } @Override public String getShortName() { return component.getShortName() + "[]"; } @Override public boolean isJava() { return component.isJava(); } @Override public String toString() { return component.toString() + "[]"; } @Override public boolean isObject() { return false; } @Override public String getDottedOnly() { return component.getDottedOnly(); } @Override public int compareTo(TypeRef other) { if (this == other) return 0; return getFQN().compareTo(other.getFQN()); } @Override public int hashCode() { return super.hashCode(); } @Override public String getShorterName() { String name = getShortName(); int n = name.lastIndexOf('$'); if (n <= 0) return name; return name.substring(n + 1); } @Override public boolean isArray() { return true; } } public TypeRef getTypeRef(String binaryClassName) { assert !binaryClassName.endsWith(".class"); int length = binaryClassName.length(); if ((length > 1) && (binaryClassName.charAt(0) == 'L') && (binaryClassName.charAt(length - 1) == ';')) { binaryClassName = binaryClassName.substring(1, length - 1); length -= 2; } binaryClassName = binaryClassName.replace('.', '$'); if ((length > 0) && (binaryClassName.charAt(0) == '[')) { // We handle arrays here since computeIfAbsent does not like // recursive calls starting in Java 9 TypeRef ref = typeRefCache.get(binaryClassName); if (ref == null) { ref = new ArrayRef(getTypeRef(binaryClassName.substring(1))); typeRefCache.put(binaryClassName, ref); } return ref; } return typeRefCache.computeIfAbsent(binaryClassName, this::createTypeRef); } private TypeRef createTypeRef(String binaryClassName) { if (binaryClassName.length() == 1) { switch (binaryClassName.charAt(0)) { case 'V' : return VOID; case 'B' : return BYTE; case 'C' : return CHAR; case 'I' : return INTEGER; case 'S' : return SHORT; case 'D' : return DOUBLE; case 'F' : return FLOAT; case 'J' : return LONG; case 'Z' : return BOOLEAN; } // falls through for other 1 letter class names } int n = binaryClassName.lastIndexOf('/'); PackageRef pref = (n < 0) ? DEFAULT_PACKAGE : getPackageRef(binaryClassName.substring(0, n)); return new ConcreteRef(pref, binaryClassName); } public TypeRef getPackageInfo(PackageRef packageRef) { String bin = packageRef.getBinary() + "/package-info"; return getTypeRef(bin); } public PackageRef getPackageRef(String binaryPackName) { binaryPackName = binaryPackName.replace('.', '/'); // Check here if a package is actually a nested class // com.example.Foo.Bar should have package com.example, // not com.example.Foo. return packageRefCache.computeIfAbsent(binaryPackName, PackageRef::new); } public Descriptor getDescriptor(String descriptor) { return descriptorCache.computeIfAbsent(descriptor, Descriptor::new); } public ClassSignature getClassSignature(String signature) { return classSignatureCache.computeIfAbsent(signature.replace('$', '.'), ClassSignature::of); } public MethodSignature getMethodSignature(String signature) { return methodSignatureCache.computeIfAbsent(signature.replace('$', '.'), MethodSignature::of); } public FieldSignature getFieldSignature(String signature) { return fieldSignatureCache.computeIfAbsent(signature.replace('$', '.'), FieldSignature::of); } public class Descriptor { final TypeRef type; final TypeRef[] prototype; final String descriptor; Descriptor(String descriptor) { this.descriptor = descriptor; int index = 0; List<TypeRef> types = Create.list(); if (descriptor.charAt(index) == '(') { index++; while (descriptor.charAt(index) != ')') { index = parse(types, descriptor, index); } index++; // skip ) prototype = types.toArray(new TypeRef[0]); types.clear(); } else prototype = null; index = parse(types, descriptor, index); type = types.get(0); } int parse(List<TypeRef> types, String descriptor, int index) { char c; StringBuilder sb = new StringBuilder(); while ((c = descriptor.charAt(index++)) == '[') { sb.append('['); } switch (c) { case 'L' : while ((c = descriptor.charAt(index++)) != ';') { sb.append(c); } break; case 'V' : case 'B' : case 'C' : case 'I' : case 'S' : case 'D' : case 'F' : case 'J' : case 'Z' : sb.append(c); break; default : throw new IllegalArgumentException( "Invalid type in descriptor: " + c + " from " + descriptor + "[" + index + "]"); } types.add(getTypeRef(sb.toString())); return index; } public TypeRef getType() { return type; } public TypeRef[] getPrototype() { return prototype; } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return Arrays.equals(prototype, ((Descriptor) other).prototype) && type == ((Descriptor) other).type; } @Override public int hashCode() { final int prime = 31; int result = prime + type.hashCode(); result = prime * result + ((prototype == null) ? 0 : Arrays.hashCode(prototype)); return result; } @Override public String toString() { return descriptor; } } /** * Return the short name of a FQN */ public static String getShortName(String fqn) { assert fqn.indexOf('/') < 0; int n = fqn.lastIndexOf('.'); if (n >= 0) { return fqn.substring(n + 1); } return fqn; } public static String binaryToFQN(String binary) { assert !binary.isEmpty(); return binary.replace('/', '.'); } public static String fqnToBinary(String binary) { return binary.replace('.', '/'); } public static String getPackage(String binaryNameOrFqn) { int n = binaryNameOrFqn.lastIndexOf('/'); if (n >= 0) return binaryNameOrFqn.substring(0, n) .replace('/', '.'); n = binaryNameOrFqn.lastIndexOf('.'); if (n >= 0) return binaryNameOrFqn.substring(0, n); return "."; } public static String fqnToPath(String s) { return fqnToBinary(s) + ".class"; } public TypeRef getTypeRefFromFQN(String fqn) { if (fqn.equals("boolean")) return BOOLEAN; if (fqn.equals("byte")) return BOOLEAN; if (fqn.equals("char")) return CHAR; if (fqn.equals("short")) return SHORT; if (fqn.equals("int")) return INTEGER; if (fqn.equals("long")) return LONG; if (fqn.equals("float")) return FLOAT; if (fqn.equals("double")) return DOUBLE; return getTypeRef(fqnToBinary(fqn)); } public TypeRef getTypeRefFromPath(String path) { assert path.endsWith(".class"); return getTypeRef(path.substring(0, path.length() - 6)); } }
package com.chirag.RNMail; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.text.Html; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.Callback; import java.util.List; import java.io.File; import java.util.ArrayList; /** * NativeModule that allows JS to open emails sending apps chooser. */ public class RNMailModule extends ReactContextBaseJavaModule { ReactApplicationContext reactContext; public RNMailModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNMail"; } /** * Converts a ReadableArray to a String array * * @param r the ReadableArray instance to convert * * @return array of strings */ private String[] readableArrayToStringArray(ReadableArray r) { int length = r.size(); String[] strArray = new String[length]; for (int keyIndex = 0; keyIndex < length; keyIndex++) { strArray[keyIndex] = r.getString(keyIndex); } return strArray; } @ReactMethod public void mail(ReadableMap options, Callback callback) { Intent i = new Intent(Intent.ACTION_SENDTO); i.setData(Uri.parse("mailto:")); if (options.hasKey("subject") && !options.isNull("subject")) { i.putExtra(Intent.EXTRA_SUBJECT, options.getString("subject")); } if (options.hasKey("body") && !options.isNull("body")) { String body = options.getString("body"); if (options.hasKey("isHTML") && options.getBoolean("isHTML")) { i.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body)); } else { i.putExtra(Intent.EXTRA_TEXT, body); } } if (options.hasKey("recipients") && !options.isNull("recipients")) { ReadableArray recipients = options.getArray("recipients"); i.putExtra(Intent.EXTRA_EMAIL, readableArrayToStringArray(recipients)); } if (options.hasKey("ccRecipients") && !options.isNull("ccRecipients")) { ReadableArray ccRecipients = options.getArray("ccRecipients"); i.putExtra(Intent.EXTRA_CC, readableArrayToStringArray(ccRecipients)); } if (options.hasKey("bccRecipients") && !options.isNull("bccRecipients")) { ReadableArray bccRecipients = options.getArray("bccRecipients"); i.putExtra(Intent.EXTRA_BCC, readableArrayToStringArray(bccRecipients)); } if (options.hasKey("attachments") && !options.isNull("attachments")) { ReadableArray r = options.getArray("attachments"); int length = r.size(); ArrayList<Uri> uris = new ArrayList<Uri>(); for (int keyIndex = 0; keyIndex < length; keyIndex++) { ReadableMap clip = r.getMap(keyIndex); if (clip.hasKey("path") && !clip.isNull("path")){ String path = clip.getString("path"); File file = new File(path); Uri u = Uri.fromFile(file); uris.add(u); } } i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); } PackageManager manager = reactContext.getPackageManager(); List<ResolveInfo> list = manager.queryIntentActivities(i, 0); if (list == null || list.size() == 0) { callback.invoke("not_available"); return; } if (list.size() == 1) { i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { reactContext.startActivity(i); } catch (Exception ex) { callback.invoke("error"); } } else { Intent chooser = Intent.createChooser(i, "Send Mail"); chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { reactContext.startActivity(chooser); } catch (Exception ex) { callback.invoke("error"); } } } }
package org.neo4j.kernel.ha.zookeeper; import static org.neo4j.kernel.ha.HaSettings.allow_init_cluster; import static org.neo4j.kernel.ha.HaSettings.cluster_name; import static org.neo4j.kernel.ha.HaSettings.lock_read_timeout; import static org.neo4j.kernel.ha.HaSettings.max_concurrent_channels_per_slave; import static org.neo4j.kernel.ha.HaSettings.read_timeout; import static org.neo4j.kernel.ha.HaSettings.server; import static org.neo4j.kernel.ha.HaSettings.server_id; import static org.neo4j.kernel.ha.HaSettings.slave_coordinator_update_mode; import static org.neo4j.kernel.ha.HaSettings.zk_session_timeout; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.management.remote.JMXServiceURL; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; import org.neo4j.backup.OnlineBackupSettings; import org.neo4j.helpers.Exceptions; import org.neo4j.helpers.Pair; import org.neo4j.kernel.GraphDatabaseAPI; import org.neo4j.kernel.HaConfig; import org.neo4j.kernel.InformativeStackTrace; import org.neo4j.kernel.SlaveUpdateMode; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.ha.Broker; import org.neo4j.kernel.ha.ClusterEventReceiver; import org.neo4j.kernel.ha.ConnectionInformation; import org.neo4j.kernel.ha.HaSettings; import org.neo4j.kernel.ha.MasterClientFactory; import org.neo4j.kernel.ha.MasterImpl; import org.neo4j.kernel.ha.MasterServer; import org.neo4j.kernel.ha.Slave; import org.neo4j.kernel.ha.SlaveClient; import org.neo4j.kernel.ha.SlaveDatabaseOperations; import org.neo4j.kernel.ha.SlaveImpl; import org.neo4j.kernel.ha.SlaveServer; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.impl.transaction.xaframework.LogExtractor; import org.neo4j.kernel.impl.transaction.xaframework.NullLogBuffer; import org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog; import org.neo4j.kernel.impl.util.StringLogger; public class ZooClient extends AbstractZooKeeperManager { static final String MASTER_NOTIFY_CHILD = "master-notify"; static final String MASTER_REBOUND_CHILD = "master-rebound"; private final ZooKeeper zooKeeper; private final int machineId; private String sequenceNr; private long committedTx; private int masterForCommittedTx; private final Object keeperStateMonitor = new Object(); private volatile KeeperState keeperState = KeeperState.Disconnected; private volatile boolean shutdown = false; private volatile boolean flushing = false; private String rootPath; private volatile StoreId storeId; private volatile TxIdUpdater updater = new NoUpdateTxIdUpdater(); // Has the format <host-name>:<port> private final String haServer; private final String storeDir; private long sessionId = -1; private Config conf; private final SlaveDatabaseOperations localDatabase; private final ClusterEventReceiver clusterReceiver; private final int backupPort; private final boolean writeLastCommittedTx; private final String clusterName; private final boolean allowCreateCluster; private final WatcherImpl watcher; private final Machine asMachine; private final Map<Integer, Pair<SlaveClient,Machine>> cachedSlaves = new HashMap<Integer, Pair<SlaveClient,Machine>>(); private volatile boolean serversRefreshed = true; public ZooClient( String storeDir, StringLogger stringLogger, Config conf, SlaveDatabaseOperations localDatabase, ClusterEventReceiver clusterReceiver, MasterClientFactory clientFactory ) { super( conf.get( HaSettings.coordinators ), stringLogger, conf.getInteger( zk_session_timeout ), clientFactory ); this.storeDir = storeDir; this.conf = conf; this.localDatabase = localDatabase; this.clusterReceiver = clusterReceiver; machineId = conf.getInteger( server_id ); backupPort = conf.getInteger( OnlineBackupSettings.online_backup_port); haServer = conf.isSet(server) ? conf.get( server ) : defaultServer(); writeLastCommittedTx = conf.getEnum(SlaveUpdateMode.class, slave_coordinator_update_mode).syncWithZooKeeper; clusterName = conf.get( cluster_name ); sequenceNr = "not initialized yet"; allowCreateCluster = conf.getBoolean( allow_init_cluster ); asMachine = new Machine( machineId, 0, 0, 0, haServer, backupPort ); try { /* * Chicken and egg problem of sorts. The WatcherImpl might need zooKeeper instance * before its constructor has returned, hence the "flushUnprocessedEvents" workaround. * Without it the watcher might throw NPE on the initial (maybe SyncConnected) events, * which would effectively prevent a client from feeling connected to its ZK cluster. * See WatcherImpl for more detail on this. */ watcher = new WatcherImpl(); zooKeeper = new ZooKeeper( getServers(), getSessionTimeout(), watcher ); watcher.flushUnprocessedEvents( zooKeeper ); } catch ( IOException e ) { throw new ZooKeeperException( "Unable to create zoo keeper client", e ); } } private String defaultServer() { InetAddress host = null; try { host = InetAddress.getLocalHost(); } catch ( UnknownHostException hostBecomesNull ) { // handled by null check } if ( host == null ) { throw new IllegalStateException( "Could not auto configure host name, please supply " + HaSettings.server.name() ); } return host.getHostAddress() + ":" + HaConfig.CONFIG_DEFAULT_PORT; } public Object instantiateMasterServer( GraphDatabaseAPI graphDb ) { int timeOut = conf.isSet( lock_read_timeout ) ? conf.getInteger( lock_read_timeout ) : conf.getInteger( read_timeout ); return new MasterServer( new MasterImpl( graphDb, timeOut ), Machine.splitIpAndPort( haServer ).other(), graphDb.getMessageLog(), conf.getInteger( max_concurrent_channels_per_slave ), timeOut, new BranchDetectingTxVerifier( graphDb ) ); } @Override protected StoreId getStoreId() { return storeId; } public Object instantiateSlaveServer( GraphDatabaseAPI graphDb, Broker broker, SlaveDatabaseOperations ops ) { return new SlaveServer( new SlaveImpl( graphDb, broker, ops ), Machine.splitIpAndPort( haServer ).other(), graphDb.getMessageLog() ); } @Override protected int getMyMachineId() { return this.machineId; } private int toInt( byte[] data ) { return ByteBuffer.wrap( data ).getInt(); } @Override void waitForSyncConnected( WaitMode mode ) { if ( keeperState == KeeperState.SyncConnected ) { return; } if ( shutdown == true ) { throw new ZooKeeperException( "ZooKeeper client has been shutdwon" ); } WaitStrategy strategy = mode.getStrategy( this ); long startTime = System.currentTimeMillis(); long currentTime = startTime; synchronized ( keeperStateMonitor ) { do { try { keeperStateMonitor.wait( 250 ); } catch ( InterruptedException e ) { Thread.interrupted(); } if ( keeperState == KeeperState.SyncConnected ) { return; } if ( shutdown == true ) { throw new ZooKeeperException( "ZooKeeper client has been shutdwon" ); } currentTime = System.currentTimeMillis(); } while ( strategy.waitMore( ( currentTime - startTime ) ) ); if ( keeperState != KeeperState.SyncConnected ) { throw new ZooKeeperTimedOutException( "Connection to ZooKeeper server timed out, keeper state=" + keeperState ); } } } protected void subscribeToDataChangeWatcher( String child ) { String root = getRoot(); String path = root + "/" + child; try { try { zooKeeper.getData( path, true, null ); } catch ( KeeperException e ) { if ( e.code() == KeeperException.Code.NONODE ) { // Create it if it doesn't exist byte[] data = new byte[4]; ByteBuffer.wrap( data ).putInt( -1 ); try { zooKeeper.create( path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); } catch ( KeeperException ce ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) throw new ZooKeeperException( "Creation error", ce ); } } else throw new ZooKeeperException( "Couldn't get or create " + child, e ); } } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted", e ); } } protected void subscribeToChildrenChangeWatcher( String child ) { String path = getRoot() + "/" + child; try { zooKeeper.getChildren( path, true ); } catch ( KeeperException e ) { throw new ZooKeeperException( "Couldn't subscribe getChildren at " + path, e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted", e ); } } protected void setDataChangeWatcher( String child, int currentMasterId ) { try { String root = getRoot(); String path = root + "/" + child; byte[] data = null; boolean exists = false; try { data = zooKeeper.getData( path, true, null ); exists = true; if ( ByteBuffer.wrap( data ).getInt() == currentMasterId ) { msgLog.logMessage( child + " not set, is already " + currentMasterId ); return; } } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NONODE ) { throw new ZooKeeperException( "Couldn't get master notify node", e ); } } // Didn't exist or has changed try { data = new byte[4]; ByteBuffer.wrap( data ).putInt( currentMasterId ); if ( !exists ) { zooKeeper.create( path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); msgLog.logMessage( child + " created with " + currentMasterId ); } else if ( currentMasterId != -1 ) { zooKeeper.setData( path, data, -1 ); msgLog.logMessage( child + " set to " + currentMasterId ); } // Add a watch for it zooKeeper.getData( path, true, null ); } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) { throw new ZooKeeperException( "Couldn't set master notify node", e ); } } } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted", e ); } } @Override public String getRoot() { makeSureRootPathIsFound(); // Make sure it exists byte[] rootData = null; do { try { rootData = zooKeeper.getData( rootPath, false, null ); return rootPath; } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NONODE ) { throw new ZooKeeperException( "Unable to get root node", e ); } } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Got interrupted", e ); } // try create root try { byte data[] = new byte[0]; zooKeeper.create( rootPath, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) { throw new ZooKeeperException( "Unable to create root", e ); } } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Got interrupted", e ); } } while ( rootData == null ); throw new IllegalStateException( "Root path couldn't be found" ); } private void makeSureRootPathIsFound() { if ( rootPath == null ) { storeId = getClusterStoreId( zooKeeper, clusterName ); if ( storeId != null ) { // There's a cluster in place, let's use that rootPath = asRootPath( storeId ); if ( NeoStoreUtil.storeExists( storeDir ) ) { // We have a local store, use and verify against it NeoStoreUtil store = new NeoStoreUtil( storeDir ); committedTx = store.getLastCommittedTx(); if ( !storeId.equals( store.asStoreId() ) ) throw new ZooKeeperException( "StoreId in database doesn't match that of the ZK cluster" ); } else { // No local store committedTx = 1; } } else { // Cluster doesn't exist if ( !allowCreateCluster ) throw new RuntimeException( "Not allowed to create cluster" ); StoreId storeIdSuggestion = NeoStoreUtil.storeExists( storeDir ) ? new NeoStoreUtil( storeDir ).asStoreId() : new StoreId(); storeId = createCluster( storeIdSuggestion ); makeSureRootPathIsFound(); } masterForCommittedTx = getFirstMasterForTx( committedTx ); } } private void cleanupChildren() { try { String root = getRoot(); List<String> children = zooKeeper.getChildren( root, false ); for ( String child : children ) { Pair<Integer, Integer> parsedChild = parseChild( child ); if ( parsedChild == null ) { continue; } if ( parsedChild.first() == machineId ) { zooKeeper.delete( root + "/" + child, -1 ); } } } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to clean up old child", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted.", e ); } } private byte[] dataRepresentingMe( long txId, int master ) { byte[] array = new byte[12]; ByteBuffer buffer = ByteBuffer.wrap( array ); buffer.putLong( txId ); buffer.putInt( master ); return array; } private String setup() { try { cleanupChildren(); writeHaServerConfig(); String root = getRoot(); String path = root + "/" + machineId + "_"; String created = zooKeeper.create( path, dataRepresentingMe( committedTx, masterForCommittedTx ), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL ); // Add watches to our master notification nodes subscribeToDataChangeWatcher( MASTER_NOTIFY_CHILD ); subscribeToDataChangeWatcher( MASTER_REBOUND_CHILD ); subscribeToChildrenChangeWatcher( HA_SERVERS_CHILD ); return created.substring( created.lastIndexOf( "_" ) + 1 ); } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to setup", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Setup got interrupted", e ); } catch ( Throwable t ) { throw new ZooKeeperException( "Unknown setup error", t ); } } private void writeHaServerConfig() throws InterruptedException, KeeperException { // Make sure the HA server root is created String serverRootPath = rootPath + "/" + HA_SERVERS_CHILD; try { zooKeeper.create( serverRootPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) { throw e; } } // Make sure the compatibility node is present String compatibilityPath = rootPath + "/" + COMPATIBILITY_CHILD; try { zooKeeper.create( compatibilityPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) { throw e; } } // Write the HA server config. String machinePath = serverRootPath + "/" + machineId; String compatibilityMachinePath = compatibilityPath + "/" + machineId; byte[] data = haServerAsData(); boolean compatCreated = false; boolean machineCreated = false; try { zooKeeper.create( compatibilityMachinePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL ); compatCreated = true; zooKeeper.create( machinePath, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL ); machineCreated = true; } catch ( KeeperException e ) { if ( e.code() != KeeperException.Code.NODEEXISTS ) { throw e; } msgLog.logMessage( "HA server info already present, trying again" ); try { if ( compatCreated ) zooKeeper.delete( compatibilityMachinePath, -1 ); if ( machineCreated ) zooKeeper.delete( machinePath, -1 ); } catch ( KeeperException ee ) { if ( ee.code() != KeeperException.Code.NONODE ) { msgLog.logMessage( "Unable to delete " + ee.getPath(), ee ); } } finally { writeHaServerConfig(); } } zooKeeper.setData( machinePath, data, -1 ); msgLog.logMessage( "Wrote HA server " + haServer + " to zoo keeper" ); } private byte[] haServerAsData() { byte[] array = new byte[haServer.length()*2 + 100]; ByteBuffer buffer = ByteBuffer.wrap( array ); buffer.putInt( backupPort ); buffer.put( (byte) haServer.length() ); buffer.asCharBuffer().put( haServer.toCharArray() ).flip(); byte[] actualArray = new byte[buffer.limit()]; System.arraycopy( array, 0, actualArray, 0, actualArray.length ); return actualArray; } public synchronized void setJmxConnectionData( JMXServiceURL jmxUrl, String instanceId ) { String path = rootPath + "/" + HA_SERVERS_CHILD + "/" + machineId + "-jmx"; String url = jmxUrl.toString(); byte[] data = new byte[( url.length() + instanceId.length() ) * 2 + 4]; ByteBuffer buffer = ByteBuffer.wrap( data ); // write URL buffer.putShort( (short) url.length() ); buffer.asCharBuffer().put( url.toCharArray() ); buffer.position( buffer.position() + url.length() * 2 ); // write instanceId buffer.putShort( (short) instanceId.length() ); buffer.asCharBuffer().put( instanceId.toCharArray() ); // truncate array if ( buffer.limit() != data.length ) { byte[] array = new byte[buffer.limit()]; System.arraycopy( data, 0, array, 0, array.length ); data = array; } try { try { zooKeeper.setData( path, data, -1 ); } catch ( KeeperException e ) { if ( e.code() == KeeperException.Code.NONODE ) { zooKeeper.create( path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL ); } else { msgLog.logMessage( "Unable to set jxm connection info", e ); } } } catch ( KeeperException e ) { msgLog.logMessage( "Unable to set jxm connection info", e ); } catch ( InterruptedException e ) { Thread.interrupted(); msgLog.logMessage( "Unable to set jxm connection info", e ); } } public void getJmxConnectionData( ConnectionInformation connection ) { String path = rootPath + "/" + HA_SERVERS_CHILD + "/" + machineId + "-jmx"; byte[] data; try { data = zooKeeper.getData( path, false, null ); } catch ( KeeperException e ) { return; } catch ( InterruptedException e ) { Thread.interrupted(); return; } if ( data == null || data.length == 0 ) return; ByteBuffer buffer = ByteBuffer.wrap( data ); char[] url, instanceId; try { // read URL url = new char[buffer.getShort()]; buffer.asCharBuffer().get( url ); buffer.position( buffer.position() + url.length * 2 ); // read instanceId instanceId = new char[buffer.getShort()]; buffer.asCharBuffer().get( instanceId ); } catch ( BufferUnderflowException e ) { return; } connection.setJMXConnectionData( new String( url ), new String( instanceId ) ); } /* * Start/stop flushing infrastructure follows. When master goes down * all machines will gang up and try to elect master. So we will get * many "start flushing" events but we only need respect one. The same * goes for stop flushing events. For that reason we first do a quick * check if we are already in the state we are trying to reach and * bail out quickly. Otherwise we just grab the lock and * synchronously update. The checking outside the lock is the * reason the flushing boolean flag is volatile. */ private void startFlushing() { if ( checkCompatibilityMode() ) { msgLog.logMessage( "Discovered compatibility node, will remain in compatibility mode until the node is removed" ); updater = new CompatibilitySlaveOnlyTxIdUpdater(); updater.init(); } else if ( !flushing ) { synchronized ( this ) { if ( !flushing ) { flushing = true; updater = new SynchronousTxIdUpdater(); updater.init(); } } } } private void stopFlushing() { if ( checkCompatibilityMode() ) { msgLog.logMessage( "Discovered compatibility node, will remain in compatibility mode until the node is removed" ); updater = new CompatibilitySlaveOnlyTxIdUpdater(); updater.init(); } else if ( flushing ) { synchronized ( this ) { if ( flushing ) { flushing = false; updater = new NoUpdateTxIdUpdater(); updater.init(); } } } } public synchronized void setCommittedTx( long tx ) { this.committedTx = tx; updater.updatedTxId( tx ); } private void writeData( long tx, int masterForThat ) { waitForSyncConnected(); String root = getRoot(); String path = root + "/" + machineId + "_" + sequenceNr; byte[] data = dataRepresentingMe( tx, masterForThat ); try { zooKeeper.setData( path, data, -1 ); } catch ( KeeperException e ) { throw new ZooKeeperException( "Unable to set current tx", e ); } catch ( InterruptedException e ) { Thread.interrupted(); throw new ZooKeeperException( "Interrupted...", e ); } } private int getFirstMasterForTx( long committedTx ) { if ( committedTx == 1 ) return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER; LogExtractor extractor = null; try { extractor = LogExtractor.from( storeDir, committedTx ); long tx = extractor.extractNext( NullLogBuffer.INSTANCE ); if ( tx != committedTx ) { msgLog.logMessage( "Tried to extract master for tx " + committedTx + " at initialization, but got tx " + tx + " back. Will be using " + XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER + " temporarily" ); return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER; } return extractor.getLastStartEntry().getMasterId(); } catch ( IOException e ) { msgLog.logMessage( "Couldn't get master for " + committedTx + " using " + XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER + " temporarily", e ); return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER; } finally { if ( extractor != null ) extractor.close(); } } @Override public void shutdown() { watcher.shutdown(); msgLog.close(); this.shutdown = true; shutdownSlaves(); super.shutdown(); } private void shutdownSlaves() { for ( Pair<SlaveClient,Machine> slave : cachedSlaves.values() ) slave.first().shutdown(); cachedSlaves.clear(); } public boolean isShutdown() { return shutdown; } @Override public ZooKeeper getZooKeeper( boolean sync ) { if ( sync ) zooKeeper.sync( rootPath, null, null ); return zooKeeper; } @Override protected Machine getHaServer( int machineId, boolean wait ) { return machineId == this.machineId ? asMachine : super.getHaServer( machineId, wait ); } private boolean checkCompatibilityMode() { try { refreshHaServers(); int totalCount = getNumberOfServers(); int myVersionCount = zooKeeper.getChildren( getRoot() + "/" + COMPATIBILITY_CHILD, false ).size(); boolean result = myVersionCount <= totalCount - 1; msgLog.logMessage( "Checking compatibility mode, read " + totalCount + " as all machines, " + myVersionCount + " as myVersion machines. Based on that I return " + result ); return result; } catch ( Exception e ) { msgLog.logMessage( "Tried to discover if we are in compatibility mode, got this exception instead", e ); throw new RuntimeException( e ); } } private synchronized StoreId createCluster( StoreId storeIdSuggestion ) { String path = "/" + clusterName; try { try { zooKeeper.create( path, storeIdSuggestion.serialize(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); return storeIdSuggestion; // if successfully written } catch ( KeeperException e ) { if ( e.code() == KeeperException.Code.NODEEXISTS ) { // another instance wrote before me try { // read what that instance wrote return StoreId.deserialize( zooKeeper.getData( path, false, null ) ); } catch ( KeeperException ex ) { throw new ZooKeeperException( "Unable to read cluster store id", ex ); } } else { throw new ZooKeeperException( "Unable to write cluster store id", e ); } } } catch ( InterruptedException e ) { throw new ZooKeeperException( "createCluster interrupted", e ); } } public StoreId getClusterStoreId( WaitMode mode ) { waitForSyncConnected( mode ); makeSureRootPathIsFound(); return storeId; } @Override protected String getSequenceNr() { return sequenceNr; } @Override public String toString() { return getClass().getSimpleName() + "[serverId:" + machineId + ", seq:" + sequenceNr + ", lastCommittedTx:" + committedTx + " w/ master:" + masterForCommittedTx + ", session:" + sessionId + "]"; } private class WatcherImpl implements Watcher { private final Queue<WatchedEvent> unprocessedEvents = new LinkedList<WatchedEvent>(); private final ExecutorService threadPool = Executors.newCachedThreadPool(); private final AtomicInteger count = new AtomicInteger( 0 ); private volatile boolean electionHappening = false; /** * Flush all events we got before initialization of * ZooKeeper/WatcherImpl was completed. * * @param zooKeeper ZooKeeper instance to use when processing. We cannot * rely on the * zooKeeper instance inherited from ZooClient since the * contract says that such fields * are only guaranteed to be published when the constructor * has returned, and at this * point it hasn't. */ protected void flushUnprocessedEvents( ZooKeeper zooKeeper ) { synchronized ( unprocessedEvents ) { WatchedEvent e = null; while ( (e = unprocessedEvents.poll()) != null ) runEventInThread( e, zooKeeper ); } } public void shutdown() { threadPool.shutdown(); try { threadPool.awaitTermination( 10, TimeUnit.SECONDS ); } catch ( InterruptedException e ) { msgLog.logMessage( ZooClient.this + " couldn't flush pending events in time during shutdown", true ); } } public void process( final WatchedEvent event ) { /* * MP: The setup we have here is messed up. Why do I say that? Well, we've got * this watcher which uses the ZooKeeper object that it's set to watch. And * it is passed in to the constructor of the ZooKeeper object. So, if this watcher * gets an event before the ZooKeeper constructor returns we're screwed here. * * Cue unprocessedEvents queue. It will act as a shield for this design blunder * and absorb the events we get before everything is properly initialized, * and emit them right thereafter (see #flushUnprocessedEvents()). */ synchronized ( unprocessedEvents ) { if ( zooKeeper == null || !unprocessedEvents.isEmpty() ) { unprocessedEvents.add( event ); return; } } runEventInThread( event, zooKeeper ); } private synchronized void runEventInThread( final WatchedEvent event, final ZooKeeper zoo ) { if ( shutdown ) { return; } if ( count.get() > 10 ) { msgLog.logMessage( "Thread count is already at " + count.get() + " and added another ZK event handler thread." ); } threadPool.submit( new Runnable() { @Override public void run() { processEvent( event, zoo ); } } ); } private void processEvent( WatchedEvent event, ZooKeeper zooKeeper ) { try { count.incrementAndGet(); String path = event.getPath(); msgLog.logMessage( this + ", " + new Date() + " Got event: " + event + " (path=" + path + ")", true ); if ( path == null && event.getState() == Watcher.Event.KeeperState.Expired ) { keeperState = KeeperState.Expired; clusterReceiver.reconnect( new InformativeStackTrace( "Reconnect due to session expired" ) ); } else if ( path == null && event.getState() == Watcher.Event.KeeperState.SyncConnected ) { long newSessionId = zooKeeper.getSessionId(); if ( newSessionId != sessionId ) { if ( writeLastCommittedTx ) { sequenceNr = setup(); msgLog.logMessage( "Did setup, seq=" + sequenceNr + " new sessionId=" + newSessionId ); if ( sessionId != -1 ) { clusterReceiver.newMaster( new InformativeStackTrace( "Got SyncConnected event from ZK" ) ); } sessionId = newSessionId; } else { msgLog.logMessage( "Didn't do setup due to told not to write" ); keeperState = KeeperState.SyncConnected; subscribeToDataChangeWatcher( MASTER_REBOUND_CHILD ); } keeperState = KeeperState.SyncConnected; if ( checkCompatibilityMode() ) { msgLog.logMessage( "Discovered compatibility node, will remain in compatibility mode until the node is removed" ); updater = new CompatibilitySlaveOnlyTxIdUpdater(); } } else { msgLog.logMessage( "SyncConnected with same session id: " + sessionId ); keeperState = KeeperState.SyncConnected; } } else if ( path == null && event.getState() == Watcher.Event.KeeperState.Disconnected ) { keeperState = KeeperState.Disconnected; } else if ( event.getType() == Watcher.Event.EventType.NodeDeleted ) { msgLog.logMessage( "Got a NodeDeleted event for " + path ); ZooKeeperMachine currentMaster = (ZooKeeperMachine) getCachedMaster().other(); if ( path.contains( currentMaster.getZooKeeperPath() ) ) { msgLog.logMessage("Acting on it, calling newMaster()"); clusterReceiver.newMaster( new InformativeStackTrace( "NodeDeleted event received (a machine left the cluster)" ) ); } } else if ( event.getType() == Watcher.Event.EventType.NodeChildrenChanged ) { if ( path.endsWith( HA_SERVERS_CHILD ) ) { try { refreshHaServers(); serversRefreshed = true; subscribeToChildrenChangeWatcher( HA_SERVERS_CHILD ); } catch ( ZooKeeperException e ) { // Happens for session expiration, why? } } } else if ( event.getType() == Watcher.Event.EventType.NodeDataChanged ) { int updatedData = toInt( getZooKeeper( true ).getData( path, true, null ) ); msgLog.logMessage( "Got event data " + updatedData ); if ( path.contains( MASTER_NOTIFY_CHILD ) ) { // This event is for the masters eyes only so it should only // be the (by zookeeper spoken) master which should make sure // it really is master. if ( updatedData == machineId && !electionHappening ) { try { electionHappening = true; clusterReceiver.newMaster( new InformativeStackTrace( "NodeDataChanged event received (someone though I should be the master)" ) ); serversRefreshed = true; } finally { electionHappening = false; } } } else if ( path.contains( MASTER_REBOUND_CHILD ) ) { // This event is for all the others after the master got the // MASTER_NOTIFY_CHILD which then shouts out to the others to // become slaves if they don't already are. if ( updatedData != machineId && !electionHappening ) { try { electionHappening = true; clusterReceiver.newMaster( new InformativeStackTrace( "NodeDataChanged event received (new master ensures I'm slave)" ) ); serversRefreshed = true; } finally { electionHappening = false; } } } else if ( path.contains( FLUSH_REQUESTED_CHILD ) ) { if ( updatedData == STOP_FLUSHING ) { stopFlushing(); } else { startFlushing(); } } else { msgLog.logMessage( "Unrecognized data change " + path ); } } } catch ( BrokerShutDownException e ) { // It's OK. We're in a state where we cannot accept incoming events. } catch ( Exception e ) { msgLog.logMessage( "Error in ZooClient.process", e, true ); throw Exceptions.launderedException( e ); } finally { msgLog.flush(); count.decrementAndGet(); } } } private abstract class AbstractTxIdUpdater implements TxIdUpdater { @Override public void updatedTxId( long txId ) { // default no op } } private class SynchronousTxIdUpdater extends AbstractTxIdUpdater { public void init() { /* * this is safe because we call getFirstMasterForTx() on the same * txid that we post - and we are supposed to be called from setCommitedTxId() * which is synchronized, which means we can't have committedTx changed while * we are here. */ writeData( committedTx, getFirstMasterForTx( committedTx ) ); msgLog.logMessage( "Starting flushing of txids to zk, while at txid " + committedTx ); } @Override public void updatedTxId( long txId ) { masterForCommittedTx = localDatabase.getMasterForTx( txId ); writeData( txId, masterForCommittedTx ); } } private class NoUpdateTxIdUpdater extends AbstractTxIdUpdater { @Override public void init() { writeData( -2, -2 ); msgLog.logMessage( "Stopping flushing of txids to zk, while at txid " + committedTx ); } } private class CompatibilitySlaveOnlyTxIdUpdater extends AbstractTxIdUpdater { public void init() { writeData( 0, -1 ); msgLog.logMessage( "Set to defaults (0 for txid, -1 for master) since we are running in compatilibility mode, while at txid " + committedTx ); } } @Override protected void invalidateMaster() { super.invalidateMaster(); serversRefreshed = true; } public Slave[] getSlavesFromZooKeeper() { synchronized ( cachedSlaves ) { if ( serversRefreshed || cachedSlaves.isEmpty() ) { // Go through the cached list and refresh where needed Machine master = cachedMaster.other(); if ( master.getMachineId() == this.machineId ) { // I'm the master, update/populate the slave list Set<Integer> visitedSlaves = new HashSet<Integer>(); for ( Machine machine : getHaServers() ) { int id = machine.getMachineId(); visitedSlaves.add( id ); if ( id == machineId ) continue; boolean instantiate = true; Pair<SlaveClient, Machine> existingSlave = cachedSlaves.get( id ); if ( existingSlave != null ) { // We already have a cached slave for this machine, check if // it's the same server information Machine existingMachine = existingSlave.other(); if ( existingMachine.getServer().equals( machine.getServer() ) ) instantiate = false; else // Connection information changed, needs refresh existingSlave.first().shutdown(); } if ( instantiate ) { cachedSlaves.put( id, Pair.of( new SlaveClient( machine.getMachineId(), machine.getServer().first(), machine.getServer().other().intValue(), msgLog, storeId, conf.get( HaSettings.max_concurrent_channels_per_slave ) ), machine ) ); } } Integer[] existingSlaves = cachedSlaves.keySet().toArray( new Integer[cachedSlaves.size()] ); for ( int id : existingSlaves ) if ( !visitedSlaves.contains( id ) ) cachedSlaves.remove( id ).first().shutdown(); } else { // I'm a slave, I don't need a slave list so clear any existing shutdownSlaves(); } serversRefreshed = true; } Slave[] slaves = new Slave[cachedSlaves.size()]; int i = 0; for ( Pair<SlaveClient, Machine> slave : cachedSlaves.values() ) slaves[i++] = slave.first(); return slaves; } } }
package io.github.ihongs.action; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.CoreLocale; import io.github.ihongs.CoreLogger; import io.github.ihongs.CoreSerial; import io.github.ihongs.HongsException; import io.github.ihongs.HongsExemption; import io.github.ihongs.util.daemon.Gate; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * . * * <p> * , ; * , * . * </p> * * <h3>:</h3> * <pre> menus = { "href" : { hrel: , icon: , text: , hint: , menus : { ... }, roles : [ "role.name1", "role.name2", ] } } roles = { "name" : { text: , hint: , depends : [ "fole.name1", "role.name2", ], actions : [ "auth.name1", "auth.name2", ] } } * </pre> * * <h3>:</h3> * <pre> * : 920~929 * 920 * 921 * 922 * </pre> * * <h3>:</h3> * <p> * rsname , * getRoleSet , * rsname . * </p> * @author Hongs */ public class NaviMap extends CoreSerial implements CoreSerial.Mtimes { protected transient String name; protected transient long time; public Map<String, Map> menus; public Map<String, Map> manus; public Map<String, Map> roles; public Set<String> actions = null; public Set<String> imports = null; public String session = null; public NaviMap(String name) throws HongsException { this.name = name ; this.init ( ); } public final void init() throws HongsException { File serFile = new File(Core.DATA_PATH + File.separator + "serial" + File.separator + name + Cnst.NAVI_EXT + ".ser"); time = serFile.lastModified(); / Gate.Leader lock = Gate.getLeader(NaviMap.class.getName() + ":" + name); lock.lockr(); try { if (! expired()) { load(serFile ); if (! expires()) { return; }} } finally { lock.unlockr(); } lock.lockw(); try { imports (); save(serFile ); } finally { lock.unlockw(); } time = serFile.lastModified(); } @Override public long dataModified() { return time; } @Override public long fileModified() { File serFile = new File(Core.DATA_PATH + File.separator + "serial" + File.separator + name + Cnst.NAVI_EXT + ".ser"); File xmlFile = new File(Core.CONF_PATH + File.separator + name + Cnst.NAVI_EXT + ".xml"); return Math.max(serFile.lastModified(), xmlFile.lastModified()); } static protected boolean expired(String namz , long timz) { File serFile = new File(Core.DATA_PATH + File.separator + "serial" + File.separator + namz + Cnst.NAVI_EXT + ".ser"); if (!serFile.exists() || serFile.lastModified() > timz) { return true; } File xmlFile = new File(Core.CONF_PATH + File.separator + namz + Cnst.NAVI_EXT + ".xml"); if ( xmlFile.exists() ) { return xmlFile.lastModified() > timz; } // jar , return null == NaviMap.class.getClassLoader().getResource( namz.contains(".") || namz.contains("/") ? namz + Cnst.NAVI_EXT + ".xml" : Cnst.CONF_PACK +"/"+ namz + Cnst.NAVI_EXT + ".xml" ); } public boolean expired() { return expired (name, time); } public boolean expires() { for (String namz : imports ) { if (expired(namz, time)) { return true; } } return false; } @Override protected void imports() throws HongsException { InputStream is; String fn; try { fn = Core.CONF_PATH +"/"+ name + Cnst.NAVI_EXT + ".xml"; is = new FileInputStream(fn); } catch (FileNotFoundException ex) { fn = name.contains(".") || name.contains("/") ? name + Cnst.NAVI_EXT + ".xml" : Cnst.CONF_PACK +"/"+ name + Cnst.NAVI_EXT + ".xml"; is = this.getClass().getClassLoader().getResourceAsStream(fn); if ( is == null ) { throw new HongsException(920, "Can not find the config file '" + name + Cnst.NAVI_EXT + ".xml'."); } } try { Element root; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder dbn = dbf.newDocumentBuilder(); Document doc = dbn.parse( is ); root = doc.getDocumentElement(); NodeList list = root.getElementsByTagName("rsname"); if (list.getLength() != 0) { session = list.item(0).getTextContent(); } } catch ( IOException ex) { throw new HongsException(921, "Read '" +name+Cnst.NAVI_EXT+".xml error'", ex); } catch (SAXException ex) { throw new HongsException(921, "Parse '"+name+Cnst.NAVI_EXT+".xml error'", ex); } catch (ParserConfigurationException ex) { throw new HongsException(921, "Parse '"+name+Cnst.NAVI_EXT+".xml error'", ex); } this.menus = new LinkedHashMap(); this.manus = new HashMap(); this.roles = new HashMap(); this.actions = new HashSet(); this.imports = new HashSet(); this.parse(root, this.menus, this.manus, this.roles, this.imports, this.actions, new HashSet()); } finally { try { is.close(); } catch (IOException ex) { throw new HongsException(ex); } } } private void parse(Element element, Map menus, Map manus, Map roles, Set imports, Set actions, Set depends) throws HongsException { if (!element.hasChildNodes()) { return; } NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i ++) { Node node = nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } Element element2 = (Element)node; String tagName2 = element2.getTagName(); if (imports == null && !"action".equals(tagName2) && !"depend".equals(tagName2) ) { continue; } if ("menu".equals(tagName2)) { Map menu2 = new HashMap(); String href = element2.getAttribute("href"); if (href == null) href = "" ; menus.put( href , menu2 ); manus.put( href , menu2 ); String hrel = element2.getAttribute("hrel"); if (hrel != null) menu2.put( "hrel", hrel ); String icon = element2.getAttribute("icon"); if (icon != null) menu2.put( "icon", icon ); String text = element2.getAttribute("text"); if (text != null) menu2.put( "text", text ); String hint = element2.getAttribute("hint"); if (hint != null) menu2.put( "hint", hint ); Map menus2 = new LinkedHashMap(); Set roles2 = new LinkedHashSet(); this.parse(element2, menus2, manus, roles, imports, actions, roles2); if (!menus2.isEmpty()) { menu2.put("menus", menus2); } if (!roles2.isEmpty()) { menu2.put("roles", roles2); } } else if ("role".equals(tagName2)) { String namz = element2.getAttribute("name"); if (namz == null) namz = "" ; Map role2 ; if (roles.containsKey(namz)) { role2 = (Map) roles.get(namz); } else { role2 = new HashMap( ); role2.put("text", "" ); role2.put("hint", "" ); roles.put( namz , role2); } if (element2.hasAttribute("text")) { role2.put("text", element2.getAttribute("text")); } if (element2.hasAttribute("hint")) { role2.put("hint", element2.getAttribute("hint")); } Set actions2 = new HashSet(); Set depends2 = new HashSet(); this.parse(element2, null, null, null, null, actions2, depends2); if (!actions2.isEmpty()) { role2.put("actions", actions2); actions.addAll(actions2); } if (!depends2.isEmpty()) { role2.put("depends", depends2); // depends.addAll(depends2); } depends.add( namz ); } else if ("action".equals(tagName2)) { String action = element2.getTextContent(); actions.add(action); } else if ("depend".equals(tagName2)) { String depend = element2.getTextContent(); depends.add(depend); } else if ("import".equals(tagName2)) { String impart = element2.getTextContent().trim(); try { NaviMap conf = new NaviMap(impart); imports.add ( impart ); imports.addAll(conf.imports); actions.addAll(conf.actions); menus.putAll(conf.menus ); manus.putAll(conf.manus ); /** * * * * Dict.putAll name */ for(Map.Entry<String, Map> et : conf.roles.entrySet()) { String namz = et.getKey( ); Map srol = et.getValue(); Map crol = (Map) roles.get(namz); if (crol != null) { Set sact, cact; sact = (Set) srol.get("actions"); cact = (Set) crol.get("actions"); if (sact != null) { if (cact != null) { cact.addAll(sact); } else { crol.put("actions", sact); }} sact = (Set) srol.get("depends"); cact = (Set) crol.get("depends"); if (sact != null) { if (cact != null) { cact.addAll(sact); } else { crol.put("depends", sact); }} } else { roles.put(namz, srol); } } } catch (HongsException ex ) { if (920 == ex.getErrno()) { CoreLogger.error( ex ); } else { throw ex; } } } } } public String getName() { return this.name; } /** * * @param name * @return null */ public Map getRole(String name) { return this.roles.get ( name); } /** * * @param name * @return null */ public Map getMenu(String name) { return this.manus.get ( name); } /** * * @param names * @return */ public Set<String> getMoreRoles(Collection<String> names) { Set <String> rolez = new HashSet(); Set <String> authz = new HashSet(); this.getRoleAuths(names, rolez, authz); return rolez; } public Set<String> getMoreRoles(String... names) { return this.getMoreRoles(Arrays.asList(names)); } /** * * @param names * @return */ public Set<String> getRoleAuths(Collection<String> names) { Set <String> rolez = new HashSet(); Set <String> authz = new HashSet(); this.getRoleAuths(names, rolez, authz); return authz; } public Set<String> getRoleAuths(String... names) { return this.getRoleAuths(Arrays.asList(names)); } protected void getRoleAuths(Collection<String> names, Set roles, Set auths) { for(String n : names) { if (roles.contains(n)) { continue; } Map role = getRole(n); if (role == null) { continue; } roles.add(n); if (role.containsKey("actions")) { Set <String> actionsSet = (Set<String>) role.get("actions"); auths.addAll(actionsSet); } if (role.containsKey("depends")) { Set <String> dependsSet = (Set<String>) role.get("depends"); getRoleAuths(dependsSet , roles, auths); } } } / /** * () * : * @return session null * @throws io.github.ihongs.HongsException */ public Set<String> getRoleSet() throws HongsException { if (session == null || session.length() == 0) { CoreLogger.warn("Can not get roles for menu " + name); return null; } if (session.startsWith(" return getInstance(session.substring(1)).getRoleSet(); } else if (session.startsWith("@")) { return ( Set ) Core.getInstance(session.substring(1)); } else { return ( Set ) Core.getInstance( ActionHelper.class ).getSessibute(session); } } /** * () * : * @return session null * @throws io.github.ihongs.HongsException */ public Set<String> getAuthSet() throws HongsException { Set<String> roleset = getRoleSet(); if (null == roleset) return null ; return getRoleAuths(roleset); } /** * () * : * @param role * @return true * @throws io.github.ihongs.HongsException */ public boolean chkRole(String role) throws HongsException { Set<String> roleset = getRoleSet( ); if (null == roleset) { return !roles.containsKey(role); } return roleset.contains(role) || !roles.containsKey(role); } /** * () * : * @param auth * @return true * @throws io.github.ihongs.HongsException */ public boolean chkAuth(String auth) throws HongsException { Set<String> authset = getAuthSet( ); if (null == authset) { return !actions.contains (auth); } return authset.contains(auth) || !actions.contains (auth); } /** * () * @param name * @return true * @throws io.github.ihongs.HongsException */ public boolean chkMenu(String name) throws HongsException { Map menu = getMenu(name); if (menu == null) { return false; } return chkMenu(menu,getRoleSet()); } private boolean chkMenu(Map menu, Set rolez) { Set r = (Set) menu.get("roles"); Map m = (Map) menu.get("menus"); boolean h = true; if (r != null && ! r.isEmpty( )) { for(Object x : r ) { if (rolez.contains((String) x)) { return true; } } h = false; } if (m != null && ! m.isEmpty( )) { for(Object o : m.entrySet()) { Map.Entry e = (Map.Entry) o; Map n = (Map) e.getValue( ); if (chkMenu(n, rolez)) { return true; } } h = false; } return h; } / /** * () * @return */ public CoreLocale getCurrTranslator() { CoreLocale lang; try { lang = CoreLocale.getInstance(name).clone(); } catch (HongsExemption e) { if (e.getErrno( ) != 826 ) { throw e; } lang = new CoreLocale(null); } for ( String namz : imports ) { lang.fill (namz); } return lang; } /** * * @return */ public List<Map> getMenuTranslates() { return getMenuTranslated(1, null ); } public List<Map> getMenuTranslates(int d) { return getMenuTranslated(d, null ); } /** * * @return * @throws io.github.ihongs.HongsException */ public List<Map> getMenuTranslated() throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getMenuTranslated(1, rolez); } public List<Map> getMenuTranslated(int d) throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getMenuTranslated(d, rolez); } public List<Map> getMenuTranslated(int d, Set<String> rolez) { CoreLocale lang = getCurrTranslator(); return getMenuTranslated(menus, rolez, lang, d, 0); } public List<Map> getMenuTranslates(String name) { return getMenuTranslated(name, 1, null); } public List<Map> getMenuTranslates(String name, int d) { return getMenuTranslated(name, d, null); } public List<Map> getMenuTranslated(String name) throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getMenuTranslated(name, 1, rolez); } public List<Map> getMenuTranslated(String name, int d) throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getMenuTranslated(name, d, rolez); } public List<Map> getMenuTranslated(String name, int d, Set<String> rolez) { CoreLocale lang= getCurrTranslator(); Map menu = getMenu(name); if (menu == null) { throw new NullPointerException("Menu for href '"+name+"' is not in "+this.name); } return getMenuTranslated((Map) menu.get("menus"), rolez, lang, d, 0 ); } protected List<Map> getMenuTranslated(Map<String, Map> menus, Set<String> rolez, CoreLocale lang, int j, int i) { List<Map> list = new LinkedList(); if (null == menus||(j != 0 && j <= i)) { return list; } for(Map.Entry item : menus.entrySet()) { String h = (String) item.getKey(); Map v = (Map) item.getValue( ); Map m = (Map) v.get( "menus" ); Set r = (Set) v.get( "roles" ); List<Map> subz = getMenuTranslated(m, rolez, lang, j, i + 1); if (null != rolez) { if (null != r && !r.isEmpty()) { boolean y = true ; for (Object x : r) { if (rolez.contains((String) x)) { y = false; break; } } if (y) { continue; } } else if (null != m && !m.isEmpty()) { if (subz.isEmpty()) { continue; } } } String p = (String) v.get("hrel"); String d = (String) v.get("icon"); String s = (String) v.get("text"); String z = (String) v.get("hint"); s = s != null ? lang.translate(s) : ""; z = z != null ? lang.translate(z) : ""; Map menu = new HashMap(); menu.put("href", h); menu.put("hrel", p); menu.put("icon", d); menu.put("text", s); menu.put("hint", z); menu.put("menus", subz ); list.add( menu); } return list; } /** * * @return */ public List<Map> getRoleTranslates() { return getRoleTranslated(0, null); } public List<Map> getRoleTranslates(int d) { return getRoleTranslated(d, null); } /** * * @return * @throws io.github.ihongs.HongsException */ public List<Map> getRoleTranslated() throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getRoleTranslated(0, rolez); } public List<Map> getRoleTranslated(int d) throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getRoleTranslated(d, rolez); } public List<Map> getRoleTranslated(int d, Set<String> rolez) { CoreLocale lang = getCurrTranslator(); return getRoleTranslated(menus, rolez, lang, d, 0); } public List<Map> getRoleTranslates(String name) { return getRoleTranslated(name, 0, null); } public List<Map> getRoleTranslates(String name, int d) { return getRoleTranslated(name, d, null); } public List<Map> getRoleTranslated(String name) throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getRoleTranslated(name, 0, rolez); } public List<Map> getRoleTranslated(String name, int d) throws HongsException { Set rolez = getRoleSet(); if (rolez == null) { rolez = new HashSet(); } return getRoleTranslated(name, d, rolez); } public List<Map> getRoleTranslated(String name, int d, Set<String> rolez) { CoreLocale lang= getCurrTranslator(); Map menu = getMenu(name); if (menu == null) { throw new NullPointerException("Menu for href '"+name+"' is not in "+this.name); } return getRoleTranslated((Map) menu.get("menus"), rolez, lang, d, 0 ); } protected List<Map> getRoleTranslated(Map<String, Map> menus, Set<String> rolez, CoreLocale lang, int j, int i) { return getRoleTranslated(menus, rolez, lang, j, i, new HashSet(), new ArrayList(0)); } protected List<Map> getRoleTranslated(Map<String, Map> menus, Set<String> rolez, CoreLocale lang, int j, int i, Set q, List p) { List<Map> list = new LinkedList(); if (null == menus||(j != 0 && j <= i)) { return list; } for(Map.Entry item : menus.entrySet()) { Map v = (Map) item.getValue(); Map m = (Map) v.get("menus" ); Set r = (Set) v.get("roles" ); String t = (String) v.get("text"); String d = (String) v.get("hint"); t = t != null ? lang.translate(t) : ""; d = d != null ? lang.translate(d) : ""; if (r != null) { List<Map> rolz = new LinkedList(); for(String n : ( Set<String> ) r) { if (rolez != null && !rolez.contains(n)) { continue; } if (q.contains(n)) { continue; } Map o = getRole(n); Set x = (Set) o.get("depends"); String l = (String) o.get("text"); String b = (String) o.get("hint"); if (l == null || l.length( ) == 0 ) { continue; } l = l != null ? lang.translate(l) : ""; b = b != null ? lang.translate(b) : ""; Map role = new HashMap(); role.put("name", n); role.put("text", l); role.put("hint", b); role.put("rels", x); rolz.add(role); q.add(n); } if (! rolz.isEmpty()) { String h = (String) item.getKey(); String l = (String) v.get("hrel"); String b = (String) v.get("icon"); Map menu = new HashMap(); menu.put("href", h); menu.put("hrel", l); menu.put("icon", b); menu.put("text", t); menu.put("hint", d); menu.put("tabs", p); menu.put("roles", rolz ); list.add(menu); } } List<String> g = new ArrayList(p.size( )+1); g.addAll(p); g.add(t); List<Map> subz = getRoleTranslated(m, rolez, lang, j, i + 1, q, g); if (! subz.isEmpty()) { list.addAll(subz); } } return list; } / public static boolean hasConfFile(String name) { String fn = "/serial/"; fn = Core.DATA_PATH +fn + name + Cnst.NAVI_EXT + ".ser"; if (new File(fn).exists()) { return true; } fn = Core.CONF_PATH +"/"+ name + Cnst.NAVI_EXT + ".xml"; if (new File(fn).exists()) { return true; } fn = name.contains(".") || name.contains("/") ? name + Cnst.NAVI_EXT + ".xml" : Cnst.CONF_PACK +"/"+ name + Cnst.NAVI_EXT + ".xml"; return null != NaviMap.class.getClassLoader().getResourceAsStream(fn); } public static NaviMap getInstance(String name) throws HongsException { Core core = Core.getInstance (); String code = NaviMap.class.getName() + ":" + name; NaviMap inst = (NaviMap) core.get(code); if (inst == null) { inst = new NaviMap( name ); core.set(code, inst); } return inst; } public static NaviMap getInstance() throws HongsException { return getInstance("default"); } }
package protocolsupport.listeners; import org.bukkit.Bukkit; import org.bukkit.SoundCategory; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityPotionEffectEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import protocolsupport.ProtocolSupport; import protocolsupport.api.Connection; import protocolsupport.api.MaterialAPI; import protocolsupport.api.ProtocolSupportAPI; import protocolsupport.api.ProtocolType; import protocolsupport.api.ProtocolVersion; import protocolsupport.api.chat.components.BaseComponent; import protocolsupport.api.tab.TabAPI; import protocolsupport.protocol.utils.minecraftdata.MinecraftBlockData; import protocolsupport.protocol.utils.minecraftdata.MinecraftBlockData.BlockDataEntry; import protocolsupport.zplatform.ServerPlatform; public class FeatureEmulation implements Listener { public FeatureEmulation() { Bukkit.getScheduler().runTaskTimer( ProtocolSupport.getInstance(), () -> { for (Player player : Bukkit.getOnlinePlayers()) { ProtocolVersion version = ProtocolSupportAPI.getProtocolVersion(player); if ((version.getProtocolType() == ProtocolType.PC) && version.isBefore(ProtocolVersion.MINECRAFT_1_9)) { if (!player.isFlying() && (player.hasPotionEffect(PotionEffectType.LEVITATION) || player.hasPotionEffect(PotionEffectType.SLOW_FALLING))) { player.setVelocity(player.getVelocity()); } } } }, 1, 1 ); } @EventHandler public void onPotionEffectAdd(EntityPotionEffectEvent event) { if (!(event.getEntity() instanceof Player)) { return; } Player player = (Player) event.getEntity(); PotionEffect effect = event.getNewEffect(); if (effect != null) { int amplifierByte = (byte) effect.getAmplifier(); if (effect.getAmplifier() != amplifierByte) { event.setCancelled(true); player.addPotionEffect(new PotionEffect( effect.getType(), effect.getDuration(), amplifierByte, effect.isAmbient(), effect.hasParticles(), effect.hasIcon() ), true); } } } @EventHandler public void onShift(PlayerToggleSneakEvent event) { Player player = event.getPlayer(); Connection connection = ProtocolSupportAPI.getConnection(player); if ( player.isInsideVehicle() && (connection != null) && (connection.getVersion().getProtocolType() == ProtocolType.PC) && connection.getVersion().isBeforeOrEq(ProtocolVersion.MINECRAFT_1_5_2) ) { player.leaveVehicle(); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); Connection connection = ProtocolSupportAPI.getConnection(player); if ( (connection != null) && (connection.getVersion().getProtocolType() == ProtocolType.PC) && connection.getVersion().isBefore(ProtocolVersion.MINECRAFT_1_9) ) { BlockDataEntry blockdataentry = MinecraftBlockData.get(MaterialAPI.getBlockDataNetworkId(event.getBlock().getBlockData())); player.playSound( event.getBlock().getLocation(), blockdataentry.getBreakSound(), SoundCategory.BLOCKS, (blockdataentry.getVolume() + 1.0F) / 2.0F, blockdataentry.getPitch() * 0.8F ); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { if (((event.getCause() == DamageCause.FIRE_TICK) || (event.getCause() == DamageCause.FIRE) || (event.getCause() == DamageCause.DROWNING))) { for (Player player : ServerPlatform.get().getMiscUtils().getNearbyPlayers(event.getEntity().getLocation(), 48, 128, 48)) { if (player != null) { Connection connection = ProtocolSupportAPI.getConnection(player); if ( (connection != null) && (connection.getVersion().getProtocolType() == ProtocolType.PC) && connection.getVersion().isBefore(ProtocolVersion.MINECRAFT_1_12) ) { connection.sendPacket(ServerPlatform.get().getPacketFactory().createEntityStatusPacket(event.getEntity(), 2)); } } } } } @EventHandler public void onJoin(final PlayerJoinEvent event) { Bukkit.getScheduler().runTaskLater(ProtocolSupport.getInstance(), () -> { BaseComponent header = TabAPI.getDefaultHeader(); BaseComponent footer = TabAPI.getDefaultFooter(); if ((header != null) || (footer != null)) { TabAPI.sendHeaderFooter(event.getPlayer(), header, footer); } }, 1); } }
package abc.player; import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.print.PrintException; import javax.swing.JDialog; import org.antlr.v4.gui.Trees; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.Utils; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.junit.Test; import abc.parser.HeaderLexer; import abc.parser.HeaderParser; public class ParseTest { @Test(expected=AssertionError.class) public void testAssertionsEnabled() { assert false; // make sure assertions are enabled with VM argument: -ea } /* HeaderParser * Testing partitions: * Basics: * - index, title, key in order * - index/title/key out of order -- expect error * - missing index/title/key -- expect error * Index * - valid index, must be positive * - invalid index (missing X: or \n or negative) * Title * - valid title * - invalid title (missing T: or \n) * Composer: * - valid composer * - invalid composer (missing C: or \n) * Meter: * - digit/digit * - C * - C| * - invalid meter (missing M: or \n, too many fractions) * Length: * - valid length * - invalid length (missing L: or \n, too many fractions) * Tempo: * - valid tempo * - invalid tempo (missing Q: or \n, containing non-numerical chars) * Voice: * - valid voice * - valid voices (multiple) * - invalid voice (missing V: or \n) * Key: * - valid key * - key note is lowercase -- expect error * - invalid key note * - missing K: or \n * Comment (% followed by any text, not treated as a field) * Whitespace (all whitespace should be ignored/skipped) */ // @Test public void testHeaderParser(){ CharStream stream = new ANTLRInputStream("X:1\nT:hello world\nK:A\n"); HeaderLexer lexer = new HeaderLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); HeaderParser parser = new HeaderParser(tokens); ParseTree tree = parser.root(); // For debugging: // Future<JDialog> inspect = Trees.inspect(tree, parser); // Option 1: // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // e.printStackTrace(); // Option 2: // try { // Utils.waitForClose(inspect.get()); // } catch (Exception e) { // e.printStackTrace(); } // header with basic required fields in order: index, title, key // valid index, valid title, valid key @Test public void testHeaderRequiredFields(){ Header header = Parser.parseHeader("X:1\nT:hello world\nK:A\n"); assertEquals(1, header.index()); assertEquals("helloworld", header.title()); assertEquals(KeySignature.valueOf("A_MAJOR"), header.keySignature()); } // header with basic required fields not in order: title, key, index @Test (expected=Exception.class) public void testHeaderIndexNotFirst(){ Header header = Parser.parseHeader("T:hello world\nK:A\nX:1\n"); } // header with basic required field missing: title, key @Test (expected=Exception.class) public void testHeaderIndexMissing(){ Header header = Parser.parseHeader("T:hello world\nK:A\n"); } // header with basic required field missing: index, key @Test (expected=Exception.class) public void testHeaderTitleMissing(){ Header header = Parser.parseHeader("X:1\nK:A\n"); } // invalid index (missing X:) @Test (expected=Exception.class) public void testInvalidIndexMissingX(){ Header header = Parser.parseHeader("1\nT:hello world\nK:A\n"); assertEquals(1, header.index()); } // invalid index (missing \n) @Test (expected=Exception.class) public void testInvalidIndexMissingNewline(){ Header header = Parser.parseHeader("X:1T:hello world\nK:A\n"); assertEquals(1, header.index()); assertEquals("helloworld", header.title()); } // invalid index (negative) @Test (expected=Exception.class) public void testInvalidIndexNegative(){ Header header = Parser.parseHeader("X:-1\nT:hello world\nK:A\n"); assertEquals(1, header.index()); //treats - as extraneous input } // invalid title (missing T:) @Test (expected=Exception.class) public void testInvalidTitleMissingT(){ Header header = Parser.parseHeader("X:1\nhello world\nK:A\n"); assertEquals("helloworld", header.title()); } // invalid title (missing \n) @Test (expected=Exception.class) public void testInvalidTitleMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello worldK:A\n"); assertEquals("helloworld", header.title()); } // valid composer @Test public void testValidComposer(){ Header header = Parser.parseHeader("X:1\nT:hello world\nC:1.pOo2\nK:A\n"); assertEquals("1.pOo2", header.composer()); } // invalid composer (missing C:) @Test (expected=Exception.class) public void testInvalidComposerMissingC(){ Header header = Parser.parseHeader("X:1\nT:hello world\nunknown\nK:A\n"); assertEquals("unknown", header.composer()); } // invalid composer (missing \n) @Test (expected=Exception.class) public void testInvalidComposerMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello world\nC:unknownK:A\n"); assertEquals("unknown", header.composer()); } // valid meter (digit/digit) @Test public void testValidMeterFraction(){ Header header = Parser.parseHeader("X:1\nT:hello world\nM:6/8\nK:A\n"); assertEquals(new Fraction(6,8), header.meter()); } // valid meter (common time) @Test public void testValidMeterCommon(){ Header header = Parser.parseHeader("X:1\nT:hello world\nM:C\nK:A\n"); assertEquals(new Fraction(4,4), header.meter()); } // valid meter (cut time) @Test public void testValidMeterCut(){ Header header = Parser.parseHeader("X:1\nT:hello world\nM:C|\nK:A\n"); assertEquals(new Fraction(2,2), header.meter()); } // invalid meter (missing M:) @Test (expected=Exception.class) public void testInvalidMeterMissingM(){ Header header = Parser.parseHeader("X:1\nT:hello world\n6/8\nK:A\n"); assertEquals(new Fraction(6,8), header.meter()); } // invalid meter (missing \n) @Test (expected=Exception.class) public void testInvalidMeterMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello world\nM:6/8K:A\n"); assertEquals(new Fraction(6,8), header.meter()); } // invalid meter (too many fractions) @Test (expected = Exception.class) public void testInvalidMeterMultipleFractions(){ Header header = Parser.parseHeader("X:1\nT:hello world\nM:6/8/2\nK:A\n"); assertEquals(new Fraction(6,8), header.meter()); } // valid length @Test public void testValidLength(){ Header header = Parser.parseHeader("X:1\nT:hello world\nL:1/4\nK:A\n"); assertEquals(new Fraction(1,4), header.noteLength()); //returning 1/8 as length instead of 1/4 } // invalid length (missing L:) @Test (expected=Exception.class) public void testInvalidLengthMissingL(){ Header header = Parser.parseHeader("X:1\nT:hello world\n1/4\nK:A\n"); assertEquals(new Fraction(1,4), header.noteLength()); } // invalid length (missing \n) @Test (expected=Exception.class) public void testInvalidLengthMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello world\nL:1/4K:A\n"); } // invalid length (too many fractions) @Test (expected=Exception.class) public void testInvalidLengthMultipleFractions(){ Header header = Parser.parseHeader("X:1\nT:hello world\nL:1/4/3\nK:A\n"); assertEquals(new Fraction(1,4), header.noteLength()); //also returns 1/8 instead of 1/4 } // valid tempo @Test public void testValidTempo(){ Header header = Parser.parseHeader("X:1\nT:hello world\nQ:1/8=100\nK:A\n"); assertEquals(100, header.tempo()); } // invalid tempo (missing Q:) @Test (expected=Exception.class) public void testInvalidTempoMissingQ(){ Header header = Parser.parseHeader("X:1\nT:hello world\n1/8=100\nK:A\n"); assertEquals(100, header.tempo()); } // invalid tempo (missing \n) @Test (expected=Exception.class) public void testInvalidTempoMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello world\nQ:1/8=100K:A\n"); assertEquals(100, header.tempo()); } // invalid tempo (non-numerical characters) @Test (expected=Exception.class) public void testInvalidTempoNonNumerical(){ Header header = Parser.parseHeader("X:1\nT:hello world\nQ:a=100K:A\n"); assertEquals(100, header.tempo()); } // valid voice @Test public void testValidVoice(){ Header header = Parser.parseHeader("X:1\nT:hello world\nV:21vd.\nK:A\n"); assertEquals(("21vd."), header.voices().get(0)); } // valid voices (multiple) @Test public void testValidVoiceMultiple(){ Header header = Parser.parseHeader("X:1\nT:hello world\nV:voice1\nV:voice2\nK:A\n"); assertTrue(header.voices().contains("voice1")); assertTrue(header.voices().contains("voice2")); } // invalid voice (missing V:) @Test (expected=Exception.class) public void testInvalidVoiceMissingV(){ Header header = Parser.parseHeader("X:1\nT:hello world\nvoice1\nK:A\n"); assertTrue(header.voices().contains("voice1")); } // invalid voice (missing \n) @Test (expected=Exception.class) public void testInvalidVoiceMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello world\nV:voice1K:A\n"); assertEquals("voice1", header.voices()); } // valid key (minor) @Test public void testValidKeyMinor(){ Header header = Parser.parseHeader("X:1\nT:hello world\nK:Am\n"); assertEquals(KeySignature.valueOf("A_MINOR"), header.keySignature()); } // valid key (sharp) @Test public void testValidKeySharp(){ Header header = Parser.parseHeader("X:1\nT:hello world\nK:A assertEquals(KeySignature.valueOf("A_SHARP_MINOR"), header.keySignature()); } // valid key (flat) @Test public void testValidKeyFlat(){ Header header = Parser.parseHeader("X:1\nT:hello world\nK:Ab\n"); assertEquals(KeySignature.valueOf("A_FLAT_MAJOR"), header.keySignature()); } // invalid key (note letter is lowercase) @Test (expected=Exception.class) public void testInvalidKeyLowercase(){ Header header = Parser.parseHeader("X:1\nT:hello world\nK:a\n"); assertEquals(KeySignature.valueOf("A_MAJOR"), header.keySignature()); } // invalid key (missing K:) @Test (expected=Exception.class) public void testInvalidKeyMissingK(){ Header header = Parser.parseHeader("X:1\nT:hello world\nA\n"); assertEquals(KeySignature.valueOf("A_MAJOR"), header.keySignature()); } // invalid key (missing \n) @Test (expected=Exception.class) public void testInvalidKeyMissingNewline(){ Header header = Parser.parseHeader("X:1\nT:hello world\nK:A"); assertEquals(KeySignature.valueOf("A_MAJOR"), header.keySignature()); } // comment @Test public void testComment(){ Header header = Parser.parseHeader("X:1%comment\nT:hello world\nK:A\n"); assertEquals(1, header.index()); assertEquals("helloworld", header.title()); assertEquals(KeySignature.valueOf("A_MAJOR"), header.keySignature()); } // whitespace @Test public void testWhitespace(){ Header header = Parser.parseHeader("X:1 \nT: hel lo wor ld\nK: A \n"); assertEquals(1, header.index()); assertEquals("helloworld", header.title()); assertEquals(KeySignature.valueOf("A_MAJOR"), header.keySignature()); } // symbols @Test public void testSymbols(){ Header header = Parser.parseHeader("X:1\nT:.~`!@$^&*()-_+{[}]|\\;:\'\"<>,?'&\nK:A\n"); assertEquals(".~`!@$^&*()-_+{[}]|\\;:'\"<>,?'&", header.title()); } /*** * TODO: FIGURE OUT HOW TO DEAL WITH ACCIDENTALS IN MEASURES */ //test body parse /* * for duration n/m --> absent numerator assumed to be 1, absent denominator assumed to be 2 * Note: * - note letter --> lowercase, uppercase * - , or ' (octave change) --> 0, 1, >1 * - accidental --> __, _, ^, ^^ * - duration --> default length, n, n/m, /m, n/, / * Rest: * - duration --> default length, n, n/m, /m, n/, / * Chord: * - number of notes --> 1, 2, >2 * - duration --> default length, modified length * - different durations --> no, yes * Tuplet: * - duplet --> notes only, chords only, notes and chords * - triplet --> notes only, chords only, notes and chords * - quadruplet --> notes only, chords only, notes and chords * Measure: * - one element (note or rest) * - multiple elements (notes and rests) * - type (normal, start repeat, doublebar, first ending, * second ending, end repeat, single repeat) * Normal measure: * - one element (note or rest) * - multiple elements (notes and rests) * Start repeat measure: * - start repeat --> first measure or preceded by another measure * Doublebar measure: * - doublebar --> || or [| or |] * First ending measure: * - first ending length --> one measure, multiple measures * Second ending measure: * - second ending length --> one measure, multiple measures * End repeat measure */ // covers normal measure (one element), note (uppercase note letter), note (default length duration) @Test public void testUppercaseNoteDefaultLength(){ String test = "A|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (length n), note (one octave above) @Test public void testLowercaseNoteLengthN(){ String test = "a2|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,2), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,2), 'A', 1); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (length n/m) @Test public void testLowercaseNoteLengthNSlashM(){ String test = "a3/2|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(3,8), voice.duration()); } // covers normal measure (one element), note (lowercase note letter), note (length n/) @Test public void testLowercaseNoteLengthNSlash(){ String test = "a3/|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(3,8), voice.duration()); } // covers normal measure (one element), note (lowercase note letter), note (length /m) @Test public void testLowercaseNoteLengthSlashM(){ String test = "a/3|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,12), voice.duration()); } // covers normal measure (one element), note (lowercase note letter), note (length /) @Test public void testLowercaseNoteLengthSlash(){ String test = "a/|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,8), voice.duration()); } // covers normal measure (one element), note (lowercase note letter), note (sharp accidental) @Test public void testLowercaseNoteLengthNSharp(){ String test = "^a|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 1, 1); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (double sharp accidental) @Test public void testLowercaseNoteDoubleSharp(){ String test = "^^a|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 1, 2); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (natural) @Test public void testLowercaseNoteNatural(){ String test = "=f|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("G_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'F', 1, 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (multiple elements), note (lowercase note letter), note (natural) @Test public void testLowercaseNoteSharpThenNatural(){ String test = "^a =a|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,2), voice.duration()); List<Music> expected = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 1, 1); Note note2 = new Note(new Fraction(1,4), 'A', 1, 0); expected.add(note1); expected.add(note2); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (flat accidental) @Test public void testLowercaseNoteFlat(){ String test = "_a|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 1, -1); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (double flat accidental) @Test public void testLowercaseNoteDoubleFlat(){ String test = "__a|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 1, -2); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (two octaves above) @Test public void testLowercaseNoteOneApostrophe(){ String test = "a'|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 2); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (three octaves above) @Test public void testLowercaseNoteTwoApostrophes(){ String test = "a''|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 3); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (uppercase note letter), note (one octave below) @Test public void testUppercaseNoteOneComma(){ String test = "A,|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', -1); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (uppercase note letter), note (two octaves below) @Test public void testUppercaseNoteTwoCommas(){ String test = "A,,|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', -2); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), note (lowercase note letter), note (octaves cancel) @Test public void testLowercaseNoteOneComma(){ String test = "a,|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers normal measure (one element), rest (default length) @Test public void testRestDefaultLength(){ String test = "z|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); } // covers normal measure (one element), rest (length n) @Test public void testRestLengthN(){ String test = "z2|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,2), voice.duration()); } // covers normal measure (one element), rest (length n/m) @Test public void testRestLengthNSlashM(){ String test = "z3/2|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(3,8), voice.duration()); } // covers normal measure (one element), rest (length n/) @Test public void testRestLengthNSlash(){ String test = "z3/|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(3,8), voice.duration()); } // covers normal measure (one element), rest (length /m) @Test public void testRestLengthSlashM(){ String test = "z/3|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,12), voice.duration()); } // covers normal measure (one element), rest (length /) @Test public void testRestLengthSlash(){ String test = "z/|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,8), voice.duration()); } // covers chord (one note), chord (default length) @Test public void testChordOneNote(){ String test = "[C]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); List<Music> chordNotes = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'C', 0); chordNotes.add(note); Chord chord = new Chord(chordNotes); expected.add(chord); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers chord (two notes), chord (default length) @Test public void testChordTwoNotes(){ String test = "[CE]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); List<Music> chordNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); chordNotes.add(note1); chordNotes.add(note2); Chord chord = new Chord(chordNotes); expected.add(chord); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers chord (three notes), chord (default length) @Test public void testChordThreeNotesDefaultLength(){ String test = "[CEG]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,4), voice.duration()); List<Music> expected = new ArrayList<>(); List<Music> chordNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); chordNotes.add(note1); chordNotes.add(note2); chordNotes.add(note3); Chord chord = new Chord(chordNotes); expected.add(chord); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers chord (three notes), chord (modified length), chord (no different durations) @Test public void testChordThreeNotesModifiedLength(){ String test = "[C2E2G2]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); assertEquals(new Fraction(1,2), voice.duration()); List<Music> expected = new ArrayList<>(); List<Music> chordNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,2), 'C', 0); Note note2 = new Note(new Fraction(1,2), 'E', 0); Note note3 = new Note(new Fraction(1,2), 'G', 0); chordNotes.add(note1); chordNotes.add(note2); chordNotes.add(note3); Chord chord = new Chord(chordNotes); expected.add(chord); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers chord (three notes), chord (length n), chord (yes different durations) @Test public void testChordTwoNotesDifferentDurations(){ String test = "[C2E4]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,2), 'C', 0); Note note2 = new Note(new Fraction(1,1), 'E', 0); chordNotes.add(note1); chordNotes.add(note2); Chord chord = new Chord(chordNotes); expected.add(chord); assertEquals(new Fraction(1,2), chord.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (duplet), duplet (notes only) @Test public void testDupletNotesOnly(){ String test = "(2CE|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); tupletNotes.add(note1); tupletNotes.add(note2); Tuplet tuplet = new Tuplet(2, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(3,4), tuplet.duration()); assertEquals(new Fraction(3,4), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (duplet), duplet (chords only) @Test public void testDupletChordsOnly(){ String test = "(2[CE][GB]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes1 = new ArrayList<>(); List<Music> chordNotes2 = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); Note note4 = new Note(new Fraction(1,4), 'B', 0); chordNotes1.add(note1); chordNotes1.add(note2); chordNotes2.add(note3); chordNotes2.add(note4); Chord chord1 = new Chord(chordNotes1); Chord chord2 = new Chord(chordNotes2); tupletNotes.add(chord1); tupletNotes.add(chord2); Tuplet tuplet = new Tuplet(2, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(3,4), tuplet.duration()); assertEquals(new Fraction(3,4), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (duplet), duplet (notes and chords) @Test public void testDupletNotesAndChords(){ String test = "(2[CE]G|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes1 = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); chordNotes1.add(note1); chordNotes1.add(note2); Chord chord1 = new Chord(chordNotes1); tupletNotes.add(chord1); tupletNotes.add(note3); Tuplet tuplet = new Tuplet(2, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(3,4), tuplet.duration()); assertEquals(new Fraction(3,4), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (triplet), triplet (notes only) @Test public void testTripletNotesOnly(){ String test = "(3CEG|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); tupletNotes.add(note1); tupletNotes.add(note2); tupletNotes.add(note3); Tuplet tuplet = new Tuplet(3, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(1,2), tuplet.duration()); assertEquals(new Fraction(1,2), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (triplet), triplet (chords only) @Test public void testTripletChordsOnly(){ String test = "(3[CE][GB][DF]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes1 = new ArrayList<>(); List<Music> chordNotes2 = new ArrayList<>(); List<Music> chordNotes3 = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); Note note4 = new Note(new Fraction(1,4), 'B', 0); Note note5 = new Note(new Fraction(1,4), 'D', 0); Note note6 = new Note(new Fraction(1,4), 'F', 0); chordNotes1.add(note1); chordNotes1.add(note2); chordNotes2.add(note3); chordNotes2.add(note4); chordNotes3.add(note5); chordNotes3.add(note6); Chord chord1 = new Chord(chordNotes1); Chord chord2 = new Chord(chordNotes2); Chord chord3 = new Chord(chordNotes3); tupletNotes.add(chord1); tupletNotes.add(chord2); tupletNotes.add(chord3); Tuplet tuplet = new Tuplet(3, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(1,2), tuplet.duration()); assertEquals(new Fraction(1,2), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (triplet), triplet (notes and chords) @Test public void testTripletNotesAndChords(){ String test = "(3[CE][GB]D|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes1 = new ArrayList<>(); List<Music> chordNotes2 = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); Note note4 = new Note(new Fraction(1,4), 'B', 0); Note note5 = new Note(new Fraction(1,4), 'D', 0); chordNotes1.add(note1); chordNotes1.add(note2); chordNotes2.add(note3); chordNotes2.add(note4); Chord chord1 = new Chord(chordNotes1); Chord chord2 = new Chord(chordNotes2); tupletNotes.add(chord1); tupletNotes.add(chord2); tupletNotes.add(note5); Tuplet tuplet = new Tuplet(3, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(1,2), tuplet.duration()); assertEquals(new Fraction(1,2), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (quadruplet), quadruplet (notes only) @Test public void testQuadrupletNotesOnly(){ String test = "(4CEGB|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); Note note4 = new Note(new Fraction(1,4), 'B', 0); tupletNotes.add(note1); tupletNotes.add(note2); tupletNotes.add(note3); tupletNotes.add(note4); Tuplet tuplet = new Tuplet(4, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(3,4), tuplet.duration()); assertEquals(new Fraction(3,4), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (quadruplet), quadruplet (chords only) @Test public void testQuadrupletChordsOnly(){ String test = "(4[CE][GB][DF][Ac]|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes1 = new ArrayList<>(); List<Music> chordNotes2 = new ArrayList<>(); List<Music> chordNotes3 = new ArrayList<>(); List<Music> chordNotes4 = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); Note note4 = new Note(new Fraction(1,4), 'B', 0); Note note5 = new Note(new Fraction(1,4), 'D', 0); Note note6 = new Note(new Fraction(1,4), 'F', 0); Note note7 = new Note(new Fraction(1,4), 'A', 0); Note note8 = new Note(new Fraction(1,4), 'C', 1); chordNotes1.add(note1); chordNotes1.add(note2); chordNotes2.add(note3); chordNotes2.add(note4); chordNotes3.add(note5); chordNotes3.add(note6); chordNotes4.add(note7); chordNotes4.add(note8); Chord chord1 = new Chord(chordNotes1); Chord chord2 = new Chord(chordNotes2); Chord chord3 = new Chord(chordNotes3); Chord chord4 = new Chord(chordNotes4); tupletNotes.add(chord1); tupletNotes.add(chord2); tupletNotes.add(chord3); tupletNotes.add(chord4); Tuplet tuplet = new Tuplet(4, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(3,4), tuplet.duration()); assertEquals(new Fraction(3,4), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers tuplet (quadruplet), quadruplet (notes and chords) @Test public void testQuadrupletNotesAndChords(){ String test = "(4[CE]G[BD]F|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> chordNotes1 = new ArrayList<>(); List<Music> chordNotes2 = new ArrayList<>(); List<Music> tupletNotes = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'C', 0); Note note2 = new Note(new Fraction(1,4), 'E', 0); Note note3 = new Note(new Fraction(1,4), 'G', 0); Note note4 = new Note(new Fraction(1,4), 'B', 0); Note note5 = new Note(new Fraction(1,4), 'D', 0); Note note6 = new Note(new Fraction(1,4), 'F', 0); chordNotes1.add(note1); chordNotes1.add(note2); chordNotes2.add(note4); chordNotes2.add(note5); Chord chord1 = new Chord(chordNotes1); Chord chord2 = new Chord(chordNotes2); tupletNotes.add(chord1); tupletNotes.add(note3); tupletNotes.add(chord2); tupletNotes.add(note6); Tuplet tuplet = new Tuplet(4, tupletNotes); expected.add(tuplet); assertEquals(new Fraction(3,4), tuplet.duration()); assertEquals(new Fraction(3,4), voice.duration()); Measure measure = new Measure(expected, false, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers start repeat measure (first measure) @Test public void testStartRepeatMeasureFirst(){ String test = "|:A|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 0); expected.add(note1); Measure measure = new Measure(expected, true, false, false, false); assertTrue(voice.getElements().contains(measure)); } // covers start repeat measure (preceded by another measure) @Test public void testStartRepeatMeasureSecond(){ String test = "A|:B|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> measure1 = new ArrayList<>(); List<Music> measure2 = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 0); Note note2 = new Note(new Fraction(1,4), 'B', 0); measure1.add(note1); measure2.add(note2); Measure expectedMeasure1 = new Measure(measure1, false, false, false, false); Measure expectedMeasure2 = new Measure(measure2, true, false, false, false); expected.add(expectedMeasure1); expected.add(expectedMeasure2); assertTrue(voice.getElements().contains(expectedMeasure1)); assertTrue(voice.getElements().contains(expectedMeasure2)); } // covers doublebar measure (||) @Test public void testDoubleBarMeasure1(){ String test = "A||"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, true); assertTrue(voice.getElements().contains(measure)); } // covers doublebar measure ([|) @Test public void testDoubleBarMeasure2(){ String test = "A[|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, true); assertTrue(voice.getElements().contains(measure)); } // covers doublebar measure (|]) @Test public void testDoubleBarMeasure3(){ String test = "A|]"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, true); assertTrue(voice.getElements().contains(measure)); } // covers first ending measure (one measure first ending) @Test public void testFirstEndingOneMeasure(){ String test = "A|[1B:|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> measure1 = new ArrayList<>(); List<Music> measure2 = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 0); Note note2 = new Note(new Fraction(1,4), 'B', 0); measure1.add(note1); measure2.add(note2); Measure expectedMeasure1 = new Measure(measure1, false, false, false, false); Measure expectedMeasure2 = new Measure(measure2, false, true, true, false); expected.add(expectedMeasure1); expected.add(expectedMeasure2); assertTrue(voice.getElements().contains(expectedMeasure1)); assertTrue(voice.getElements().contains(expectedMeasure2)); } // covers first ending measure (multiple measure first ending) @Test public void testFirstEndingMultipleMeasure(){ String test = "A|[1B|C:|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> measure1 = new ArrayList<>(); List<Music> measure2 = new ArrayList<>(); List<Music> measure3 = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 0); Note note2 = new Note(new Fraction(1,4), 'B', 0); Note note3 = new Note(new Fraction(1,4), 'C', 0); measure1.add(note1); measure2.add(note2); measure3.add(note3); Measure expectedMeasure1 = new Measure(measure1, false, false, false, false); Measure expectedMeasure2 = new Measure(measure2, false, false, true, false); Measure expectedMeasure3 = new Measure(measure3, false, true, false, false); expected.add(expectedMeasure1); expected.add(expectedMeasure2); expected.add(expectedMeasure3); assertTrue(voice.getElements().contains(expectedMeasure1)); assertTrue(voice.getElements().contains(expectedMeasure2)); assertTrue(voice.getElements().contains(expectedMeasure3)); } // covers single repeat measure (one measure second ending) @Test public void testSecondEndingOneMeasure(){ String test = "[2A||"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, false, false, true); assertTrue(voice.getElements().contains(measure)); } // covers single repeat measure (multiple measure second ending) @Test public void testSecondEndingMultipleMeasure(){ String test = "[2A|B||"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> measure1 = new ArrayList<>(); List<Music> measure2 = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 0); Note note2 = new Note(new Fraction(1,4), 'B', 0); measure1.add(note1); measure2.add(note2); Measure expectedMeasure1 = new Measure(measure1, false, false, false, false); Measure expectedMeasure2 = new Measure(measure2, false, false, false, true); expected.add(expectedMeasure1); expected.add(expectedMeasure2); assertTrue(voice.getElements().contains(expectedMeasure1)); assertTrue(voice.getElements().contains(expectedMeasure2)); } // covers end repeat measure @Test public void testEndRepeatMeasure(){ String test = "A:|"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); Note note = new Note(new Fraction(1,4), 'A', 0); expected.add(note); Measure measure = new Measure(expected, false, true, false, false); assertTrue(voice.getElements().contains(measure)); } // covers first ending and second ending @Test public void testFirstEndingSecondEnding(){ String test = "A|[1B|C:|[2D||"; Voice voice = (Voice) Parser.parseMusic(test, new Fraction(1,4), KeySignature.valueOf("C_MAJOR"), "voice"); List<Music> expected = new ArrayList<>(); List<Music> measure1 = new ArrayList<>(); List<Music> measure2 = new ArrayList<>(); List<Music> measure3 = new ArrayList<>(); List<Music> measure4 = new ArrayList<>(); Note note1 = new Note(new Fraction(1,4), 'A', 0); Note note2 = new Note(new Fraction(1,4), 'B', 0); Note note3 = new Note(new Fraction(1,4), 'C', 0); Note note4 = new Note(new Fraction(1,4), 'D', 0); measure1.add(note1); measure2.add(note2); measure3.add(note3); measure4.add(note4); Measure expectedMeasure1 = new Measure(measure1, false, false, false, false); Measure expectedMeasure2 = new Measure(measure2, false, false, true, false); Measure expectedMeasure3 = new Measure(measure3, false, true, false, false); Measure expectedMeasure4 = new Measure(measure4, false, false, false, true); expected.add(expectedMeasure1); expected.add(expectedMeasure2); expected.add(expectedMeasure3); expected.add(expectedMeasure4); assertTrue(voice.getElements().contains(expectedMeasure1)); assertTrue(voice.getElements().contains(expectedMeasure2)); assertTrue(voice.getElements().contains(expectedMeasure3)); assertTrue(voice.getElements().contains(expectedMeasure4)); } }
package io.moquette.broker; import io.moquette.broker.subscriptions.Topic; import io.moquette.broker.security.IAuthenticator; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufHolder; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.mqtt.*; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static io.netty.channel.ChannelFutureListener.CLOSE_ON_FAILURE; import static io.netty.channel.ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE; import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.*; import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from; import static io.netty.handler.codec.mqtt.MqttQoS.*; final class MQTTConnection { private static final Logger LOG = LoggerFactory.getLogger(MQTTConnection.class); final Channel channel; private final BrokerConfiguration brokerConfig; private final IAuthenticator authenticator; private final SessionRegistry sessionRegistry; private final PostOffice postOffice; private volatile boolean connected; private final AtomicInteger lastPacketId = new AtomicInteger(0); private Session bindedSession; MQTTConnection(Channel channel, BrokerConfiguration brokerConfig, IAuthenticator authenticator, SessionRegistry sessionRegistry, PostOffice postOffice) { this.channel = channel; this.brokerConfig = brokerConfig; this.authenticator = authenticator; this.sessionRegistry = sessionRegistry; this.postOffice = postOffice; this.connected = false; } void handleMessage(MqttMessage msg) { MqttMessageType messageType = msg.fixedHeader().messageType(); LOG.debug("Received MQTT message, type: {}", messageType); switch (messageType) { case CONNECT: processConnect((MqttConnectMessage) msg); break; case SUBSCRIBE: processSubscribe((MqttSubscribeMessage) msg); break; case UNSUBSCRIBE: processUnsubscribe((MqttUnsubscribeMessage) msg); break; case PUBLISH: processPublish((MqttPublishMessage) msg); break; case PUBREC: processPubRec(msg); break; case PUBCOMP: processPubComp(msg); break; case PUBREL: processPubRel(msg); break; case DISCONNECT: processDisconnect(msg); break; case PUBACK: processPubAck(msg); break; case PINGREQ: MqttFixedHeader pingHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, AT_MOST_ONCE, false, 0); MqttMessage pingResp = new MqttMessage(pingHeader); channel.writeAndFlush(pingResp).addListener(CLOSE_ON_FAILURE); break; default: LOG.error("Unknown MessageType: {}", messageType); break; } } private void processPubComp(MqttMessage msg) { final int messageID = ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId(); this.postOffice.routeCommand(bindedSession.getClientID(), () -> { bindedSession.processPubComp(messageID); return bindedSession.getClientID(); }); } private void processPubRec(MqttMessage msg) { final int messageID = ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId(); this.postOffice.routeCommand(bindedSession.getClientID(), () -> { bindedSession.processPubRec(messageID); return null; }); } static MqttMessage pubrel(int messageID) { MqttFixedHeader pubRelHeader = new MqttFixedHeader(MqttMessageType.PUBREL, false, AT_LEAST_ONCE, false, 0); return new MqttMessage(pubRelHeader, from(messageID)); } private void processPubAck(MqttMessage msg) { final int messageID = ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId(); final String clientId = getClientId(); this.postOffice.routeCommand(clientId, () -> { bindedSession.pubAckReceived(messageID); return null; }); } Future<PostOffice.RouteResult> processConnect(MqttConnectMessage msg) { MqttConnectPayload payload = msg.payload(); String clientId = payload.clientIdentifier(); final String username = payload.userName(); LOG.trace("Processing CONNECT message. CId: {} username: {}", clientId, username); if (isNotProtocolVersion(msg, MqttVersion.MQTT_3_1) && isNotProtocolVersion(msg, MqttVersion.MQTT_3_1_1)) { LOG.warn("MQTT protocol version is not valid. CId: {}", clientId); abortConnection(CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION); return CompletableFuture.completedFuture(null); } final boolean cleanSession = msg.variableHeader().isCleanSession(); if (clientId == null || clientId.length() == 0) { if (!brokerConfig.isAllowZeroByteClientId()) { LOG.info("Broker doesn't permit MQTT empty client ID. Username: {}", username); abortConnection(CONNECTION_REFUSED_IDENTIFIER_REJECTED); return CompletableFuture.completedFuture(null); } if (!cleanSession) { LOG.info("MQTT client ID cannot be empty for persistent session. Username: {}", username); abortConnection(CONNECTION_REFUSED_IDENTIFIER_REJECTED); return CompletableFuture.completedFuture(null); } // Generating client id. clientId = UUID.randomUUID().toString().replace("-", ""); LOG.debug("Client has connected with integration generated id: {}, username: {}", clientId, username); } if (!login(msg, clientId)) { abortConnection(CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD); channel.close().addListener(CLOSE_ON_FAILURE); return CompletableFuture.completedFuture(null); } final String sessionId = clientId; return this.postOffice.routeCommand(clientId, () -> { executeConnect(msg, sessionId); return null; }); } /** * Invoked by the Session's event loop. * */ private void executeConnect(MqttConnectMessage msg, String clientId) { final SessionRegistry.SessionCreationResult result; try { LOG.trace("Binding MQTTConnection to session"); result = sessionRegistry.createOrReopenSession(msg, clientId, this.getUsername()); result.session.bind(this); bindedSession = result.session; } catch (SessionCorruptedException scex) { LOG.warn("MQTT session for client ID {} cannot be created", clientId); abortConnection(CONNECTION_REFUSED_SERVER_UNAVAILABLE); return; } final boolean msgCleanSessionFlag = msg.variableHeader().isCleanSession(); boolean isSessionAlreadyPresent = !msgCleanSessionFlag && result.alreadyStored; final String clientIdUsed = clientId; final MqttConnAckMessage ackMessage = MqttMessageBuilders.connAck() .returnCode(CONNECTION_ACCEPTED) .sessionPresent(isSessionAlreadyPresent).build(); channel.writeAndFlush(ackMessage).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.trace("CONNACK sent, channel: {}", channel); if (!result.session.completeConnection()) { // send DISCONNECT and close the channel final MqttMessage disconnectMsg = MqttMessageBuilders.disconnect().build(); channel.writeAndFlush(disconnectMsg).addListener(CLOSE); LOG.warn("CONNACK is sent but the session created can't transition in CONNECTED state"); } else { NettyUtils.clientID(channel, clientIdUsed); connected = true; // OK continue with sending queued messages and normal flow if (result.mode == SessionRegistry.CreationModeEnum.REOPEN_EXISTING) { result.session.sendQueuedMessagesWhileOffline(); } initializeKeepAliveTimeout(channel, msg, clientIdUsed); setupInflightResender(channel); postOffice.dispatchConnection(msg); LOG.trace("dispatch connection: {}", msg); } } else { bindedSession.disconnect(); sessionRegistry.remove(bindedSession); LOG.error("CONNACK send failed, cleanup session and close the connection", future.cause()); channel.close(); } } }); } private void setupInflightResender(Channel channel) { channel.pipeline() .addFirst("inflightResender", new InflightResender(5_000, TimeUnit.MILLISECONDS)); } private void initializeKeepAliveTimeout(Channel channel, MqttConnectMessage msg, String clientId) { int keepAlive = msg.variableHeader().keepAliveTimeSeconds(); NettyUtils.keepAlive(channel, keepAlive); NettyUtils.cleanSession(channel, msg.variableHeader().isCleanSession()); NettyUtils.clientID(channel, clientId); int idleTime = Math.round(keepAlive * 1.5f); setIdleTime(channel.pipeline(), idleTime); LOG.debug("Connection has been configured CId={}, keepAlive={}, removeTemporaryQoS2={}, idleTime={}", clientId, keepAlive, msg.variableHeader().isCleanSession(), idleTime); } private void setIdleTime(ChannelPipeline pipeline, int idleTime) { if (pipeline.names().contains("idleStateHandler")) { pipeline.remove("idleStateHandler"); } pipeline.addFirst("idleStateHandler", new IdleStateHandler(idleTime, 0, 0)); } private boolean isNotProtocolVersion(MqttConnectMessage msg, MqttVersion version) { return msg.variableHeader().version() != version.protocolLevel(); } private void abortConnection(MqttConnectReturnCode returnCode) { MqttConnAckMessage badProto = MqttMessageBuilders.connAck() .returnCode(returnCode) .sessionPresent(false).build(); channel.writeAndFlush(badProto).addListener(FIRE_EXCEPTION_ON_FAILURE); channel.close().addListener(CLOSE_ON_FAILURE); } private boolean login(MqttConnectMessage msg, final String clientId) { // handle user authentication if (msg.variableHeader().hasUserName()) { byte[] pwd = null; if (msg.variableHeader().hasPassword()) { pwd = msg.payload().passwordInBytes(); } else if (!brokerConfig.isAllowAnonymous()) { LOG.info("Client didn't supply any password and MQTT anonymous mode is disabled CId={}", clientId); return false; } final String login = msg.payload().userName(); if (!authenticator.checkValid(clientId, login, pwd)) { LOG.info("Authenticator has rejected the MQTT credentials CId={}, username={}", clientId, login); return false; } NettyUtils.userName(channel, login); } else if (!brokerConfig.isAllowAnonymous()) { LOG.info("Client didn't supply any credentials and MQTT anonymous mode is disabled. CId={}", clientId); return false; } return true; } void handleConnectionLost() { final String clientID = NettyUtils.clientID(channel); if (clientID == null || clientID.isEmpty()) { return; } // this must not be done on the netty thread LOG.info("Notifying connection lost event"); postOffice.routeCommand(clientID, () -> { processConnectionLost(clientID); return null; }); } private void processConnectionLost(String clientID) { if (bindedSession.hasWill()) { postOffice.fireWill(bindedSession.getWill()); } if (bindedSession.isClean()) { LOG.debug("Remove session for client"); sessionRegistry.remove(bindedSession); } else { bindedSession.disconnect(); } connected = false; //dispatch connection lost to intercept. String userName = NettyUtils.userName(channel); postOffice.dispatchConnectionLost(clientID,userName); LOG.trace("dispatch disconnection: userName={}", userName); } boolean isConnected() { return connected; } void dropConnection() { channel.close().addListener(FIRE_EXCEPTION_ON_FAILURE); } Future<PostOffice.RouteResult> processDisconnect(MqttMessage msg) { final String clientID = NettyUtils.clientID(channel); LOG.trace("Start DISCONNECT"); if (!connected) { LOG.info("DISCONNECT received on already closed connection"); return CompletableFuture.completedFuture(null); } return this.postOffice.routeCommand(clientID, () -> { bindedSession.disconnect(); connected = false; channel.close().addListener(FIRE_EXCEPTION_ON_FAILURE); LOG.trace("Processed DISCONNECT"); String userName = NettyUtils.userName(channel); postOffice.clientDisconnected(clientID, userName); LOG.trace("dispatch disconnection userName={}", userName); return null; }); } Future<PostOffice.RouteResult> processSubscribe(MqttSubscribeMessage msg) { final String clientID = NettyUtils.clientID(channel); if (!connected) { LOG.warn("SUBSCRIBE received on already closed connection"); dropConnection(); return CompletableFuture.completedFuture(null); } final String username = NettyUtils.userName(channel); return postOffice.routeCommand(clientID, () -> { postOffice.subscribeClientToTopics(msg, clientID, username, this); return null; }); } void sendSubAckMessage(int messageID, MqttSubAckMessage ackMessage) { LOG.trace("Sending SUBACK response messageId: {}", messageID); channel.writeAndFlush(ackMessage).addListener(FIRE_EXCEPTION_ON_FAILURE); } private void processUnsubscribe(MqttUnsubscribeMessage msg) { List<String> topics = msg.payload().topics(); final String clientID = NettyUtils.clientID(channel); final int messageId = msg.variableHeader().messageId(); postOffice.routeCommand(clientID, () -> { LOG.trace("Processing UNSUBSCRIBE message. topics: {}", topics); postOffice.unsubscribe(topics, this, messageId); return null; }); } void sendUnsubAckMessage(List<String> topics, String clientID, int messageID) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, AT_MOST_ONCE, false, 0); MqttUnsubAckMessage ackMessage = new MqttUnsubAckMessage(fixedHeader, from(messageID)); LOG.trace("Sending UNSUBACK message. messageId: {}, topics: {}", messageID, topics); channel.writeAndFlush(ackMessage).addListener(FIRE_EXCEPTION_ON_FAILURE); LOG.trace("Client unsubscribed from topics <{}>", topics); } Future<? extends Object> processPublish(MqttPublishMessage msg) { final MqttQoS qos = msg.fixedHeader().qosLevel(); final String username = NettyUtils.userName(channel); final String topicName = msg.variableHeader().topicName(); final String clientId = getClientId(); final int messageID = msg.variableHeader().packetId(); LOG.trace("Processing PUBLISH message, topic: {}, messageId: {}, qos: {}", topicName, messageID, qos); final Topic topic = new Topic(topicName); if (!topic.isValid()) { LOG.debug("Drop connection because of invalid topic format"); dropConnection(); } // retain else msg is cleaned by the NewNettyMQTTHandler and is not available // in execution by SessionEventLoop msg.retain(); switch (qos) { case AT_MOST_ONCE: return postOffice.routeCommand(clientId, () -> { postOffice.receivedPublishQos0(topic, username, clientId, msg); return null; }); case AT_LEAST_ONCE: return postOffice.routeCommand(clientId, () -> { postOffice.receivedPublishQos1(this, topic, username, messageID, msg); return null; }); case EXACTLY_ONCE: { final CompletableFuture<PostOffice.RouteResult> firstStepFuture = postOffice.routeCommand(clientId, () -> { bindedSession.receivedPublishQos2(messageID, msg); return null; }); return firstStepFuture.thenCompose(v -> postOffice.receivedPublishQos2(this, msg, username)); } default: LOG.error("Unknown QoS-Type:{}", qos); final CompletableFuture<Void> failed = new CompletableFuture<>(); failed.completeExceptionally(new Error("Unknown QoS-")); return failed; } } void sendPubRec(int messageID) { LOG.trace("sendPubRec invoked, messageID: {}", messageID); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBREC, false, AT_MOST_ONCE, false, 0); MqttPubAckMessage pubRecMessage = new MqttPubAckMessage(fixedHeader, from(messageID)); sendIfWritableElseDrop(pubRecMessage); } private void processPubRel(MqttMessage msg) { final int messageID = ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId(); this.postOffice.routeCommand(bindedSession.getClientID(), () -> { executePubRel(messageID); return null; }); } private void executePubRel(int messageID) { bindedSession.receivedPubRelQos2(messageID); sendPubCompMessage(messageID); } void sendPublish(MqttPublishMessage publishMsg) { final int packetId = publishMsg.variableHeader().packetId(); final String topicName = publishMsg.variableHeader().topicName(); final String clientId = getClientId(); MqttQoS qos = publishMsg.fixedHeader().qosLevel(); if (LOG.isTraceEnabled()) { LOG.trace("Sending PUBLISH({}) message. MessageId={}, topic={}, payload={}", qos, packetId, topicName, DebugUtils.payload2Str(publishMsg.payload())); } else { LOG.debug("Sending PUBLISH({}) message. MessageId={}, topic={}", qos, packetId, topicName); } sendIfWritableElseDrop(publishMsg); } void sendIfWritableElseDrop(MqttMessage msg) { if (LOG.isDebugEnabled()) { LOG.debug("OUT {}", msg.fixedHeader().messageType()); } if (channel.isWritable()) { // Sending to external, retain a duplicate. Just retain is not // enough, since the receiver must have full control. Object retainedDup = msg; if (msg instanceof ByteBufHolder) { retainedDup = ((ByteBufHolder) msg).retainedDuplicate(); } ChannelFuture channelFuture; if (brokerConfig.isImmediateBufferFlush()) { channelFuture = channel.writeAndFlush(retainedDup); } else { channelFuture = channel.write(retainedDup); } channelFuture.addListener(FIRE_EXCEPTION_ON_FAILURE); } } public void writabilityChanged() { if (channel.isWritable()) { LOG.debug("Channel is again writable"); bindedSession.writabilityChanged(); } } void sendPubAck(int messageID) { LOG.trace("sendPubAck for messageID: {}", messageID); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBACK, false, AT_MOST_ONCE, false, 0); MqttPubAckMessage pubAckMessage = new MqttPubAckMessage(fixedHeader, from(messageID)); sendIfWritableElseDrop(pubAckMessage); } private void sendPubCompMessage(int messageID) { LOG.trace("Sending PUBCOMP message messageId: {}", messageID); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP, false, AT_MOST_ONCE, false, 0); MqttMessage pubCompMessage = new MqttMessage(fixedHeader, from(messageID)); sendIfWritableElseDrop(pubCompMessage); } String getClientId() { return NettyUtils.clientID(channel); } String getUsername() { return NettyUtils.userName(channel); } public void sendPublishRetainedQos0(Topic topic, MqttQoS qos, ByteBuf payload) { MqttPublishMessage publishMsg = retainedPublish(topic.toString(), qos, payload); sendPublish(publishMsg); } public void sendPublishRetainedWithPacketId(Topic topic, MqttQoS qos, ByteBuf payload) { final int packetId = nextPacketId(); MqttPublishMessage publishMsg = retainedPublishWithMessageId(topic.toString(), qos, payload, packetId); sendPublish(publishMsg); } private static MqttPublishMessage retainedPublish(String topic, MqttQoS qos, ByteBuf message) { return retainedPublishWithMessageId(topic, qos, message, 0); } private static MqttPublishMessage retainedPublishWithMessageId(String topic, MqttQoS qos, ByteBuf message, int messageId) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, true, 0); MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId); return new MqttPublishMessage(fixedHeader, varHeader, message); } // TODO move this method in Session void sendPublishNotRetainedQos0(Topic topic, MqttQoS qos, ByteBuf payload) { MqttPublishMessage publishMsg = notRetainedPublish(topic.toString(), qos, payload); sendPublish(publishMsg); } static MqttPublishMessage notRetainedPublish(String topic, MqttQoS qos, ByteBuf message) { return notRetainedPublishWithMessageId(topic, qos, message, 0); } static MqttPublishMessage notRetainedPublishWithMessageId(String topic, MqttQoS qos, ByteBuf message, int messageId) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, false, 0); MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId); return new MqttPublishMessage(fixedHeader, varHeader, message); } public void resendNotAckedPublishes() { bindedSession.resendInflightNotAcked(); } int nextPacketId() { return lastPacketId.updateAndGet(v -> v == 65535 ? 1 : v + 1); } @Override public String toString() { return "MQTTConnection{channel=" + channel + ", connected=" + connected + '}'; } InetSocketAddress remoteAddress() { return (InetSocketAddress) channel.remoteAddress(); } public void readCompleted() { LOG.debug("readCompleted client CId: {}", getClientId()); if (getClientId() != null) { // TODO drain all messages in target's session in-flight message queue bindedSession.flushAllQueuedMessages(); } } public void flush() { channel.flush(); } public void bindSession(Session session) { bindedSession = session; } }
package org.intermine.xml.full; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.util.StringUtil; import org.intermine.util.XmlUtil; /** * Representation of an object * @author Andrew Varley * @author Kim Rutherford */ public class Item implements Comparable { private String identifier = ""; private String className = ""; private String implementations = ""; private Map<String, Attribute> attributes = new HashMap<String, Attribute>(); private Map<String, Reference> references = new HashMap(); private Map<String, ReferenceList> collections = new HashMap(); private Model model = null; private ClassDescriptor classDescriptor = null; private Set implementationClassDescriptors = null; /** * Construct an item. */ public Item() { } /** * Construct an item. * @see ItemFactory * @param model the Model used to type-check set methods; if null no type checking is done * @param identifier item identifier * @param className name of described class * @param implementations names of implemented classes */ public Item(Model model, String identifier, String className, String implementations) { this.identifier = identifier; this.className = className; this.implementations = implementations; setModel(model); } /** * Construct an item withno Model. The calls to the set methods won't be type checked unless * setModel() is called. * @see ItemFactory * @param identifier item identifier * @param className name of described class * @param implementations names of implemented classes */ public Item(String identifier, String className, String implementations) { this(null, identifier, className, implementations); } /** * Set the Model to use when checking calls to the other set methods * @param model the Model */ public void setModel(Model model) { this.model = model; implementationClassDescriptors = null; setClassDescriptor(className); } /** * Return the model that was passed to the constructor or set with setModel(). * @return the Model */ public Model getModel() { return model; } /** * Set the identifier of this item * @param identifier the identifier */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Get the identifier of this item * @return the identifier */ public String getIdentifier() { return identifier; } /** * Set the class of this item * @param className the class */ public void setClassName(String className) { if (className == null) { throw new IllegalArgumentException("className argument cannot be null"); } classDescriptor = getClassDescriptorByName(className); this.className = className; } /** * Get the class name of this item * @return the class name */ public String getClassName() { return className; } /** * Set the "implements" of this item * @param implementations the interfaces that this item implements */ public void setImplementations(String implementations) { if (implementations == null) { throw new IllegalArgumentException("implementations argument cannot be null"); } implementationClassDescriptors = null; checkImplementations(implementations); this.implementations = implementations; } /** * Get the interfaces implemented by this item * @return the implemented interfaces */ public String getImplementations() { return implementations; } /** * Add an attribute * @param attribute the Attribute to add */ public void addAttribute(Attribute attribute) { String name = attribute.getName(); if (!checkAttribute(name)) { throw new RuntimeException("class \"" + className + "\" has no \"" + name + "\" attribute"); } if (attribute.getValue() == null) { throw new RuntimeException("value cannot be null for attribute " + className + "." + name); } else { if (attribute.getValue().equals("")) { throw new RuntimeException("value cannot be an empty string for attribute " + className + "." + name); } } attributes.put(name, attribute); } /** * Remove a attribute of the specified name if it exists * @param attributeName name of the attribute to remove */ public void removeAttribute(String attributeName) { if (!checkAttribute(attributeName)) { throw new RuntimeException("class \"" + className + "\" has no \"" + attributeName + "\" attribute"); } attributes.remove(attributeName); } /** * Get all the attributes * @return all the attributes */ public Collection<Attribute> getAttributes() { return attributes.values(); } /** * Get a named attribute * @param attributeName the attribute name * @return the Attribute with the given name */ public Attribute getAttribute(String attributeName) { if (!checkAttribute(attributeName)) { throw new RuntimeException("class \"" + classDescriptor.getName() + "\" has no \"" + attributeName + "\" attribute"); } return attributes.get(attributeName); } /** * Return true if named attribute exists * @param attributeName the attribute name * @return true if the attribute exists */ public boolean hasAttribute(String attributeName) { //checkAttribute(attributeName); return attributes.containsKey(attributeName); } /** * Add a reference * @param reference the reference to add */ public void addReference(Reference reference) { checkReference(reference.getName()); references.put(reference.getName(), reference); } /** * Remove a reference of the specified name if it exists * @param referenceName name of the reference to remove */ public void removeReference(String referenceName) { checkReference(referenceName); references.remove(referenceName); } /** * Get all the references * @return all the references */ public Collection getReferences() { return references.values(); } /** * Get a named reference * @param referenceName the reference name * @return the Reference with the given name */ public Reference getReference(String referenceName) { checkReference(referenceName); return (Reference) references.get(referenceName); } /** * Return true if named reference exists * @param referenceName the reference name * @return true if the reference exists */ public boolean hasReference(String referenceName) { checkReference(referenceName); return references.containsKey(referenceName); } /** * Add a collection * @param collection the collection to add */ public void addCollection(ReferenceList collection) { checkCollection(collection.getName()); collections.put(collection.getName(), collection); } /** * Remove a collection of the specified name if it exists * @param collectionName name of the collection to remove */ public void removeCollection(String collectionName) { checkCollection(collectionName); collections.remove(collectionName); } /** * Get all the collections * @return all the collections */ public Collection getCollections() { return collections.values(); } /** * Return true if named collection exists * @param collectionName the collection name * @return true if the collection exists */ public boolean hasCollection(String collectionName) { checkCollection(collectionName); return collections.containsKey(collectionName); } /** * Get a named collection * @param collectionName the collection name * @return the Collection with the given name */ public ReferenceList getCollection(String collectionName) { checkCollection(collectionName); return (ReferenceList) collections.get(collectionName); } /** * Set a colletion. * @param collectionName collection name * @param refIds ids to reference */ public void setCollection(String collectionName, List<String> refIds) { addCollection(new ReferenceList(collectionName, refIds)); } /** * Add an attribute to this item * @param name the name of the attribute * @param value the value of the attribute - cannot be null or empty */ public void setAttribute(String name, String value) { if (value == null) { throw new RuntimeException("value cannot be null for attribute " + className + "." + name); } else { if (value.equals("")) { throw new RuntimeException("value cannot be an empty string for attribute " + className + "." + name); } } addAttribute(new Attribute(name, value)); } /** * Add an attribute to this item and set it to the empty string * @param name the name of the attribute */ public void setAttributeToEmptyString(String name) { attributes.put(name, new Attribute(name, "")); } /** * Add a reference to this item * @param name the name of the attribute * @param refId the value of the attribute */ public void setReference(String name, String refId) { if (refId.equals("")) { throw new RuntimeException("empty string used as ref_id for: " + name); } addReference(new Reference(name, refId)); } /** * Add a reference that points to a particular item. * @param name the name of the attribute * @param item the item to refer to */ public void setReference(String name, Item item) { addReference(new Reference(name, item.getIdentifier())); } /** * Add the identifier of the given Item to a collection * @param name the name of the collection * @param item the item whose identifier is to be added to the collection */ public void addToCollection(String name, Item item) { ReferenceList list = getCollection(name); if (list == null) { list = new ReferenceList(name); addCollection(list); } list.addRefId(item.getIdentifier()); } /** * Add a reference to a collection of this item * @param name the name of the collection * @param identifier the item to add to the collection */ public void addToCollection(String name, String identifier) { if (identifier.equals("")) { throw new RuntimeException("empty string added to collection for: " + name); } ReferenceList list = getCollection(name); if (list == null) { list = new ReferenceList(name); addCollection(list); } list.addRefId(identifier); } /** * Return true if the name parameter is an attribute of the class for this Item or if * the Model or the className of this Item haven't been set. * @param name the attribute name * @return true if the name is a valid attribute name */ public boolean checkAttribute(String name) { if (model == null || classDescriptor == null) { return true; } Iterator cdIter = getAllClassDescriptors().iterator(); while (cdIter.hasNext()) { ClassDescriptor cd = (ClassDescriptor) cdIter.next(); if (cd.getAttributeDescriptorByName(name, true) != null) { return true; } } return false; } /** * Throw a RuntimeException if the name parameter isn't an reference in the class set by * setClassName() in the Model set by setModel(). Returns immediately if the Model or the * className of this Item haven't been set. * @param name the reference name * */ protected void checkReference(String name) { if (model == null || classDescriptor == null) { return; } if (!canHaveReference(name)) { throw new RuntimeException("class \"" + classDescriptor.getName() + "\" has no \"" + name + "\" reference"); } } /** * Return true if and only if the argument names a possible reference for this Item. ie. the * ClassDescriptor for this Item contains a ReferenceDescriptor for this name. * @param name the field name * @return Return true if and only if this Item has a reference of the given name in the model */ public boolean canHaveReference(String name) { return classDescriptor.getReferenceDescriptorByName(name, true) != null; } /** * Return true if and only if the argument names a possible collection for this Item. ie. the * ClassDescriptor for this Item contains a CollectionDescriptor for this name. * @param name the field name * @return Return true if and only if this Item has a collection of the given name in the model */ public boolean canHaveCollection(String name) { return classDescriptor.getCollectionDescriptorByName(name, true) != null; } /** * Throw a RuntimeException if the name parameter isn't an collection in the class set by * setClassName() in the Model set by setModel(). Returns immediately if the Model or the * className of this Item haven't been set. * @param name the collection name */ protected void checkCollection(String name) { if (model == null || classDescriptor == null) { return; } if (classDescriptor.getCollectionDescriptorByName(name, true) == null) { throw new RuntimeException("class \"" + classDescriptor.getName() + "\" has no \"" + name + "\" collection"); } } /** * Throw RuntimeException if the given implementations don't match the model. * @param implementations the interfaces that this item implements */ protected void checkImplementations(String implementations) { if (model == null) { return; } getImplementClassDescriptors(implementations); } /** * Throw a RuntimeException if any of the named class isn't in the Model set by setModel(). * Returns null if the model isn't set or className is "". * @param className the class name * @return the ClassDescriptor for the given class */ protected ClassDescriptor getClassDescriptorByName(String className) { if (model == null) { return null; } if (className.equals("")) { return null; } String classNameNS = XmlUtil.getNamespaceFromURI(className); if (!model.getNameSpace().toString().equals(classNameNS)) { throw new RuntimeException("class \"" + className + "\" is not in the Model " + "(namespace doesn't match \"" + model.getNameSpace() + "\" != \"" + classNameNS + "\")"); } String fullClassName = model.getPackageName() + "." + XmlUtil.getFragmentFromURI(className); ClassDescriptor cd = model.getClassDescriptorByName(fullClassName); if (cd == null) { throw new IllegalArgumentException("class \"" + fullClassName + "\" is not in the Model"); } return cd; } /** * Set the classDescriptor attribute to be the ClassDescriptor for the given className in the * Model set by setModel(). Returns immediately if the Model hasn't been set or the className * parameter is "". * @param className the class name */ protected void setClassDescriptor(String className) { if (model != null && !className.equals("")) { String fullClassName = model.getPackageName() + "." + XmlUtil.getFragmentFromURI(className); classDescriptor = getClassDescriptorByName(fullClassName); } } /** * Return the ClassDescriptors of the class of this Item (as given by className) and all the * implementations. Call only if model, className and implementations are set. * @return all the ClassDescriptors for this Item */ protected Set getAllClassDescriptors() { Set cds = new HashSet(); Set implementationCds = getImplementClassDescriptors(implementations); if (implementationCds != null) { cds.addAll(implementationCds); } cds.add(classDescriptor); return cds; } /** * Returns the ClassDescriptors for the given implementations. Returns null if the Model hasn't * been set. Throw a RuntimeException if any of the classes named in the implementations * parameter aren't in the Model. * @param implementations the interfaces that this item implements * @return the ClassDescriptors for the given implementations. Returns null if the Model hasn't * been set */ protected Set getImplementClassDescriptors(String implementations) { if (implementations.length() == 0) { return null; } if (implementationClassDescriptors != null) { return implementationClassDescriptors; } Set cds = new HashSet(); String [] bits = StringUtil.split(implementations, " "); for (int i = 0; i < bits.length; i++) { ClassDescriptor cd = getClassDescriptorByName(bits[i]); cds.add(cd); } implementationClassDescriptors = cds; return implementationClassDescriptors; } /** * {@inheritDoc} */ public boolean equals(Object o) { if (o instanceof Item) { Item i = (Item) o; return identifier.equals(i.identifier) && className.equals(i.className) && implementations.equals(i.implementations) && attributes.equals(i.attributes) && references.equals(i.references) && collections.equals(i.collections); } return false; } /** * Compare items first by class, then by identifier, intended for creating * ordered output files. * {@inheritDoc} */ public int compareTo(Object o) { if (!(o instanceof Item)) { throw new RuntimeException("Attempt to compare an item to a " + o.getClass() + " (" + o.toString() + ")"); } Item i = (Item) o; int compValue = this.getClassName().compareTo(i.getClassName()); if (compValue == 0) { compValue = this.getIdentifier().compareTo(i.getIdentifier()); } return compValue; } /** * {@inheritDoc} */ public int hashCode() { return identifier.hashCode() + 3 * className.hashCode() + 5 * implementations.hashCode() + 7 * attributes.hashCode() + 11 * references.hashCode() + 13 * collections.hashCode(); } /** * {@inheritDoc} */ public String toString() { return XmlUtil.indentXmlSimple(FullRenderer.render(this)); } }
package org.intermine.task; import org.intermine.metadata.Model; import junit.framework.*; import java.sql.SQLException; import java.util.List; import java.util.ArrayList; import java.util.Properties; import java.io.InputStream; import org.intermine.metadata.Model; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.StoreDataTestCase; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreSummary; import org.intermine.objectstore.ObjectStoreFactory; /** * Tests for PrecomputeTask. * * @author Kim Rutherford */ public class PrecomputeTaskTest extends StoreDataTestCase { public PrecomputeTaskTest (String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); } public static void oneTimeSetUp() throws Exception { StoreDataTestCase.oneTimeSetUp(); } public void executeTest(String type) { } public static Test suite() { return buildSuite(PrecomputeTaskTest.class); } /** * Test that PrecomputeTask creates the */ public void testExecute() throws Exception { DummyPrecomputeTask task = new DummyPrecomputeTask(); task.setAlias("os.unittest"); task.setTestMode(Boolean.FALSE); task.setMinRows(new Integer(1)); Properties summaryProperties; String configFile = "objectstoresummary.config.properties"; InputStream is = PrecomputeTask.class.getClassLoader().getResourceAsStream(configFile); if (is == null) { throw new Exception("Cannot find " + configFile + " in the class path"); } summaryProperties = new Properties(); summaryProperties.load(is); ObjectStore os = ObjectStoreFactory.getObjectStore("os.unittest"); ObjectStoreSummary oss = new ObjectStoreSummary(os, summaryProperties); task.precomputeAll(os, oss); for ( int i = 0 ; i < task.queries.size () ; ++i ) { System.err.println (task.queries.get(i)); } assertEquals(118, task.queries.size()); String[] expectedQueries = new String[] { "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_)", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.vatNumber", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.salary", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.title", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.age", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.end", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.fullTime", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.salary AS a9_, a8_.title AS a10_, a8_.age AS a11_, a8_.end AS a12_, a8_.fullTime AS a13_, a8_.name AS a14_, a8_.id AS a15_, a8_.seniority AS a16_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.CEO AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.seniority", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.CEO AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.CEO AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_) ORDER BY a2_", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.CEO AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_) ORDER BY a3_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_)", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.vatNumber", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.age", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.end", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.fullTime", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.age AS a9_, a8_.end AS a10_, a8_.fullTime AS a11_, a8_.name AS a12_, a8_.id AS a13_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Employee AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.id", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_) ORDER BY a2_", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_) ORDER BY a3_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_)", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.vatNumber", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a5_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.title", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.age", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.end", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.fullTime", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_, a8_, a8_.title AS a9_, a8_.age AS a10_, a8_.end AS a11_, a8_.fullTime AS a12_, a8_.name AS a13_, a8_.id AS a14_, a8_.seniority AS a15_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_, org.intermine.model.testmodel.Manager AS a8_ WHERE (a1_.departments CONTAINS a5_ AND a5_.employees CONTAINS a8_) ORDER BY a8_.seniority", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Manager AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Manager AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_) ORDER BY a2_", "SELECT DISTINCT a1_, a2_, a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Manager AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_) ORDER BY a3_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a1_.vatNumber", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a5_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a5_.id", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE a1_.departments CONTAINS a2_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE a1_.departments CONTAINS a2_ ORDER BY a2_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a1_.vatNumber", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a5_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a5_.address", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a5_.id", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a2_ WHERE a1_.address CONTAINS a2_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a2_ WHERE a1_.address CONTAINS a2_ ORDER BY a2_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.salary", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.title", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.age", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.end", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.fullTime", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.name", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.id", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.seniority", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a2_ WHERE a1_.employees CONTAINS a2_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a2_ WHERE a1_.employees CONTAINS a2_ ORDER BY a2_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.age", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.end", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.fullTime", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.name", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.id", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a2_ WHERE a1_.employees CONTAINS a2_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a2_ WHERE a1_.employees CONTAINS a2_ ORDER BY a2_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_.name", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.title", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.age", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.end", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.fullTime", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.name", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.id", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a4_.seniority", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a2_ WHERE a1_.employees CONTAINS a2_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a2_ WHERE a1_.employees CONTAINS a2_ ORDER BY a2_", "SELECT DISTINCT a1_, a1_.id AS a2_, a3_, a3_.name AS a4_, a3_.id AS a5_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a3_ WHERE a1_.secretarys CONTAINS a3_", "SELECT DISTINCT a1_, a1_.id AS a2_, a3_, a3_.name AS a4_, a3_.id AS a5_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a3_ WHERE a1_.secretarys CONTAINS a3_ ORDER BY a1_.id", "SELECT DISTINCT a1_, a1_.id AS a2_, a3_, a3_.name AS a4_, a3_.id AS a5_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a3_ WHERE a1_.secretarys CONTAINS a3_ ORDER BY a3_", "SELECT DISTINCT a1_, a1_.id AS a2_, a3_, a3_.name AS a4_, a3_.id AS a5_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a3_ WHERE a1_.secretarys CONTAINS a3_ ORDER BY a3_.name", "SELECT DISTINCT a1_, a1_.id AS a2_, a3_, a3_.name AS a4_, a3_.id AS a5_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a3_ WHERE a1_.secretarys CONTAINS a3_ ORDER BY a3_.id", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a2_ WHERE a1_.secretarys CONTAINS a2_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a2_ WHERE a1_.secretarys CONTAINS a2_ ORDER BY a2_", "SELECT DISTINCT emp, add FROM org.intermine.model.testmodel.Employee AS emp, org.intermine.model.testmodel.Address AS add WHERE emp.address CONTAINS add", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a2_ WHERE a1_.employees CONTAINS a2_", }; for (int i = 0; i < expectedQueries.length; i++) { assertEquals(expectedQueries[i], "" + task.queries.get(i)); } } public void testQueries() { } class DummyPrecomputeTask extends PrecomputeTask { protected List queries = new ArrayList(); protected void precompute(ObjectStore os, Query query) { queries.add(query); } } }
package com.getirkit.irkit; import android.app.backup.BackupManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.WindowManager; import com.getirkit.irkit.net.IRAPICallback; import com.getirkit.irkit.net.IRAPIError; import com.getirkit.irkit.net.IRAPIResult; import com.getirkit.irkit.net.IRHTTPClient; import com.getirkit.irkit.net.IRInternetAPIService; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.math.BigInteger; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteOrder; import java.util.ArrayDeque; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import retrofit.RetrofitError; import retrofit.client.Response; /** * IRKit SDK * Main class for IRKit SDK. */ public class IRKit { public String TAG; public static final String SERVICE_TYPE = "_irkit._tcp.local."; public static final String PREF_KEY_BONJOUR_HOSTNAME = "debuginfo.bonjour.hostname"; public static final String PREF_KEY_BONJOUR_RESOLVED_AT = "debuginfo.bonjour.resolved_at"; private static final int SEND_SIGNAL_LOCAL_TIMEOUT_MS = 3000; /** * IRPeripheralIRPeripherals * IRPeripherals instance which holds existing IRPeripheral instances. */ public IRPeripherals peripherals; /** * IRSignalIRSignals * IRSignals instance which holds existing IRSignal instances. */ public IRSignals signals; private Context context; private IRKitEventListener irkitEventListener; private IRHTTPClient httpClient; private boolean isDataLoaded = false; private WifiManager wifiManager; private ScanResultReceiver scanResultReceiver; private WifiEnableEventReceiver wifiEnableEventReceiver; private boolean isDiscovering = false; private LinkedList<Boolean> discoveryQueue; private boolean isProcessingBonjour = false; private boolean isInitialized = false; private IRKitSetupManager setupManager; private NetworkStateChangeReceiver networkStateChangeReceiver; // For JmDNS private WifiManager.MulticastLock multicastLock; private JmDNS jmdns; private BonjourServiceListener bonjourServiceListener; // singleton private static IRKit ourInstance = new IRKit(); /** * singleton * Returns a singleton instance. * * @return */ public static IRKit sharedInstance() { return ourInstance; } public IRHTTPClient getHTTPClient() { return httpClient; } private ArrayDeque<SendSignalItem> sendSignalQueue = new ArrayDeque<>(); private IRKit() { httpClient = IRHTTPClient.sharedInstance(); TAG = IRKit.class.getSimpleName() + ":" + this.hashCode(); } /** * SharedPreferences * Load data from SharedPreferences. */ public void loadData() { if (!isDataLoaded) { peripherals = new IRPeripherals(); peripherals.load(); signals = new IRSignals(); signals.load(); signals.updateImageResourceIdFromName(context.getResources()); if (!signals.checkIdOverlap()) { Log.e(TAG, "there are some signals that share the same id"); // TODO: reassign ids? } signals.removeInvalidSignals(); isDataLoaded = true; } } /** * * Cancel IRKit device setup. Do nothing if setup is not being performed. */ public void cancelIRKitSetup() { if (setupManager != null) { setupManager.cancel(); setupManager = null; } stopWifiStateListener(); stopWifiScan(); getHTTPClient().cancelPostDoor(); httpClient.clearDeviceKeyCache(); } /** * <p class="ja"> * IRKitlistener * </p> * * <p class="en"> * Begin IRKit device setup. If a setup is already started, it only updates the listener. * </p> * * @param apiKey apikey * @param connectDestination IRKitWi-Fi Wi-Fi which will be connected by IRKit. * @param irkitWifiPassword IRKit Wi-Fi IRKit Wi-Fi password. * @param listener IRKitConnectWifiListener instance */ public void setupIRKit(String apiKey, IRWifiInfo connectDestination, String irkitWifiPassword, IRKitConnectWifiListener listener) { if (setupManager != null && setupManager.isActive()) { // There is an active setup setupManager.setIrKitConnectWifiListener(listener); return; } // cancelIRKitSetup(); // TODO: Do we need this? setupManager = new IRKitSetupManager(context); setupManager.setIrKitConnectWifiListener(listener); setupManager.start(apiKey, connectDestination, irkitWifiPassword); } /** * Wi-FiWi-FiBonjour * Wi-FiBonjour * Watch Wi-Fi state change. When Wi-Fi is enabled, Bonjour discovery * will automatically start. When Wi-Fi is disabled, Bonjour discovery * will automatically stop. */ public void registerWifiStateChangeListener() { if (networkStateChangeReceiver == null) { networkStateChangeReceiver = new NetworkStateChangeReceiver(); } context.getApplicationContext().registerReceiver(networkStateChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } /** * Wi-Fi * Unwatch Wi-Fi state change. */ public void unregisterWifiStateChangeListener() { if (networkStateChangeReceiver != null) { context.getApplicationContext().unregisterReceiver(networkStateChangeReceiver); networkStateChangeReceiver = null; } } /** * mDNSIRKit * Start IRKit discovery by mDNS. */ public void startServiceDiscovery() { if (!isWifiConnected()) { // Wi-Fi is not connected. We don't initiate service discovery. return; } synchronized (this) { if (isDiscovering) { return; } isDiscovering = true; } startBonjourDiscovery(); } /** * mDNSIRKit * Stop IRKit discovery. */ public void stopServiceDiscovery() { synchronized (this) { if (!isDiscovering) { return; } isDiscovering = false; } stopBonjourDiscovery(); } /** * * Return whether the initialization has been done. * * @return true True if initialization has been done. */ public boolean isInitialized() { return isInitialized; } /** * peripheralssignals * Add example data to peripherals and signals if they are empty. */ public void addExampleDataIfEmpty() { if (peripherals.isEmpty()) { addExamplePeripheral(); } if (signals.isEmpty()) { addExampleSignal(); } } /** * peripherals * Add example data to peripherals. */ public void addExamplePeripheral() { IRPeripheral peripheral = new IRPeripheral(); peripheral.setHostname("IRKit1234"); peripheral.setCustomizedName("IRKit1234"); peripheral.setFoundDate(new Date()); peripheral.setDeviceId("testdeviceid"); peripheral.setModelName("IRKit"); peripheral.setFirmwareVersion("2.0.2.0.g838e0ea"); peripherals.add(peripheral); peripherals.save(); } /** * signals * Add example data to signals. */ public void addExampleSignal() { // debug (add signal) IRSignal testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); // testSignal.setName("Warm"); testSignal.setName(""); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_aircon, context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(0); signals.add(testSignal); testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); // testSignal.setName("Cool"); testSignal.setName(""); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_aircon, context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(1); signals.add(testSignal); testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); testSignal.setName("\uD83D\uDCA4"); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_aircon, context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(2); signals.add(testSignal); testSignal = new IRSignal(); testSignal.setData(new int[]{ 18031, 8755, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 1190, 1190, 3341, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 3341, 1190, 65535, 0, 9379, 18031, 4400, 1190 }); testSignal.setFormat("raw"); testSignal.setFrequency(38.0f); // testSignal.setName("\uD83C\uDFE0"); // house building // testSignal.setName("Living Room"); testSignal.setName(""); testSignal.setId(signals.getNewId()); testSignal.setImageResourceId(R.drawable.btn_icon_256_light, context.getResources()); testSignal.setDeviceId("testdeviceid"); testSignal.setViewPosition(3); signals.add(testSignal); signals.save(); } /** * <p class="ja"> * contextIRKit * </p> * * <p class="en"> * Set context, and initialize IRKit instance if it is not initialized yet. * </p> * * @param context Context object */ public void init(Context context) { setContext(context); if (!isInitialized) { isInitialized = true; discoveryQueue = new LinkedList<>(); loadData(); } } /** * SharedPreferences * Store data in SharedPreferences. * * @param key Key * @param value Value */ public void savePreference(String key, String value) { SharedPreferences sharedPrefs = context.getSharedPreferences( context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE ); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString(key, value); editor.apply(); this.requestBackup(); } /** * SharedPreferences * Fetch data from SharedPreferences. * * @param key Key * @return String, or null if the specified key does not exist. */ public String getPreference(String key) { SharedPreferences sharedPrefs = context.getSharedPreferences( context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE ); return sharedPrefs.getString(key, null); } /** * Android * Request backup to Android backup service. */ public void requestBackup() { BackupManager bm = new BackupManager(context); bm.dataChanged(); } /** * IRKit SDKapikey * Returns the current IRKit apikey. * * @return apikey */ public String getIRKitAPIKey() { if (context == null) { throw new IllegalStateException("Context is not set. Have you called IRKit.sharedInstance().init(context)?"); } // Fetch IRKit api key in whatever way you want ApplicationInfo ai = null; try { ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); Log.e(TAG, "Failed to get apikey. Have you add com.getirkit.IRKIT_API_KEY to AndroidManifest.xml?"); return null; } Bundle metaData = ai.metaData; if (metaData == null) { Log.e(TAG, "Failed to get apikey. Have you add com.getirkit.IRKIT_API_KEY to AndroidManifest.xml?"); return null; } return metaData.getString("com.getirkit.IRKIT_API_KEY"); } /** * clientkeyapikeyapikeynull * AndroidManifest.xmlapikey * If we have not received clientkey yet, fetch it using apikey. * If apikey is null, it is read from AndroidManifest.xml. */ public void registerClient(String apikey) { if (apikey == null) { apikey = getIRKitAPIKey(); } if (apikey != null) { IRHTTPClient.sharedInstance().ensureRegisteredAndCall(apikey, new IRAPICallback<IRInternetAPIService.PostClientsResponse>() { @Override public void success(IRInternetAPIService.PostClientsResponse postClientsResponse, Response response) { // Client has been registered or already registered } @Override public void failure(RetrofitError error) { Log.e(TAG, "Failed to register client: " + error.getMessage()); } }); } } /** * clientkey * Fetch clientkey if we have not received it yet. */ public void registerClient() { registerClient(null); } /** * networkIdAndroid * Remove network auth data that matches networkId from Android. * * @param networkId Network ID used by WifiManager */ public void removeWifiConfiguration(int networkId) { if (networkId != -1) { fetchWifiManager(); wifiManager.removeNetwork(networkId); } } /** * Wi-Fi * Disconnect from current Wi-Fi network. */ public void disconnectFromCurrentWifi() { fetchWifiManager(); wifiManager.disconnect(); } /** * Wi-FiWifiConfiguration * Return the WifiConfiguration for the current Wi-Fi. * * @return WifiConfiguration */ public WifiConfiguration getCurrentWifiConfiguration() { fetchWifiManager(); WifiInfo currentWifiInfo = getCurrentWifiInfo(); if (currentWifiInfo == null) { return null; } List<WifiConfiguration> networks = wifiManager.getConfiguredNetworks(); if (networks == null) { return null; } for (WifiConfiguration config : networks) { if (config.networkId == currentWifiInfo.getNetworkId()) { return config; } } return null; } /** * Wi-FiWifiInfo * Return the WifiInfo instance of current Wi-Fi. * * @return WifiInfo */ public WifiInfo getCurrentWifiInfo() { if (context == null) { Log.e(TAG, "getCurrentWifiInfo: context is null"); return null; } ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.getConnectionInfo(); // returns WifiInfo instance } else { // No internet connection WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); return wifiManager.getConnectionInfo(); // returns WifiInfo instance } } /** * WifiManager * Fetch WifiManager instance. */ private void fetchWifiManager() { if (wifiManager == null) { wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); } } /** * Wi-Fi * Stop watching for Wi-Fi state change. */ public void stopWifiStateListener() { if (wifiEnableEventReceiver != null) { wifiEnableEventReceiver.stop(); context.getApplicationContext().unregisterReceiver(wifiEnableEventReceiver); wifiEnableEventReceiver = null; } } /** * Wi-Fi * Enable Wi-Fi. * * @param set Wi-Fitrue To enable Wi-Fi, true. */ public void setWifiEnabled(boolean set) { fetchWifiManager(); wifiManager.setWifiEnabled(set); } /** * Wi-Fi * Return whether Wi-Fi is enabled. * * @return Wi-Fitrue True if Wi-Fi is enabled. */ public boolean isWifiEnabled() { fetchWifiManager(); return wifiManager.isWifiEnabled(); } /** * IRKit Wi-Fi * Scan for IRKit Wi-Fi. * * @param listener Listener to be notified. */ public void scanIRKitWifi(final IRKitWifiScanResultListener listener) { fetchWifiManager(); if (scanResultReceiver == null) { scanResultReceiver = new ScanResultReceiver(wifiManager); scanResultReceiver.setIRKitWifiScanResultListener(new IRKitWifiScanResultListener() { @Override public void onIRKitWifiFound(ScanResult result) { stopWifiScan(); listener.onIRKitWifiFound(result); } }); context.getApplicationContext().registerReceiver(scanResultReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); } if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); wifiEnableEventReceiver = new WifiEnableEventReceiver(); wifiEnableEventReceiver.setListener(new WifiEnableEventReceiver.WifiEnableEventReceiverListener() { @Override public void onWifiEnabled() { stopWifiStateListener(); wifiManager.startScan(); final Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { if (scanResultReceiver == null) { // cancel timer t.cancel(); } else { // perform another scan wifiManager.startScan(); } } }, 10000, 10000); } }); context.getApplicationContext().registerReceiver(wifiEnableEventReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)); } else { wifiManager.startScan(); } } /** * Wi-Fi * Listener to be notified Wi-Fi state changes. */ public interface WifiConnectionChangeListener { /** * Wi-Fi * Called when Android is connected to target Wi-Fi. * * @param wifiInfo WifiInfo object * @param networkInfo NetworkInfo object */ public void onTargetWifiConnected(WifiInfo wifiInfo, NetworkInfo networkInfo); /** * Wi-Fi * Called when error occurred while connecting to the Wi-Fi. * * @param reason Error message. */ public void onError(String reason); /** * Wi-Fi * Called when the attempt to connect to the Wi-Fi has timed out. */ public void onTimeout(); } public interface IRKitWifiScanResultListener { public void onIRKitWifiFound(ScanResult result); } /** * Wi-Fi * Stop Wi-Fi scan. */ public void stopWifiScan() { if (scanResultReceiver != null) { scanResultReceiver.stopScan(); context.getApplicationContext().unregisterReceiver(scanResultReceiver); scanResultReceiver = null; } } /** * AndroidIRKit Wi-Fi * Remove configured networks that are IRKit Wi-Fi from Android. */ public void clearIRKitWifiConfigurations() { fetchWifiManager(); List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) { if (IRWifiInfo.isIRKitWifi(config)) { wifiManager.removeNetwork(config.networkId); } } } /** * ssidWifiConfiguration * Return WifiConfiguration that matches the ssid. * * @param ssid SSID * @return WifiConfiguration */ public WifiConfiguration getWifiConfigurationBySSID(String ssid) { List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) { if (config.SSID.equals(ssid)) { return config; } } return null; } /** * Wi-FiIRKit Wi-FiWi-Fi * Connect to home Wi-Fi (Wi-Fi that is not an IRKit Wi-Fi). * * @param wifiConfig WifiConfiguration WifiConfiguration to use. * @param listener WifiConnectionChangeListener */ public void connectToNormalWifi(WifiConfiguration wifiConfig, final WifiConnectionChangeListener listener) { fetchWifiManager(); final WifiConnectionChangeReceiver wifiConnectionChangeReceiver = new WifiConnectionChangeReceiver(wifiManager, wifiConfig); wifiConnectionChangeReceiver.setWifiConnectionChangeListener(new WifiConnectionChangeListener() { @Override public void onTargetWifiConnected(WifiInfo wifiInfo, NetworkInfo networkInfo) { wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onTargetWifiConnected(wifiInfo, networkInfo); } @Override public void onError(String reason) { Log.e(TAG, "connectToNormalWifi error: " + reason); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onError(reason); } @Override public void onTimeout() { Log.e(TAG, "connectToNormalWifi timeout"); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onTimeout(); } }); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); context.getApplicationContext().registerReceiver(wifiConnectionChangeReceiver, intentFilter); wifiManager.enableNetwork(wifiConfig.networkId, true); } /** * IRKit Wi-Fi * Connect to IRKit Wi-Fi. * * @param irWifiInfo IRKit Wi-Fi IRKit Wi-Fi info. * @param listener Listener to be notified state changes. * @return IRKit Wi-FiNetwork ID Network ID of IRKit Wi-Fi. */ public int connectToIRKitWifi(IRWifiInfo irWifiInfo, final WifiConnectionChangeListener listener) { final String irkitSSID = "\"" + irWifiInfo.getSSID() + "\""; WifiConfiguration wifiConfig = getWifiConfigurationBySSID(irkitSSID); int irkitWifiNetworkId; if (wifiConfig != null) { // Update existing IRKit Wi-Fi configuration wifiConfig.preSharedKey = "\"" + irWifiInfo.getPassword() + "\""; irkitWifiNetworkId = wifiManager.updateNetwork(wifiConfig); if (irkitWifiNetworkId == -1) { Log.e(TAG, "Failed to update network configuration"); listener.onError("Failed to update network configuration"); return irkitWifiNetworkId; } } else { // Add IRKit Wi-Fi configuration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = irkitSSID; wifiConfig.preSharedKey = "\"" + irWifiInfo.getPassword() + "\""; irkitWifiNetworkId = wifiManager.addNetwork(wifiConfig); if (irkitWifiNetworkId == -1) { Log.e(TAG, "Failed to add network configuration"); listener.onError("Failed to add network configuration"); return irkitWifiNetworkId; } } long irkitWifiConnectionTimeout = 30000; fetchWifiManager(); final WifiConnectionChangeReceiver wifiConnectionChangeReceiver = new WifiConnectionChangeReceiver( wifiManager, wifiConfig, WifiConnectionChangeReceiver.FLAG_FULL_MATCH, irkitWifiConnectionTimeout); wifiConnectionChangeReceiver.setWifiConnectionChangeListener(new WifiConnectionChangeListener() { @Override public void onTargetWifiConnected(WifiInfo wifiInfo, NetworkInfo networkInfo) { wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); getHTTPClient().setDeviceAPIEndpoint(IRHTTPClient.DEVICE_API_ENDPOINT_IRKITWIFI); listener.onTargetWifiConnected(wifiInfo, networkInfo); } @Override public void onError(String reason) { Log.e(TAG, "connectToIRKitWifi error: " + reason); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onError(reason); } @Override public void onTimeout() { Log.e(TAG, "connectToIRKitWifi timeout"); wifiConnectionChangeReceiver.cancel(); context.getApplicationContext().unregisterReceiver(wifiConnectionChangeReceiver); listener.onTimeout(); } }); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); context.getApplicationContext().registerReceiver(wifiConnectionChangeReceiver, intentFilter); if (irkitWifiNetworkId != -1) { if (!wifiManager.enableNetwork(irkitWifiNetworkId, true)) { Log.e(TAG, "enableNetwork failed"); } } else { Log.e(TAG, "Invalid network id: " + irkitWifiNetworkId); } return irkitWifiNetworkId; } /** * JSON * Return JSON string that contains debug info. * * @return JSON string */ public String getDebugInfo() { WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(metrics); try { JSONObject debugInfo = new JSONObject(); JSONObject os = new JSONObject(); os.put("manufacturer", Build.MANUFACTURER); os.put("model", Build.MODEL); os.put("version", Build.VERSION.RELEASE); os.put("sdk_int", Build.VERSION.SDK_INT); os.put("fingerprint", Build.FINGERPRINT); // BRAND/PRODUCT/DEVICE:VERSION.RELEASE/ID/VERSION.INCREMENTAL:TYPE/TAGS JSONObject screen = new JSONObject(); screen.put("width", metrics.widthPixels); screen.put("height", metrics.heightPixels); os.put("screen", screen); debugInfo.put("system", os); debugInfo.put("peripherals", peripherals.toJSONArray()); JSONObject bonjour = new JSONObject(); bonjour.put("hostname", getPreference(PREF_KEY_BONJOUR_HOSTNAME)); bonjour.put("resolved_at", getPreference(PREF_KEY_BONJOUR_RESOLVED_AT)); debugInfo.put("bonjour", bonjour); debugInfo.put("version", BuildConfig.VERSION_NAME); debugInfo.put("platform", "android"); return debugInfo.toString(); } catch (JSONException e) { e.printStackTrace(); return null; } // String osCodename = Build.VERSION.CODENAME; // String osIncremental = Build.VERSION.INCREMENTAL; // String osRelease = Build.VERSION.RELEASE; // int sdkVersion = Build.VERSION.SDK_INT; // Log.d(TAG, "VERSION.CODENAME: " + osCodename); // Log.d(TAG, "VERSION.INCREMENTAL: " + osIncremental); // Log.d(TAG, "VERSION.RELEASE: " + osRelease); // Log.d(TAG, "VERSION.SDK_INT: " + sdkVersion); // String deviceManufacturer = Build.MANUFACTURER; // String deviceModel = Build.MODEL; // Log.d(TAG, "MANUFACTURER: " + deviceManufacturer); // Log.d(TAG, "MODEL: " + deviceModel); // String buildId = Build.DISPLAY; // Log.d(TAG, "DISPLAY (build ID): " + buildId); // Log.d(TAG, "FINGERPRINT: " + Build.FINGERPRINT); // Log.d(TAG, "HARDWARE: " + Build.HARDWARE); // Log.d(TAG, "ID (changelist number or label): " + Build.ID); // Log.d(TAG, "PRODUCT: " + Build.PRODUCT); // Log.d(TAG, "SERIAL: " + Build.SERIAL); // Log.d(TAG, "TAGS: " + Build.TAGS); // Log.d(TAG, "TYPE: " + Build.TYPE); // Log.d(TAG, "DEVICE: " + Build.DEVICE); // Log.d(TAG, "BRAND: " + Build.BRAND); // Log.d(TAG, "BOOTLOADER: " + Build.BOOTLOADER); // Log.d(TAG, "BOARD: " + Build.BOARD); } /** * Androidregdomain * Return regdomain for the default locale of this Android. * * @return regdomain */ public static int getRegDomainForDefaultLocale() { return getRegDomainForLocale(Locale.getDefault()); } /** * localeregdomain * Return regdomain for the locale. * * @param locale Locale * @return regdomain */ public static int getRegDomainForLocale(Locale locale) { String countryCode = locale.getCountry(); int regdomain; String fccPattern = "^(?:CA|MX|US|AU|HK|IN|MY|NZ|PH|TW|RU|AR|BR|CL|CO|CR|DO|DM|EC|PA|PY|PE|PR|VE)$"; if (countryCode.equals("JP")) { regdomain = 2; // TELEC } else if (countryCode.matches(fccPattern)) { regdomain = 0; // FCC } else { regdomain = 1; // ETSI } return regdomain; } /** * Wi-FiIPv4 * Return IPv4 address of Wi-Fi interface. * * @return Wi-FiIPv4 IPv4 address of Wi-Fi interface. */ public InetAddress getWifiIPv4Address() { fetchWifiManager(); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); // Convert little-endian to big-endian if needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); } byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(ipByteArray); } catch (UnknownHostException ex) { Log.e(TAG, "Failed to get Wi-Fi IP address"); } return inetAddress; } /** * JmDNS * Listener for JmDNS. */ class BonjourServiceListener implements ServiceListener { /** * * Called when a service is added. * * @param serviceEvent ServiceEvent */ @Override public void serviceAdded(ServiceEvent serviceEvent) { jmdns.requestServiceInfo(serviceEvent.getType(), serviceEvent.getName()); } /** * * Called when a service become unavailable. * * @param serviceEvent ServiceEvent */ @Override public void serviceRemoved(ServiceEvent serviceEvent) { String serviceName = serviceEvent.getName(); IRPeripheral peripheral = peripherals.getPeripheral(serviceName); if (peripheral != null) { peripheral.lostLocalAddress(); } } /** * ServiceInfo * Called when a service is resolved and ServiceInfo become available. * * @param serviceEvent ServiceEvent */ @Override public void serviceResolved(ServiceEvent serviceEvent) { ServiceInfo serviceInfo = serviceEvent.getInfo(); if (serviceInfo == null) { Log.e(TAG, "serviceResolved: service info is null"); return; } Inet4Address[] addresses = serviceInfo.getInet4Addresses(); if (addresses.length == 0) { Log.e(TAG, "serviceResolved: no address"); return; } Inet4Address host = addresses[0]; int port = serviceInfo.getPort(); String serviceName = serviceEvent.getName(); // Log.d(TAG, "resolve success: name=" + serviceName + " host=" + host + " port=" + port); savePreference(PREF_KEY_BONJOUR_HOSTNAME, serviceEvent.getInfo().getQualifiedName()); savePreference(PREF_KEY_BONJOUR_RESOLVED_AT, String.valueOf(new Date().getTime() / 1000)); IRPeripheral peripheral = peripherals.getPeripheral(serviceName); if (peripheral == null) { // Found new IRKit peripheral = peripherals.addPeripheral(serviceName); if (irkitEventListener != null) { irkitEventListener.onNewIRKitFound(peripheral); } } else { if (irkitEventListener != null) { irkitEventListener.onExistingIRKitFound(peripheral); } } peripheral.setHost(host); peripheral.setPort(port); final IRPeripheral p = peripheral; if (!peripheral.hasDeviceId()) { // Wait 1000 ms to settle before sending a request. // We can't use Handler nor AsyncTask because we aren't on the UI thread. Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { p.fetchDeviceId(); } }, 1000); } else { // Retrieve the model info every time as it may change. // Wait 1000 ms to settle before sending a request. // We can't use Handler nor AsyncTask because we aren't on the UI thread. Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { p.fetchModelInfo(); } }, 1000); } } } private void pushDiscoveryQueue(boolean startDiscovery) { int originalSize; synchronized (discoveryQueue) { originalSize = discoveryQueue.size(); while (discoveryQueue.size() >= 1) { boolean set = discoveryQueue.peekLast(); if (set == startDiscovery) { return; } else { if (discoveryQueue.size() >= 2) { discoveryQueue.removeLast(); continue; } } break; } discoveryQueue.add(startDiscovery); } if (originalSize == 0 && !isProcessingBonjour) { nextDiscoveryQueue(); } } private void nextDiscoveryQueue() { boolean startDiscovery; synchronized (discoveryQueue) { if (discoveryQueue.isEmpty()) { return; } startDiscovery = discoveryQueue.pop(); } if (startDiscovery) { _startBonjourDiscovery(); } else { _stopBonjourDiscovery(); } } private void _startBonjourDiscovery() { if (isProcessingBonjour) { Log.e(TAG, "isProcessingBonjour is true"); return; } isProcessingBonjour = true; // Do network tasks in background. We can't use Handler here. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { fetchWifiManager(); WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); multicastLock = wifi.createMulticastLock(getClass().getName()); multicastLock.setReferenceCounted(true); multicastLock.acquire(); InetAddress deviceIPAddress = getWifiIPv4Address(); try { // Do not use default constructor i.e. JmDNS.create() jmdns = JmDNS.create(deviceIPAddress); } catch (IOException e) { e.printStackTrace(); } if (jmdns != null) { // Started zeroconf probe bonjourServiceListener = new BonjourServiceListener(); jmdns.addServiceListener(SERVICE_TYPE, bonjourServiceListener); } isProcessingBonjour = false; nextDiscoveryQueue(); return null; } }.execute(); } /** * mDNS * Start mDNS discovery. */ public void startBonjourDiscovery() { pushDiscoveryQueue(true); } /** * mDNS * Stop mDNS discovery. */ public void stopBonjourDiscovery() { pushDiscoveryQueue(false); } private void _stopBonjourDiscovery() { if (isProcessingBonjour) { Log.e(TAG, "isProcessingBonjour is true"); return; } isProcessingBonjour = true; // Do network tasks in another thread new Thread(new Runnable() { @Override public void run() { if (jmdns != null) { if (bonjourServiceListener != null) { jmdns.removeServiceListener(SERVICE_TYPE, bonjourServiceListener); bonjourServiceListener = null; } try { jmdns.close(); } catch (IOException e) { e.printStackTrace(); } jmdns = null; } if (multicastLock != null) { multicastLock.release(); multicastLock = null; } // Stopped zeroconf probe isProcessingBonjour = false; nextDiscoveryQueue(); } }).start(); } /** * <p class="ja"> * IRKitIRKitDevice HTTP API * Device HTTP APIInternet HTTP APIsendSignal() * IRKit1 * </p> * * <p class="en"> * Send signal via IRKit device. When sendSignal() is called multiple times in a short period * of time, it will be sent one by one to prevent IRKit device panic. * NOTE: IRKit panics when received parallel requests from local network. * </p> * * @param signal IR signal to be sent. * @param callback Callback for receiving the result. */ public void sendSignal(IRSignal signal, IRAPIResult callback) { synchronized (sendSignalQueue) { sendSignalQueue.add(new SendSignalItem(signal, callback)); if (sendSignalQueue.size() == 1) { // Do it now _sendSignal(signal, callback); } } } private void consumeNextSendSignal() { synchronized (sendSignalQueue) { sendSignalQueue.removeFirst(); SendSignalItem sendSignalItem = sendSignalQueue.peek(); if (sendSignalItem != null) { // Consume the next signal _sendSignal(sendSignalItem.signal, sendSignalItem.callback); } } } private void _sendSignal(final IRSignal signal, final IRAPIResult callback) { String deviceId = signal.getDeviceId(); if (deviceId == null) { // This shouldn't happen under normal circumstances Log.e(TAG, "sendSignal: deviceId is null"); if (callback != null) { callback.onError(new IRAPIError("deviceId is null")); } consumeNextSendSignal(); return; } final IRPeripheral peripheral = peripherals.getPeripheralByDeviceId(deviceId); // If a peripheral is registered twice, its deviceId is overwritten. // But we still try to send those signals over Internet API. final IRAPICallback<IRInternetAPIService.PostMessagesResponse> internetAPICallback = new IRAPICallback<IRInternetAPIService.PostMessagesResponse>() { @Override public void success(IRInternetAPIService.PostMessagesResponse postMessagesResponse, Response response) { if (callback != null) { callback.onSuccess(); } consumeNextSendSignal(); } @Override public void failure(RetrofitError error) { if (callback != null) { callback.onError(new IRAPIError(error.getLocalizedMessage())); } consumeNextSendSignal(); } }; if ( peripheral != null && peripheral.isLocalAddressResolved() ) { httpClient.setDeviceAPIEndpoint(peripheral.getDeviceAPIEndpoint()); httpClient.sendSignalOverLocalNetwork(signal, new IRAPIResult() { @Override public void onSuccess() { if (callback != null) { callback.onSuccess(); } consumeNextSendSignal(); } @Override public void onError(IRAPIError error) { // Try to send signal over Internet httpClient.sendSignalOverInternet(signal, internetAPICallback); } @Override public void onTimeout() { peripheral.lostLocalAddress(); // Try to send signal over Internet httpClient.sendSignalOverInternet(signal, internetAPICallback); } }, SEND_SIGNAL_LOCAL_TIMEOUT_MS); } else { // Local address isn't resolved httpClient.sendSignalOverInternet(signal, internetAPICallback); } } /** * Wi-Fi * Return whether Android is connected to Wi-Fi. * * @return Wi-Fitrue True if Android is connected to Wi-Fi. */ public boolean isWifiConnected() { ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return mWifi.isConnected(); } // Getters and setters /** * irkitEventListener * Return irkitEventListener. * * @return irkitEventListener */ public IRKitEventListener getIRKitEventListener() { return irkitEventListener; } /** * IRKitEventListenernull * Set an IRKitEventListener to this instance. When null is passed, listener will be removed. * * @param listener IRKitEventListenernull * IRKitEventListener instance, or null to remove the listener. */ public void setIRKitEventListener(IRKitEventListener listener) { this.irkitEventListener = listener; } /** * Context * Set the context. * * @param c Context object */ public void setContext(Context c) { context = c; if (!httpClient.hasClientKey()) { httpClient.setClientKey(this.getPreference("clientkey")); } } /** * Context * Return the context. * * @return Context object */ public Context getContext() { return context; } /** * * Return whether the data has been loaded. * * @return true True if the data has been loaded. */ public boolean isDataLoaded() { return isDataLoaded; } // Interfaces /** * IRKit * Listener to be notified the setup status of IRKit device. */ public interface IRKitConnectWifiListener { /** * * Called when the setup status has changed. * * @param status Setup status. */ public void onStatus(String status); /** * * Called when the setup has failed. * * @param message Error message. */ public void onError(String message); /** * * Called when the setup has been completed. */ public void onComplete(); } // Inner classes private static class SendSignalItem { public IRSignal signal; public IRAPIResult callback; public SendSignalItem(IRSignal signal, IRAPIResult callback) { this.signal = signal; this.callback = callback; } } private static class NetworkStateChangeReceiver extends BroadcastReceiver { public static final String TAG = NetworkStateChangeReceiver.class.getName(); /** * Called when connectivity has been changed * * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = conMan.getActiveNetworkInfo(); IRKit irkit = IRKit.sharedInstance(); if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) { // Wi-Fi connection is available irkit.startServiceDiscovery(); } else { // No Wi-Fi connection irkit.stopServiceDiscovery(); } } } /** * Wi-Fi * Receiver for Wi-Fi state changes. */ private static class WifiConnectionChangeReceiver extends BroadcastReceiver { public static final String TAG = WifiConnectionChangeReceiver.class.getSimpleName(); public static final int FLAG_FULL_MATCH = 1; public static final int FLAG_STARTS_WITH = 2; private WifiConnectionChangeListener wifiConnectionChangeListener; private String targetSSID; private int flag; private WifiConfiguration targetWifiConfiguration; private String lastSeenSSID; private long startTime; private static final int ERROR_TIME_THRESHOLD = 3000; // milliseconds private boolean isFinished = false; private int authFailedCount = 0; private WifiManager wifiManager; private boolean isCanceled = false; private Handler timeoutHandler; private Runnable timeoutRunnable; public WifiConnectionChangeReceiver(WifiManager wifiManager, WifiConfiguration wifiConfig, int flag, long timeoutMs) { super(); this.wifiManager = wifiManager; targetWifiConfiguration = wifiConfig; targetSSID = targetWifiConfiguration.SSID; this.flag = flag; startTime = System.currentTimeMillis(); if (timeoutMs != 0) { timeoutHandler = new Handler(); timeoutRunnable = new Runnable() { @Override public void run() { synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onTimeout(); } } timeoutRunnable = null; timeoutHandler = null; } } }; timeoutHandler.postDelayed(timeoutRunnable, timeoutMs); } } public WifiConnectionChangeReceiver(WifiManager wifiManager, WifiConfiguration wifiConfig) { this(wifiManager, wifiConfig, FLAG_FULL_MATCH, 0); } public void cancel() { synchronized (this) { isCanceled = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } } } private boolean matchesSSID(String currentSSID, String targetSSID) { if (currentSSID == null || targetSSID == null) { return false; } Pattern pattern = Pattern.compile("^\"(.*)\"$"); Matcher matcher = pattern.matcher(currentSSID); if ( matcher.matches() ) { currentSSID = matcher.group(1); } matcher = pattern.matcher(targetSSID); if ( matcher.matches() ) { targetSSID = matcher.group(1); } if (flag == FLAG_FULL_MATCH) { return currentSSID.equals(targetSSID); } else if (flag == FLAG_STARTS_WITH) { return currentSSID.startsWith(targetSSID); } else { throw new IllegalStateException("unknown flag: " + flag); } } @Override public void onReceive(Context context, Intent intent) { if (isCanceled) { return; } final String action = intent.getAction(); if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); // WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // NetworkInfo.DetailedState state = info.getDetailedState(); // String extraInfo = info.getExtraInfo(); // Log.d(TAG, "state changed: isConnected=" + info.isConnected() + " detailedState=" + state + " extra=" + extraInfo + " wifiInfo=" + wifiInfo + " networkInfo=" + info); lastSeenSSID = info.getExtraInfo(); if (info.isConnected()) { if (wifiInfo != null) { int ipaddr = wifiInfo.getIpAddress(); // String ipaddrString = String.format("%d.%d.%d.%d", // (ipaddr & 0xff), (ipaddr >> 8 & 0xff), (ipaddr >> 16 & 0xff), (ipaddr >> 24 & 0xff)); // Log.d(TAG, "ip address: " + ipaddrString); if (ipaddr == 0) { // Empty IP address. Still wait. return; } } if (wifiInfo != null) { String currentSSID = wifiInfo.getSSID(); if (matchesSSID(currentSSID, targetSSID)) { // Connected to target Wi-Fi synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onTargetWifiConnected(wifiInfo, info); } } } } } } } else if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) { int errorCode = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0); // NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); // WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); // Log.d(TAG, "Supplicant state change: errorCode=" + errorCode + " ERROR_AUTHENTICATING=" + WifiManager.ERROR_AUTHENTICATING); if (errorCode == WifiManager.ERROR_AUTHENTICATING) { if (matchesSSID(lastSeenSSID, targetSSID)) { long diff = System.currentTimeMillis() - startTime; Log.e(TAG, "Wifi authentication failed (count=" + authFailedCount + " diff=" + diff + "ms)"); if (++authFailedCount >= 2) { synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onError("Authentication failed"); } } } } if (diff >= ERROR_TIME_THRESHOLD) { synchronized (this) { if (!isCanceled && !isFinished) { isFinished = true; if (timeoutHandler != null) { timeoutHandler.removeCallbacks(timeoutRunnable); timeoutRunnable = null; timeoutHandler = null; } if (wifiConnectionChangeListener != null) { wifiConnectionChangeListener.onError("Authentication failed"); } } } } } } } } public WifiConnectionChangeListener getWifiConnectionChangeListener() { return wifiConnectionChangeListener; } public void setWifiConnectionChangeListener(WifiConnectionChangeListener wifiConnectionChangeListener) { this.wifiConnectionChangeListener = wifiConnectionChangeListener; } } /** * Wi-Fi * Receiver for the event which Wi-Fi is enabled. */ private static class WifiEnableEventReceiver extends BroadcastReceiver { public static final String TAG = WifiEnableEventReceiver.class.getSimpleName(); private interface WifiEnableEventReceiverListener { public void onWifiEnabled(); } private WifiEnableEventReceiverListener listener; private boolean isStopped = false; public WifiEnableEventReceiverListener getListener() { return listener; } public void setListener(WifiEnableEventReceiverListener listener) { this.listener = listener; } public void stop() { isStopped = true; } @Override public void onReceive(Context context, Intent intent) { if (isStopped) { return; } int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1); if (wifiState == WifiManager.WIFI_STATE_ENABLED) { if (listener != null) { listener.onWifiEnabled(); } } } } /** * Wi-Fi * Receiver for Wi-Fi scan results. */ private static class ScanResultReceiver extends BroadcastReceiver { public static final String TAG = ScanResultReceiver.class.getSimpleName(); private boolean isStopped; private WifiManager wifiManager; private IRKitWifiScanResultListener irkitWifiScanResultListener; public ScanResultReceiver(WifiManager wifiManager) { this.wifiManager = wifiManager; isStopped = false; } @Override public void onReceive(Context context, Intent intent) { if (isStopped) { return; } List<ScanResult> results = wifiManager.getScanResults(); if (results != null) { for (ScanResult result : results) { if (IRWifiInfo.isIRKitWifi(result)) { if (irkitWifiScanResultListener != null) { irkitWifiScanResultListener.onIRKitWifiFound(result); return; } } } } if (!isStopped) { wifiManager.startScan(); } } public void stopScan() { isStopped = true; } public IRKitWifiScanResultListener getIRKitWifiScanResultListener() { return irkitWifiScanResultListener; } public void setIRKitWifiScanResultListener(IRKitWifiScanResultListener irKitWifiScanResultListener) { this.irkitWifiScanResultListener = irKitWifiScanResultListener; } } }
package builder.controller; import java.awt.Color; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import builder.Builder; import builder.common.ColorFactory; import builder.common.CommonUtil; import builder.common.EnumFactory; import builder.common.FontFactory; import builder.common.FontItem; import builder.common.TestException; import builder.models.BoxModel; import builder.models.CheckBoxModel; import builder.models.GeneralModel; import builder.models.GraphModel; import builder.models.ImageModel; import builder.models.ImgButtonModel; import builder.models.ProgressBarModel; import builder.models.RadioButtonModel; import builder.models.SliderModel; import builder.models.TextBoxModel; import builder.models.TextModel; import builder.models.TxtButtonModel; import builder.models.WidgetModel; import builder.prefs.GeneralEditor; import builder.views.PagePane; import builder.widgets.Widget; /** * The Class CodeGenerator does the actual creation of the C skeleton * used by GUIslice API mapped to the specific platform, arduino, or linux. * <p> * Much of the code is driven by templates that are keyed by Tags within the * C skeletons. * </p> * <ul> * <li>ino.t for arduino C skeleton * <li>min.t for arduino using flash C skeleton * <li>c.t for linux C skeleton * <li>arduino.t for arduino code templates * <li>arduino_min.t for arduino flash code templates * <li>linux.t for linux code templates * </ul> * * Kind of a Quick and Dirty implementation. * * @author Paul Conti * */ public class CodeGenerator { /** The instance. */ private static CodeGenerator instance = null; /** The Constant ARDUINO_PLATFORM. */ private final static int ARDUINO_PLATFORM = 0; /** The Constant LINUX_PLATFORM. */ private final static int LINUX_PLATFORM = 1; /** The Constant ARDUINO_MIN_PLATFORM. */ private final static int ARDUINO_MIN_PLATFORM = 2; /** The target platform. */ private static int targetPlatform = 0; /** The max string length */ private static int maxstr_len; /** The Constant ARDUINO_FONT_TEMPLATE. */ public final static String ARDUINO_FONT_TEMPLATE = "arduinofonts.csv"; /** The Constant DROIDFONTS_TEMPLATE. */ public final static String DROIDFONTS_TEMPLATE = "droidfonts.csv"; /** The Constant FREEFONTS_TEMPLATE. */ public final static String FREEFONTS_TEMPLATE = "freefonts.csv"; /** The Constant LINUX_FONT_TEMPLATE. */ public final static String LINUX_FONT_TEMPLATE = "linuxfonts.csv"; /** The Constant ARDUINO_RES. */ public final static String ARDUINO_RES = "arduino_res"; /** The Constant LINUX_RES. */ public final static String LINUX_RES = "linux_res"; /** The Constant ARDUINO_FILE. */ public final static String ARDUINO_FILE = "ino.t"; /** The Constant LINUX_FILE. */ public final static String LINUX_FILE = "c.t"; /** The Constant ARDUINO_MIN_FILE. */ public final static String ARDUINO_MIN_FILE = "min.t"; /** The Constant ALIGN_TEMPLATE. */ private final static String ALIGN_TEMPLATE = "<ALIGN>"; /** The Constant BACKGROUND_TEMPLATE. */ private final static String BACKGROUND_TEMPLATE = "<BACKGROUND>"; /** The Constant BOX_TEMPLATE. */ private final static String BOX_TEMPLATE = "<BOX>"; /** The Constant BUTTON_CB_TEMPLATE. */ private final static String BUTTON_CB_TEMPLATE = "<BUTTON_CB>"; /** The Constant BUTTON_LOOP_TEMPLATE. */ private final static String BUTTON_LOOP_TEMPLATE = "<BUTTON_CB_LOOP>"; /** The Constant BUTTON_CHGPG_TEMPLATE. */ private final static String BUTTON_CHGPG_TEMPLATE = "<BUTTON_CB_CHGPAGE>"; /** The Constant CHECKBOX_TEMPLATE. */ private final static String CHECKBOX_TEMPLATE = "<CHECKBOX>"; /** The Constant COLOR_TEMPLATE. */ private final static String COLOR_TEMPLATE = "<COLOR>"; /** The Constant DRAWFUNC_TEMPLATE. */ private final static String DRAWFUNC_TEMPLATE = "<DRAWFUNC>"; /** The Constant DRAWBOX_CB_TEMPLATE. */ private final static String DRAWBOX_CB_TEMPLATE = "<DRAWBOX_CB>"; /** The Constant FONT_LOAD_TEMPLATE. */ private final static String FONT_LOAD_TEMPLATE = "<FONT_LOAD>"; /** The Constant GRAPH_TEMPLATE. */ private final static String GRAPH_TEMPLATE = "<GRAPH>"; /** The Constant GROUP_TEMPLATE. */ private final static String GROUP_TEMPLATE = "<GROUP>"; /** The Constant IMAGE_TEMPLATE. */ private final static String IMAGE_TEMPLATE = "<IMAGE>"; /** The Constant IMGBUTTON_TEMPLATE. */ private final static String IMGBUTTON_TEMPLATE = "<IMGBUTTON>"; /** The Constant IMAGETRANSPARENT_TEMPLATE. */ private final static String IMAGETRANSPARENT_TEMPLATE = "<IMAGETRANSPARENT>"; /** The Constant PROGMEM_TEMPLATE. */ private final static String PROGMEM_TEMPLATE = "<PROGMEM>"; /** The Constant PROGRESSBAR_TEMPLATE. */ private final static String PROGRESSBAR_TEMPLATE = "<PROGRESSBAR>"; /** The Constant RADIOBUTTON_TEMPLATE. */ private final static String RADIOBUTTON_TEMPLATE = "<RADIOBUTTON>"; /** The Constant SLIDER_TEMPLATE. */ private final static String SLIDER_TEMPLATE = "<SLIDER>"; /** The Constant SLIDER_CB_TEMPLATE. */ private final static String SLIDER_CB_TEMPLATE = "<SLIDER_CB>"; /** The Constant SLIDER_LOOP_TEMPLATE. */ private final static String SLIDER_LOOP_TEMPLATE = "<SLIDER_CB_LOOP>"; /** The Constant TEXT_TEMPLATE. */ private final static String TEXT_TEMPLATE = "<TEXT>"; /** The Constant TEXTBOX_TEMPLATE. */ private final static String TEXTBOX_TEMPLATE = "<TEXTBOX>"; /** The Constant TEXTCOLOR_TEMPLATE. */ private final static String TEXTCOLOR_TEMPLATE = "<TEXT_COLOR>"; /** The Constant TEXT_UPDATE_TEMPLATE. */ private final static String TEXT_UPDATE_TEMPLATE = "<TEXT_UPDATE>"; /** The Constant TICK_CB_TEMPLATE. */ private final static String TICK_CB_TEMPLATE = "<TICK_CB>"; /** The Constant TICKFUNC_TEMPLATE. */ private final static String TICKFUNC_TEMPLATE = "<TICKFUNC"; /** The Constant TXTBUTTON_TEMPLATE. */ private final static String TXTBUTTON_TEMPLATE = "<TXTBUTTON>"; /** The Constant STOP_TEMPLATE. */ private final static String STOP_TEMPLATE = "<STOP>"; /** The Constant END_TEMPLATE. */ private final static String END_TEMPLATE = "<END>"; /** The Constant ARDUINO_EXT. */ public final static String ARDUINO_EXT = ".ino"; /** The Constant LINUX_EXT. */ public final static String LINUX_EXT = ".c"; /** The Constant RESOURCES_PATH. */ private final static String RESOURCES_PATH = "/resources/templates/"; /** The Constant PREFIX. */ private final static String PREFIX = " /** The Constant BUTTON_CB_SECTION. */ private final static String BUTTON_CB_SECTION = "//<Button Callback !Start!>"; /** The Constant BUTTON_CB_END. */ private final static String BUTTON_CB_END = "//<Button Callback !End!>"; /** The Constant BUTTON_ENUMS_SECTION. */ private final static String BUTTON_ENUMS_SECTION = "//<Button Enums !Start!>"; /** The Constant BUTTON_ENUMS_END. */ private final static String BUTTON_ENUMS_END = "//<Button Enums !End!>"; /** The Constant DEFINES_SECTION. */ private final static String DEFINES_SECTION = "//<ElementDefines !Start!>"; /** The Constant DEFINES_END. */ private final static String DEFINES_END = "//<ElementDefines !End!>"; /** The Constant DRAW_CB_SECTION. */ private final static String DRAW_CB_SECTION = "//<Draw Callback !Start!>"; /** The Constant DRAW_CB_END. */ private final static String DRAW_CB_END = "//<Draw Callback !End!>"; /** The Constant ENUM_SECTION. */ private final static String ENUM_SECTION = "//<Enum !Start!>"; /** The Constant ENUM_END. */ private final static String ENUM_END = "//<Enum !End!>"; /** The Constant FILE_SECTION. */ private final static String FILE_SECTION = "//<File !Start!>"; /** The Constant FILE_END. */ private final static String FILE_END = "//<File !End!>"; /** The Constant FONT_SECTION. */ private final static String FONT_SECTION = "//<Fonts !Start!>"; /** The Constant FONT_END. */ private final static String FONT_END = "//<Fonts !End!>"; /** The Constant GUI_SECTION. */ private final static String GUI_SECTION = "//<GUI_Extra_Elements !Start!>"; /** The Constant GUI_END. */ private final static String GUI_END = "//<GUI_Extra_Elements !End!>"; /** The Constant INITGUI_SECTION. */ private final static String INITGUI_SECTION = "//<InitGUI !Start!>"; /** The Constant INITGUI_END. */ private final static String INITGUI_END = "//<InitGUI !End!>"; /** The Constant LOADFONT_SECTION. */ private final static String LOADFONT_SECTION = "//<Load_Fonts !Start!>"; /** The Constant LOADFONT_END. */ private final static String LOADFONT_END = "//<Load_Fonts !End!>"; /** The Constant PATH_SECTION. */ private final static String PATH_SECTION = "//<PathStorage !Start!>"; /** The Constant PATH_END. */ private final static String PATH_END = "//<PathStorage !End!>"; /** The Constant QUICK_SECTION. */ private final static String QUICK_SECTION = "//<Quick_Access !Start!>"; /** The Constant QUICK_END. */ private final static String QUICK_END = "//<Quick_Access !End!>"; /** The Constant RESOURCES_SECTION. */ private final static String RESOURCES_SECTION = "//<Resources !Start!>"; /** The Constant RESOURCES_END. */ private final static String RESOURCES_END = "//<Resources !End!>"; /** The Constant SAVEREF_SECTION. */ private final static String SAVEREF_SECTION = "//<Save_References !Start!>"; /** The Constant SAVEREF_END. */ private final static String SAVEREF_END = "//<Save_References !End!>"; /** The Constant SLIDER_CB_SECTION. */ private final static String SLIDER_CB_SECTION = "//<Slider Callback !Start!>"; /** The Constant SLIDER_CB_END. */ private final static String SLIDER_CB_END = "//<Slider Callback !End!>"; /** The Constant SLIDER_ENUMS_SECTION. */ private final static String SLIDER_ENUMS_SECTION = "//<Slider Enums !Start!>"; /** The Constant SLIDER_ENUMS_END. */ private final static String SLIDER_ENUMS_END = "//<Slider Enums !End!>"; /** The Constant TICK_CB_SECTION. */ private final static String TICK_CB_SECTION = "//<Tick Callback !Start!>"; /** The Constant TICK_CB_END. */ private final static String TICK_CB_END = "//<Tick Callback !End!>"; /** The Constant PAGE_ENUM_MACRO. */ private final static String PAGE_ENUM_MACRO = "PAGE_ENUM"; /** The Constant BACKGROUND_COLOR_MACRO. */ private final static String BACKGROUND_COLOR_MACRO = "BACKGROUND_COLOR"; /** The Constant BOOL_MACRO. */ private final static String BOOL_MACRO = "BOOL"; /** The Constant CHECKED_MACRO. */ private final static String CHECKED_MACRO = "CHECKED"; /** The Constant COLS_MACRO. */ private final static String COLS_MACRO = "COLS"; /** The Constant COUNT_MACRO. */ private final static String COUNT_MACRO = "COUNT"; /** The Constant ENUM_MACRO. */ private final static String ENUM_MACRO = "WIDGET_ENUM"; /** The Constant DIVISIONS_MACRO. */ private final static String DIVISIONS_MACRO = "DIVISIONS"; /** The Constant DRAWFUNC_MACRO. */ private final static String DRAWFUNC_MACRO = "DRAWFUNC"; /** The Constant FILL_COLOR_MACRO. */ private final static String FILL_COLOR_MACRO = "FILL_COLOR"; /** The Constant FONT_COUNT_MACRO. */ private final static String FONT_COUNT_MACRO = "FONT_COUNT"; /** The Constant FONT_ID_MACRO. */ private final static String FONT_ID_MACRO = "FONT_ID"; /** The Constant FONT_REF_MACRO. */ private final static String FONT_REF_MACRO = "FONT_REF"; /** The Constant FONT_REFTYPE_MACRO. */ private final static String FONT_REFTYPE_MACRO = "FONT_REFTYPE"; /** The Constant FONT_SZ_MACRO. */ private final static String FONT_SZ_MACRO = "FONT_SZ"; /** The Constant FRAME_COLOR_MACRO. */ private final static String FRAME_COLOR_MACRO = "FRAME_COLOR"; /** The Constant GLOW_COLOR_MACRO. */ private final static String GLOW_COLOR_MACRO = "GLOW_COLOR"; /** The Constant GRAPH_COLOR_MACRO. */ private final static String GRAPH_COLOR_MACRO = "GRAPH_COLOR"; /** The Constant GROUP_ID_MACRO. */ private final static String GROUP_ID_MACRO = "GROUP_ID"; /** The Constant HEIGHT_MACRO. */ private final static String HEIGHT_MACRO = "HEIGHT"; /** The Constant ID_MACRO. */ private final static String ID_MACRO = "ID"; /** The Constant IMAGE_MACRO. */ private final static String IMAGE_MACRO = "IMAGE_DEFINE"; /** The Constant IMAGE_SEL_MACRO. */ private final static String IMAGE_SEL_MACRO = "IMAGE_SEL_DEFINE"; /** The Constant IMAGE_FORMAT_MACRO. */ private final static String IMAGE_FORMAT_MACRO = "IMAGE_FORMAT"; /** The Constant MARK_COLOR_MACRO. */ private final static String MARK_COLOR_MACRO = "MARK_COLOR"; /** The Constant MIN_MACRO. */ private final static String MIN_MACRO = "MIN"; /** The Constant MAX_MACRO. */ private final static String MAX_MACRO = "MAX"; /** The Constant ROWS_MACRO. */ private final static String ROWS_MACRO = "ROWS"; /** The Constant SIZE_MACRO. */ private final static String SIZE_MACRO = "SIZE"; /** The Constant STYLE_MACRO. */ private final static String STYLE_MACRO = "STYLE"; /** The Constant TEXT_MACRO. */ private final static String TEXT_MACRO = "TEXT"; /** The Constant TEXT_ALIGN_MACRO. */ private final static String TEXT_ALIGN_MACRO = "TEXT_ALIGN"; /** The Constant TEXT_COLOR_MACRO. */ private final static String TEXT_COLOR_MACRO = "TEXT_COLOR"; /** The Constant THUMBSZ_MACRO. */ private final static String THUMBSZ_MACRO = "THUMBSZ"; /** The Constant TICKFUNC_MACRO. */ private final static String TICKFUNC_MACRO = "TICKFUNC"; /** The Constant TICKSZ_MACRO. */ private final static String TICKSZ_MACRO = "TICKSZ"; /** The Constant TRIM_COLOR_MACRO. */ private final static String TRIM_COLOR_MACRO = "TRIM_COLOR"; /** The Constant VALUE_MACRO. */ private final static String VALUE_MACRO = "VALUE"; /** The Constant WIDTH_MACRO. */ private final static String WIDTH_MACRO = "WIDTH"; /** The Constant X_MACRO. */ private final static String X_MACRO = "X"; /** The Constant Y_MACRO. */ private final static String Y_MACRO = "Y"; /** The Constant BEGIN_LINE. */ // finite state machine for printing enums private final static int BEGIN_LINE = 0; /** The Constant WRITE_NEXT. */ private final static int WRITE_NEXT = 1; /** The Constant OVERFLOW_LINE. */ private final static int OVERFLOW_LINE = 2; /** The print state. */ int printState = BEGIN_LINE; /** The backup file. */ private File backupFile=null; /** The backup name. */ private String backupName=null; /** The fr. */ private FileReader fr; /** The br. */ private BufferedReader br; /** The fw. */ private FileWriter fw; /** The pw. */ private PrintWriter pw; /** The cf. */ private static ColorFactory cf; /** The ff. */ private static FontFactory ff=null; /** The pages. */ private List<PagePane> pages; /** The project file. */ File projectFile = null; /** The target. */ static String target = null; /** The file extension. */ static String fileExtension = null; /** The default file name. */ String defaultFileName = null; /** The template file name. */ String templateFileName = null; /** The font list. */ List<FontItem> fontList = new ArrayList<FontItem>(); /** The template map. */ HashMap<String, Integer> templateMap; /** The ref list. */ List<WidgetModel> refList = new ArrayList<WidgetModel>(); /** The list of templates. */ List<String>[] listOfTemplates = null; /** The macro. */ String[] macro = new String[30]; /** The replacement. */ String[] replacement = new String[30]; /** The count check boxes. */ // its possible that a better way of handling this exists but brute force works so... int countCheckBoxes = 0; /** The count gauges. */ int countGauges = 0; /** The count sliders. */ int countSliders = 0; /** The line. */ String line = ""; /** The background color */ private Color background; /** * Gets the single instance of CodeGenerator. * * @return single instance of CodeGenerator */ public static synchronized CodeGenerator getInstance() { if (instance == null) { instance = new CodeGenerator(); } return instance; } /** * Get a Test Instance for JUnit tests * @return instance of CodeGenerator * @throws TestException on read of resource failure */ public static synchronized CodeGenerator getTestInstance() throws TestException { if (instance == null) { instance = new CodeGenerator(); cf = ColorFactory.getInstance(); ff = FontFactory.getInstance(); } return instance; } /** * Instantiates a new code generator. */ public CodeGenerator() { } /** * Generate code setup. * * @param fileName * the file name * @param pages * the pages */ @SuppressWarnings("unchecked") public String generateCode(String folder, String fileName, List<PagePane> pages) { this.pages = pages; GeneralModel generalModel = (GeneralModel) GeneralEditor.getInstance().getModel(); cf = ColorFactory.getInstance(); ff = FontFactory.getInstance(); target = generalModel.getTarget(); maxstr_len = generalModel.getMaxStr(); background = generalModel.getFillColor(); cf = ColorFactory.getInstance(); ff = FontFactory.getInstance(); target = generalModel.getTarget(); maxstr_len = generalModel.getMaxStr(); background = generalModel.getFillColor(); listOfTemplates = new ArrayList[32]; switch(target) { case "linux": defaultFileName = LINUX_FILE; fileExtension = LINUX_EXT; storeTemplates("linux.t"); targetPlatform = LINUX_PLATFORM; break; case "arduino_min": defaultFileName = ARDUINO_MIN_FILE; fileExtension = ARDUINO_EXT; storeTemplates("arduino_min.t"); targetPlatform = ARDUINO_MIN_PLATFORM; break; default: defaultFileName = ARDUINO_FILE; fileExtension = ARDUINO_EXT; storeTemplates("arduino.t"); targetPlatform = ARDUINO_PLATFORM; break; } if (fileName == null) { return null; } int n = fileName.indexOf(".prj"); String tmp = fileName.substring(0,n); String skeletonName = new String(folder + System.getProperty("file.separator") + tmp + fileExtension); projectFile = new File(skeletonName); if(projectFile.exists()) { // Make a backup copy of projectFile and overwrite backup file if it exists. backupName = new String(skeletonName + ".bak"); backupFile = new File(backupName); if (backupFile.exists()) { // rename previous backup files so we don't lose them String newTemplate = new String(skeletonName + ".ba"); int idx = 0; String newName = newTemplate + String.valueOf(++idx); File newFile = new File(newName); while (newFile.exists()) { newName = newTemplate + String.valueOf(++idx); newFile = new File(newName); } backupFile.renameTo(newFile); } copyFile(projectFile, backupFile); } try { // Here we are either going to use a previously generated file as input // or we are generating a brand new file from one of our templates. // if backupFile == null then its a brand new file // I do all of this so users can create a file, then edit it do a run on a target platform // and go back and add or subtract widgets from the same file and not lose edits. if (backupName == null) { String fullPath = CommonUtil.getInstance().getWorkingDir(); String tName = fullPath + "templates" + System.getProperty("file.separator") + defaultFileName; File template = new File(tName); fr = new FileReader(template); } else { backupFile = new File(backupName); fr = new FileReader(backupFile); } br = new BufferedReader(fr); doCodeGen(); return skeletonName; } catch (IOException e) { e.printStackTrace(); return null; } } /** * Generate test code setup. * * @param outName * the file name for output of code generation * @param pages * the pages * @throws TestException on read of resources * @throws IOException on file i/o */ @SuppressWarnings("unchecked") public void generateTestCode(String testPlatform, String outName, List<PagePane> pages) throws TestException, IOException { target = testPlatform; this.pages = pages; background = Color.GRAY; maxstr_len = 100; listOfTemplates = new ArrayList[32]; if (outName == null) throw new TestException("Missing Name of Output Project File"); switch(target) { case "linux": defaultFileName = LINUX_FILE; fileExtension = LINUX_EXT; storeTemplates("linux.t"); targetPlatform = LINUX_PLATFORM; break; case "arduino_min": defaultFileName = ARDUINO_MIN_FILE; fileExtension = ARDUINO_EXT; storeTemplates("arduino_min.t"); targetPlatform = ARDUINO_MIN_PLATFORM; break; default: defaultFileName = ARDUINO_FILE; fileExtension = ARDUINO_EXT; storeTemplates("arduino.t"); targetPlatform = ARDUINO_PLATFORM; break; } String fileName = new String(outName + fileExtension); // prompt the user to enter output name projectFile = new File(fileName); if (projectFile == null) throw new TestException("Creation of Output File Failed"); String resourcePath = "/resources/templates/" + defaultFileName; InputStream in; in = Builder.class.getResourceAsStream(resourcePath); if (in == null) { throw new TestException("missing resource: " + resourcePath); } br = new BufferedReader(new InputStreamReader(in)); doCodeGen(); } /** * doCodeGen is the main code generation loop. */ public void doCodeGen() { fontList.clear(); refList.clear(); try { fw = new FileWriter(projectFile); pw = new PrintWriter(fw); while ((line = br.readLine()) != null) { if (!line.startsWith(PREFIX)) { pw.printf("%s%n",line); } else { if (line.equals(FONT_SECTION)) { fontSection(); } else if (line.equals(RESOURCES_SECTION)) { resourcesSection(); } else if (line.equals(ENUM_SECTION)) { enumSection(); } else if (line.equals(DEFINES_SECTION)) { definesSection(); } else if (line.equals(GUI_SECTION)) { guiSection(); } else if (line.equals(SAVEREF_SECTION)) { saveRefSection(); } else if (line.equals(BUTTON_CB_SECTION)) { buttonCbSection(); } else if (line.equals(DRAW_CB_SECTION)) { drawCbSection(); } else if (line.equals(SLIDER_CB_SECTION)) { sliderCbSection(); } else if (line.equals(TICK_CB_SECTION)) { tickCbSection(); } else if (line.equals(INITGUI_SECTION)) { initGUISection(); } else if (line.equals(QUICK_SECTION)) { quickAccessSection(); } else if (line.equals(LOADFONT_SECTION)) { loadFontSection(); } else if (line.equals(BUTTON_ENUMS_SECTION)) { buttonEnumsSection(); } else if (line.equals(SLIDER_ENUMS_SECTION)) { sliderEnumsSection(); } else if (line.equals(FILE_SECTION)) { fileNameSection(); } else if (line.equals(PATH_SECTION)) { pathSection(); } else { pw.printf("%s%n",line); } } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (pw != null) pw.close(); if (fw != null) fw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * File name section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void fileNameSection() throws IOException { pw.printf("// FILE: %s%n", projectFile.getName()); while ((line = br.readLine()) != null) { if (line.equals(FILE_END)) break; } } /** * Path section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void pathSection() throws IOException { // this section currently only occurs in linux platform. // find our Image and ImageButton models since no one else needs path name storage List<WidgetModel> modelList = new ArrayList<WidgetModel>(); List<String> widgetTypes = new ArrayList<String>(); widgetTypes.add(EnumFactory.IMAGE); widgetTypes.add(EnumFactory.IMAGEBUTTON); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, modelList); } // now generate path name storage String strKey = ""; String strCount = ""; for (WidgetModel m : modelList) { strKey = m.getKey(); int n = strKey.indexOf("$"); strCount = strKey.substring(n+1, strKey.length()); if (m.getType().equals(EnumFactory.IMAGE)) { pw.printf("char m_strImgPath%s[MAX_PATH];%n", strCount); } else { // must be EnumFactory.IMAGEBUTTON pw.printf("char m_strImgBtnPath%s[MAX_PATH];%n", strCount); pw.printf("char m_strImgBtnSelPath%s[MAX_PATH];%n", strCount); } } // finish up by scanning pass this section of our template readPassString(PATH_END); } /** * Font section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void fontSection() throws IOException { pw.printf("%s%n",line); // build up a list of GUISlice fonts in use // Find our Text, TextButton, and TextBox models // and pull out from the models the font keys that we can map // to something GUIslice API can understand. List<String> fontNames = new ArrayList<String>(); for (PagePane p : pages) { for (Widget w : p.getWidgets()) { if (w.getType().equals(EnumFactory.TEXT)) { fontNames.add(((TextModel)w.getModel()).getFontDisplayName()); } else if (w.getType().equals(EnumFactory.TEXTBUTTON)) { fontNames.add(((TxtButtonModel)w.getModel()).getFontDisplayName()); } else if (w.getType().equals(EnumFactory.TEXTBOX)) { fontNames.add(((TextBoxModel)w.getModel()).getFontDisplayName()); } } } // Now we have a full list of font names but we also may have duplicates // so we sort the list in order and remove duplicates. sortListandRemoveDups(fontNames); // Now make pass using our now compact set of font names to // grab all of our font data (FontItem) for each font in use. for (String fName : fontNames) { FontItem item = ff.getFontItem(fName); fontList.add(item); } // finish off by outputting font includes or defines, if any List<String> dups = new ArrayList<String>(); for (FontItem f : fontList) { if (!f.getIncludeFile().equals("NULL")) { // This code only affects arduino implementation. pw.printf("#include \"%s\"%n", f.getIncludeFile()); } else if (!f.getDefineFile().equals("NULL")) { // This code only affects linux implementation. // I have removed duplicate enums but duplicate fontrefs can and will still exist // I don't expect too many so i'll just use brute force on checking boolean bFound = false; for (String s : dups) { if (s.equals(f.getFontRef())) bFound = true; } if (!bFound) { pw.printf("#define %-20s \"%s\"%n", f.getFontRef(), f.getDefineFile()); dups.add(f.getFontRef()); } } } // finish up by scanning pass this section of our template readPassString(FONT_END); } /** * Resources section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void resourcesSection() throws IOException { pw.printf("%s%n",line); // build up a list of GUISlice resources in use List<String> resources = new ArrayList<String>(); // first find our Image and ImageButton models // since no one else uses resources List<WidgetModel> modelList = new ArrayList<WidgetModel>(); List<String> widgetTypes = new ArrayList<String>(); widgetTypes.add(EnumFactory.IMAGE); widgetTypes.add(EnumFactory.IMAGEBUTTON); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, modelList); } // now pull out from the models the resources as strings that GUIslice can understand for (WidgetModel m : modelList) { if (m.getType().equals(EnumFactory.IMAGE)) { String s = String.format("#define %-25s \"%s\"", ((ImageModel) m).getDefine(), ((ImageModel) m).getImageName()); resources.add(s); } else { // must be EnumFactory.IMAGEBUTTON String s = String.format("#define %-25s \"%s\"", ((ImgButtonModel) m).getDefine(), ((ImgButtonModel) m).getImageName()); String sel = String.format("#define %-25s \"%s\"", ((ImgButtonModel) m).getSelDefine(), ((ImgButtonModel) m).getSelectImageName()); resources.add(s); resources.add(sel); } } // Sort the list in order then make another pass to remove dups. // We might have the same image on different pages of the UI, like a Logo. sortListandRemoveDups(resources); // finish off by outputting resources, if any for (String s : resources) { pw.printf("%s%n", s); } // finish up by scanning pass this section of our template readPassString(RESOURCES_END); } /** * Enum section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void enumSection() throws IOException { pw.printf("%s%n",line); // build up a list of GUISlice enums in use // first find our Page models List<String> enumList = new ArrayList<String>(); for (PagePane p : pages) { enumList.add(p.getEnum()); } printEnums(enumList); // Now build up a list of our remaining UI widget enums enumList.clear(); String ref = ""; String strKey = ""; String strCount = ""; String strEnum = ""; int n; for (PagePane p : pages) { for (Widget w : p.getWidgets()) { strEnum = w.getModel().getEnum(); if (!strEnum.equals("GSLC_ID_AUTO")) enumList.add(strEnum); // textbox has an embedded scrollbar so add it. if (w.getType().equals(EnumFactory.TEXTBOX)) { ref = "E_SCROLLBAR"; strKey = w.getModel().getKey(); n = strKey.indexOf("$"); strCount = strKey.substring(n+1, strKey.length()); ref = ref + strCount; enumList.add(ref); } } } if (enumList.size() > 0) { // Now we have a full list of enum names we can sort the list. Collections.sort(enumList); // Now output the list printEnums(enumList); } enumList.clear(); // Final pass output any font enums for (FontItem f : fontList) { enumList.add(f.getFontId()); } if (enumList.size() > 0) printEnums(enumList); // finish up by scanning pass this section of our template readPassString(ENUM_END); } /** * Defines section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void definesSection() throws IOException { pw.printf("%s%n",line); // output number of pages String elemTitle = "MAX_PAGE"; pw.printf("#define %-24s%d%n", elemTitle, pages.size()); // output number of fonts elemTitle = "MAX_FONT"; pw.printf("#define %-24s%d%n", elemTitle, fontList.size()); // build up a list of counts for out various UI widgets // build up a list of counts for out various UI widgets // first are we doing arduino minimum? if so, count _P functions stored in flash int i = 0; if (targetPlatform == ARDUINO_MIN_PLATFORM) { int[] elem_cnt = new int[pages.size()]; int[] flash_cnt = new int[pages.size()]; List<String> widgetTypes = new ArrayList<String>(); widgetTypes.add(EnumFactory.CHECKBOX); widgetTypes.add(EnumFactory.RADIOBUTTON); widgetTypes.add(EnumFactory.BOX); widgetTypes.add(EnumFactory.PROGRESSBAR); widgetTypes.add(EnumFactory.SLIDER); widgetTypes.add(EnumFactory.TEXT); widgetTypes.add(EnumFactory.TEXTBUTTON); for (PagePane p : pages) { flash_cnt[i] = countByType(p.getWidgets(), widgetTypes); elem_cnt[i] = p.getWidgets().size(); i++; } // we also need to output some comments List<String> templateLines = loadTemplate(PROGMEM_TEMPLATE); writeTemplate(templateLines); i = 0; elemTitle = "MAX_ELEM_PG_MAIN"; for (PagePane p : pages) { if (p.getWidgets().size() > 0) { pw.printf("#define %-24s%d%n", elemTitle, elem_cnt[i]); } i++; elemTitle = String.format("%s%d", "MAX_ELEM_PG_EXTRA", i); } pw.printf("#if (GSLC_USE_PROGMEM)%n"); i = 0; elemTitle = "MAX_ELEM_PG_MAIN_PROG"; for (PagePane p : pages) { if (p.getWidgets().size() > 0) { pw.printf("#define %-24s%d%n", elemTitle, flash_cnt[i]); } i++; elemTitle = String.format("%s%d", "MAX_ELEM_PG_EXTRA_PROG", i); } pw.printf("#else%n"); i = 0; elemTitle = "MAX_ELEM_PG_MAIN_PROG"; for (PagePane p : pages) { if (p.getWidgets().size() > 0) { pw.printf("#define %-24s%d%n", elemTitle, 0); } i++; elemTitle = String.format("%s%d", "MAX_ELEM_PG_EXTRA_PROG", i); } pw.printf("#endif%n"); i = 0; elemTitle = "MAX_ELEM_PG_MAIN_RAM"; for (PagePane p : pages) { if (p.getWidgets().size() > 0) { if (i==0) { pw.printf("#define %-24sMAX_ELEM_PG_MAIN - MAX_ELEM_PG_MAIN_PROG%n", elemTitle); } else { pw.printf("#define %-24sMAX_ELEM_PG_EXTRA%d - MAX_ELEM_PG_EXTRA_PROG%d%n", elemTitle,i,i); } } i++; elemTitle = String.format("%s%d", "MAX_ELEM_PG_EXTRA_RAM", i); } } else { elemTitle = "MAX_ELEM_PG_MAIN"; for (PagePane p : pages) { int count = 0; for (Widget w : p.getWidgets()) { if (w.getType().equals(EnumFactory.TEXTBOX)) { count += 3; // TEXTBOX has embedded a wrapper Box and a scrollbar along with text box } else { count++; } } if (count > 0) { pw.printf("#define %-24s%d%n", elemTitle, count); if (i==0) { pw.printf("#define %s %s%n", "MAX_ELEM_PG_MAIN_RAM",elemTitle); } else { pw.printf("#define %s%d %s%n", "MAX_ELEM_PG_EXTRA_RAM",i,elemTitle); } } i++; elemTitle = String.format("%s%d", "MAX_ELEM_PG_EXTRA", i); } } readPassString(DEFINES_END); } /** * Gui section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void guiSection() throws IOException { pw.printf("%s%n",line); // output GUI extra elements,if we have more than one page String strElement = ""; if (pages.size() > 1) { for (int i=1; i<pages.size(); i++) { if (pages.get(i).getWidgets().size() > 0) { strElement = "gslc_tsElem"; pw.printf("%-25sm_asExtraElem[MAX_ELEM_PG_EXTRA_RAM%d];%n", strElement, i); strElement = "gslc_tsElemRef"; pw.printf("%-25sm_asExtraElemRef[MAX_ELEM_PG_EXTRA%d];%n", strElement, i); } } } // extension widgets have separate storage // Except, for reasons unknown to me extra storage isn't used by arduino min // Which begs the question why does standard arduino and linux need it? // how many text boxes? // we need to do text boxes first because they have an embedded scrollbar // that needs to be taken into account. int textbox_cnt = 0; int nRows, nCols; String strKey = ""; int n = 0; String strCount = ""; String ref = ""; for (PagePane p : pages) { for (Widget w : p.getWidgets()) { if (w.getType().equals(EnumFactory.TEXTBOX)) { textbox_cnt++; nRows = ((TextBoxModel)w.getModel()).getNumTextRows(); nCols = ((TextBoxModel)w.getModel()).getNumTextColumns(); strKey = w.getKey(); n = strKey.indexOf("$"); strCount = strKey.substring(n+1, strKey.length()); ref = "m_sTextbox" + strCount; strElement = "gslc_tsXTextbox"; pw.printf("%-32s%s;%n", strElement, ref); strElement = "char"; ref = "m_acTextboxBuf" + strCount; pw.printf("%-32s%s[%d]; // NRows=%d NCols=%d%n", strElement, ref, nRows*nCols, nRows, nCols); } } } // how many graphs? for (PagePane p : pages) { for (Widget w : p.getWidgets()) { if (w.getType().equals(EnumFactory.GRAPH)) { nRows = ((GraphModel)w.getModel()).getNumRows(); strKey = w.getKey(); n = strKey.indexOf("$"); strCount = strKey.substring(n+1, strKey.length()); ref = "m_sGraph" + strCount; strElement = "gslc_tsXGraph"; pw.printf("%-32s%s;%n", strElement, ref); strElement = "int16_t"; ref = "m_anGraphBuf" + strCount; pw.printf("%-32s%s[%d]; // NRows=%d%n", strElement, ref, nRows, nRows); } } } // Extension widgets have separate storage // Except, for reasons unknown to me extra storage isn't used by arduino min _P API if (targetPlatform != ARDUINO_MIN_PLATFORM) { List<String> widgetTypes = new ArrayList<String>(); int count = 0; // how many checkboxes? widgetTypes.add(EnumFactory.CHECKBOX); widgetTypes.add(EnumFactory.RADIOBUTTON); for (PagePane p : pages) { count += countByType(p.getWidgets(), widgetTypes); } if (count > 0) { strElement = "gslc_tsXCheckbox"; pw.printf("%-32sm_asXCheck[%d];%n", strElement, count); } widgetTypes.clear(); // how many gauges? widgetTypes.add(EnumFactory.PROGRESSBAR); count = 0; for (PagePane p : pages) { count += countByType(p.getWidgets(), widgetTypes); } if (count > 0) { strElement = "gslc_tsXGauge"; pw.printf("%-32sm_sXGauge[%d];%n", strElement, count); } // how many sliders? widgetTypes.clear(); widgetTypes.add(EnumFactory.SLIDER); count = 0; for (PagePane p : pages) { count += countByType(p.getWidgets(), widgetTypes); } count = count + textbox_cnt; // don't forget our embedded scrollbars within textboxes if (count > 0) { strElement = "gslc_tsXSlider"; pw.printf("%-32sm_sXSlider[%d];%n", strElement, count); } } // output MAX String size strElement = "MAX_STR"; pw.printf("%n#define %-24s%d%n%n", strElement, maxstr_len); readPassString(GUI_END); } /** * Save ref section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void saveRefSection() throws IOException { pw.printf("%s%n",line); // save references to elements that may need quick access and while we are at it // save page enum for our quick access code generation section // quick access may be needed for progressbars, sliders, and text that is changed dynamically at runtime. for (PagePane p : pages) { for (Widget w : p.getWidgets()) { if (w.getType().equals(EnumFactory.TEXT)) { if (((TextModel)w.getModel()).getTextStorage() > 0) { refList.add(w.getModel()); w.getModel().setPageEnum(p.getEnum()); } } else if (w.getType().equals(EnumFactory.PROGRESSBAR) || w.getType().equals(EnumFactory.TEXTBOX) || w.getType().equals(EnumFactory.GRAPH) || w.getType().equals(EnumFactory.SLIDER)) { refList.add(w.getModel()); w.getModel().setPageEnum(p.getEnum()); } } } if (refList.size() > 0) { // we need to sort our model list in key value order Collections.sort(refList, new Comparator<WidgetModel>() { public int compare(WidgetModel one, WidgetModel other) { return one.getKey().compareTo(other.getKey()); } }); String ref = ""; for (WidgetModel m : refList) { if (m.getType().equals(EnumFactory.TEXT)) { ref = ((TextModel) m).getElementRef(); } else if (m.getType().equals(EnumFactory.PROGRESSBAR)) { ref = ((ProgressBarModel) m).getElementRef(); } else if (m.getType().equals(EnumFactory.TEXTBOX)) { ref = ((TextBoxModel) m).getElementRef(); } else if (m.getType().equals(EnumFactory.GRAPH)) { ref = ((GraphModel) m).getElementRef(); } else { // must be EnumFactory.SLIDER ref = ((SliderModel) m).getElementRef(); } pw.printf("gslc_tsElemRef* %-18s= NULL;%n", ref); } } readPassString(SAVEREF_END); } /** * Button cb section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void buttonCbSection() throws IOException { // create any callbacks for buttons in use List<WidgetModel> modelList = new ArrayList<WidgetModel>(); List<String> widgetTypes = new ArrayList<String>(); widgetTypes.add(EnumFactory.TEXTBUTTON); widgetTypes.add(EnumFactory.IMAGEBUTTON); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, modelList); } if (modelList.size() > 0) { outputButtonCB(modelList); while ((line = br.readLine()) != null) { if (line.equals(BUTTON_CB_END)) break; } } else { pw.printf("%s%n", BUTTON_CB_SECTION); readPassString(BUTTON_CB_END); } } /** * Slider cb section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void sliderCbSection() throws IOException { List<String> widgetTypes = new ArrayList<String>(); // create any call backs for sliders in use widgetTypes.clear(); widgetTypes.add(EnumFactory.SLIDER); widgetTypes.add(EnumFactory.TEXTBOX); List<String>enumList = getListOfEnums(widgetTypes); if (enumList.size() > 0) { outputCallback(enumList, SLIDER_ENUMS_SECTION, SLIDER_CB_TEMPLATE, SLIDER_LOOP_TEMPLATE); while ((line = br.readLine()) != null) { if (line.equals(SLIDER_CB_END)) break; } } else { pw.printf("%s%n", SLIDER_CB_SECTION); readPassString(SLIDER_CB_END); } } /** * Draw cb section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void drawCbSection() throws IOException { List<String> widgetTypes = new ArrayList<String>(); // how many draw boxes? List<WidgetModel> modelList = new ArrayList<WidgetModel>(); widgetTypes.clear(); widgetTypes.add(EnumFactory.BOX); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, modelList); } // now search the models for any BOX widget that has a callback. boolean bFoundDrawFunc = false; for (WidgetModel m : modelList) { if (((BoxModel) m).hasDrawFunc()) { bFoundDrawFunc = true; break; } } if (bFoundDrawFunc) { // only one draw function callback created no matter how many requested. //TODO - a better job some day List<String> templateLines = loadTemplate(DRAWBOX_CB_TEMPLATE); writeTemplate(templateLines); while ((line = br.readLine()) != null) { if (line.equals(DRAW_CB_END)) break; } } else { pw.printf("%s%n", DRAW_CB_SECTION); readPassString(DRAW_CB_END); } } /** * Tick cb section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void tickCbSection() throws IOException { List<String> widgetTypes = new ArrayList<String>(); // how many draw boxes? List<WidgetModel> modelList = new ArrayList<WidgetModel>(); widgetTypes.clear(); widgetTypes.add(EnumFactory.BOX); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, modelList); } // now search the models for any BOX widget that has a callback. boolean bFoundTickFunc = false; for (WidgetModel m : modelList) { if (((BoxModel) m).hasTickFunc()) { bFoundTickFunc = true; break; } } if (bFoundTickFunc) { // only one tick function callback created no matter how many requested. //TODO - a better job some day List<String> templateLines = loadTemplate(TICK_CB_TEMPLATE); writeTemplate(templateLines); while ((line = br.readLine()) != null) { if (line.equals(TICK_CB_END)) break; } } else { pw.printf("%s%n", TICK_CB_SECTION); readPassString(TICK_CB_END); } } /** * Initializes the GUI section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void initGUISection() throws IOException { pw.printf("%s%n",line); String strMaxElem = "MAX_ELEM_PG_MAIN"; String strMaxRam = "MAX_ELEM_PG_MAIN_RAM"; pw.printf(" gslc_PageAdd(&m_gui,%s,m_asMainElem,%s,m_asMainElemRef,%s);%n", pages.get(0).getEnum(), strMaxRam, strMaxElem); if (pages.size() > 1) { for (int i=1; i<pages.size(); i++) { strMaxElem = String.format("%s%d", "MAX_ELEM_PG_EXTRA", i); strMaxRam = String.format("%s%d", "MAX_ELEM_PG_EXTRA_RAM", i); pw.printf(" gslc_PageAdd(&m_gui,%s,m_asExtraElem,%s,m_asExtraElemRef,%s);%n", pages.get(i).getEnum(), strMaxRam, strMaxElem); } } // deal with background String color = cf.colorAsString(background); macro[0] = BACKGROUND_COLOR_MACRO; macro[1] = null; replacement[0] = color; List<String> templateLines = loadTemplate(BACKGROUND_TEMPLATE); List<String> outputLines = expandMacros(templateLines, macro, replacement); writeTemplate(outputLines); for (PagePane p : pages) { pw.printf("%n pw.printf(" // PAGE: %s%n", p.getEnum()); for (Widget w : p.getWidgets()) { outputAPI(p.getEnum(), w.getModel()); } } readPassString(INITGUI_END); } /** * Quick access section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void quickAccessSection() throws IOException { pw.printf("%s%n",line); // find text elements with storage if (refList.size() > 0) { String ref = ""; for (WidgetModel m : refList) { if (m.getType().equals(EnumFactory.TEXT)) { ref = ((TextModel) m).getElementRef(); } else if (m.getType().equals(EnumFactory.PROGRESSBAR)) { ref = ((ProgressBarModel) m).getElementRef(); } else if (m.getType().equals(EnumFactory.GRAPH)) { ref = ((GraphModel) m).getElementRef(); } else if (m.getType().equals(EnumFactory.TEXTBOX)) { ref = ((TextBoxModel) m).getElementRef(); } else { // must be EnumFactory.SLIDER ref = ((SliderModel) m).getElementRef(); } pw.printf(" %-18s= gslc_PageFindElemById(&m_gui,%s,%s);%n", ref,m.getPageEnum(),m.getEnum()); } } readPassString(QUICK_END); } /** * Load font section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void loadFontSection() throws IOException { pw.printf("%s%n",line); List<String> templateLines = loadTemplate(FONT_LOAD_TEMPLATE); List<String> outputLines; macro[0] = FONT_ID_MACRO; macro[1] = FONT_REFTYPE_MACRO; macro[2] = FONT_REF_MACRO; macro[3] = FONT_SZ_MACRO; macro[4] = null; for (FontItem f : fontList) { replacement[0] = f.getFontId(); replacement[1] = f.getFontRefType(); replacement[2] = f.getFontRef(); replacement[3] = f.getFontSz(); outputLines = expandMacros(templateLines, macro, replacement); writeTemplate(outputLines); } readPassString(LOADFONT_END); } /** * Button enums section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void buttonEnumsSection() throws IOException { pw.printf("%s%n",line); // build up a list of buttons in use List<WidgetModel> modelList = new ArrayList<WidgetModel>(); List<String> widgetTypes = new ArrayList<String>(); widgetTypes.add(EnumFactory.TEXTBUTTON); widgetTypes.add(EnumFactory.IMAGEBUTTON); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, modelList); } if (modelList.size() > 0) { List<String> templateStandard; List<String> templateChgPage; List<String> outputLines; List<String> scanLines = new ArrayList<String>(); // our callback section already exists - so pass it through storing each line output // so we can scan them next while((line = br.readLine()) != null) { if (line.equals(BUTTON_ENUMS_END)) break; scanLines.add(line); pw.printf("%s%n",line); } templateStandard = loadTemplate(BUTTON_LOOP_TEMPLATE); templateChgPage = loadTemplate(BUTTON_CHGPG_TEMPLATE); macro[0] = ENUM_MACRO; macro[1] = PAGE_ENUM_MACRO; macro[2] = null; for (WidgetModel m : modelList) { replacement[0] = m.getEnum(); replacement[1] = ""; // search our saved lines for this enum, if found skip it, otherwise expand the macros if (!searchForEnum(scanLines, replacement[0])) { if (m.getType().equals(EnumFactory.TEXTBUTTON)) { if (((TxtButtonModel)m).isChangePageFunct()) { replacement[1] = ((TxtButtonModel)m).getChangePageEnum(); outputLines = expandMacros(templateChgPage, macro, replacement); writeTemplate(outputLines); } else { outputLines = expandMacros(templateStandard, macro, replacement); writeTemplate(outputLines); } } else if (((ImgButtonModel)m).isChangePageFunct()) { replacement[1] = ((ImgButtonModel)m).getChangePageEnum(); outputLines = expandMacros(templateChgPage, macro, replacement); writeTemplate(outputLines); } else { outputLines = expandMacros(templateStandard, macro, replacement); writeTemplate(outputLines); } } } pw.printf("%s%n",BUTTON_ENUMS_END); return; } readPassString(BUTTON_ENUMS_END); } /** * Slider enums section. * * @throws IOException * Signals that an I/O exception has occurred. */ private void sliderEnumsSection() throws IOException { pw.printf("%s%n",line); // build up a list of sliders in use List<String> widgetTypes = new ArrayList<String>(); widgetTypes.add(EnumFactory.SLIDER); widgetTypes.add(EnumFactory.TEXTBOX); List<String>enumList = getListOfEnums(widgetTypes); if (enumList.size() >= 1) { List<String> templateLines; List<String> outputLines; List<String> scanLines = new ArrayList<String>(); // our callback section already exists - so pass it through storing each line output // so we can scan them next while((line = br.readLine()) != null) { if (line.equals(SLIDER_ENUMS_END)) break; scanLines.add(line); pw.printf("%s%n",line); } templateLines = loadTemplate(SLIDER_LOOP_TEMPLATE); macro[0] = ENUM_MACRO; macro[1] = null; for (int i=0; i<enumList.size(); i++) { replacement[0] = enumList.get(i); // search our saved lines for this enum, if found skip it, otherwise expand the macros if (!searchForEnum(scanLines, replacement[0])) { outputLines = expandMacros(templateLines, macro, replacement); writeTemplate(outputLines); } } pw.printf("%s%n",SLIDER_ENUMS_END); return; } readPassString(SLIDER_ENUMS_END); } // output API methods /** * Output API. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI(String pageEnum, WidgetModel m) { // System.out.println("outputAPI page: " + pageEnum + " widget: " + m.getType()); switch(m.getType()) { case "Box": if (targetPlatform == ARDUINO_MIN_PLATFORM) { outputAPI_Box_P(pageEnum, ((BoxModel)m)); } else { outputAPI_Box(pageEnum, ((BoxModel)m)); } break; case "CheckBox": if (targetPlatform == ARDUINO_MIN_PLATFORM) { outputAPI_CheckBox_P(pageEnum, ((CheckBoxModel)m)); } else { outputAPI_CheckBox(pageEnum, ((CheckBoxModel)m)); } break; case "Graph": outputAPI_Graph(pageEnum, ((GraphModel)m)); break; case "ImageButton": outputAPI_ImgButton(pageEnum, ((ImgButtonModel)m)); break; case "Image": outputAPI_Image(pageEnum, ((ImageModel)m)); break; case "ProgressBar": if (targetPlatform == ARDUINO_MIN_PLATFORM) { outputAPI_ProgressBar_P(pageEnum, ((ProgressBarModel)m)); } else { outputAPI_ProgressBar(pageEnum, ((ProgressBarModel)m)); } break; case "RadioButton": if (targetPlatform == ARDUINO_MIN_PLATFORM) { outputAPI_RadioButton_P(pageEnum, ((RadioButtonModel)m)); } else { outputAPI_RadioButton(pageEnum, ((RadioButtonModel)m)); } break; case "Slider": outputAPI_Slider(pageEnum, ((SliderModel)m)); break; case "Text": if (targetPlatform == ARDUINO_MIN_PLATFORM) { outputAPI_Text_P(pageEnum, ((TextModel)m)); } else { outputAPI_Text(pageEnum, ((TextModel)m)); } break; case "TextBox": outputAPI_TextBox(pageEnum, ((TextBoxModel)m)); break; case "TextButton": if (targetPlatform == ARDUINO_MIN_PLATFORM) { outputAPI_TxtButton_P(pageEnum, ((TxtButtonModel)m)); } else { outputAPI_TxtButton(pageEnum, ((TxtButtonModel)m)); } break; default: break; } } /** * Common API. * * @param pageEnum * the page enum * @param m * the m * @return the <code>int</code> object */ private int commonAPI(String pageEnum, WidgetModel m) { int n =0; // setup common attributes macro[n] = ENUM_MACRO; replacement[n++] = m.getEnum(); macro[n] = PAGE_ENUM_MACRO; replacement[n++] = pageEnum; macro[n] = X_MACRO; replacement[n++] = String.valueOf(m.getX()); macro[n] = Y_MACRO; replacement[n++] = String.valueOf(m.getY()); macro[n] = WIDTH_MACRO; replacement[n++] = String.valueOf(m.getWidth()); macro[n] = HEIGHT_MACRO; replacement[n++] = String.valueOf(m.getHeight()); return n; } /** * Output API box. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Box(String pageEnum, BoxModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = null; template = loadTemplate(BOX_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (m.hasDrawFunc()) { template = loadTemplate(DRAWFUNC_TEMPLATE); writeTemplate(template); } if (m.hasTickFunc()) { template = loadTemplate(TICKFUNC_TEMPLATE); writeTemplate(template); } if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API box P. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Box_P(String pageEnum, BoxModel m) { List<String> template = null; List<String> outputLines = null; String strDrawFunc = "NULL"; String strTickFunc = "NULL"; if (m.hasDrawFunc()) { strDrawFunc = "&CbDrawScanner"; } if (m.hasTickFunc()) { strTickFunc = "&CbTickScanner"; } int n = commonAPI(pageEnum, m); macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = DRAWFUNC_MACRO; replacement[n++] = strDrawFunc; macro[n] = TICKFUNC_MACRO; replacement[n++] = strTickFunc; macro[n] = null; template = loadTemplate(BOX_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } /** * Output API check box. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_CheckBox(String pageEnum, CheckBoxModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getMarkColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(m.isChecked()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countCheckBoxes); countCheckBoxes++; macro[n] = null; template = loadTemplate(CHECKBOX_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API check box P. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_CheckBox_P(String pageEnum, CheckBoxModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getMarkColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(m.isChecked()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countCheckBoxes); countCheckBoxes++; String groupId = m.getGroupId(); if (groupId.length() == 0) groupId = "GSLC_GROUP_ID_NONE"; macro[n] = GROUP_ID_MACRO; replacement[n++] = groupId; macro[n] = null; template = loadTemplate(CHECKBOX_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API graph. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Graph(String pageEnum, GraphModel m) { List<String> template = null; List<String> outputLines = null; String fontId = ""; String strKey = ""; String strCount = ""; int n = commonAPI(pageEnum, m); strKey = m.getKey(); int ts = strKey.indexOf("$"); strCount = strKey.substring(ts+1, strKey.length()); macro[n] = ID_MACRO; replacement[n++] = strCount; macro[n] = FONT_ID_MACRO; fontId = ff.getFontItem(m.getFontDisplayName()).getFontId(); replacement[n++] = fontId; macro[n] = STYLE_MACRO; switch(m.getGraphStyle()) { case "Dot": replacement[n++] = "GSLCX_GRAPH_STYLE_DOT"; break; case "Line": replacement[n++] = "GSLCX_GRAPH_STYLE_LINE"; break; case "Fill": replacement[n++] = "GSLCX_GRAPH_STYLE_FILL"; break; default: replacement[n++] = m.getGraphStyle(); break; } macro[n] = ROWS_MACRO; replacement[n++] = String.valueOf(m.getNumRows()); macro[n] = GRAPH_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getGraphColor()); macro[n] = null; template = loadTemplate(GRAPH_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API img button. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_ImgButton(String pageEnum, ImgButtonModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = IMAGE_MACRO; replacement[n++] = ((ImgButtonModel)m).getDefine(); macro[n] = IMAGE_SEL_MACRO; replacement[n++] = ((ImgButtonModel)m).getSelDefine(); macro[n] = IMAGE_FORMAT_MACRO; replacement[n++] = ((ImgButtonModel)m).getImageFormat(); macro[n] = null; template = loadTemplate(IMGBUTTON_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); // handle transparency n = 0; macro[n] = BOOL_MACRO; if (m.isTransparent()) replacement[n++] = "false"; else replacement[n++] = "true"; macro[n] = null; template = loadTemplate(IMAGETRANSPARENT_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } /** * Output API image. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Image(String pageEnum, ImageModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = IMAGE_MACRO; replacement[n++] = m.getDefine(); macro[n] = IMAGE_FORMAT_MACRO; replacement[n++] = m.getImageFormat(); macro[8] = null; template = loadTemplate(IMAGE_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); // handle transparency n = 0; macro[n] = BOOL_MACRO; if (m.isTransparent()) replacement[n++] = "false"; else replacement[n++] = "true"; macro[n] = null; template = loadTemplate(IMAGETRANSPARENT_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } /** * Output API progress bar. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_ProgressBar(String pageEnum, ProgressBarModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(((ProgressBarModel)m).getIndicatorColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).isVertical()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countGauges); countGauges++; macro[n] = MIN_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).getMin()); macro[n] = MAX_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).getMax()); macro[n] = VALUE_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).getValue()); macro[n] = null; template = loadTemplate(PROGRESSBAR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (m.isRampStyle()) { pw.printf(" gslc_ElemXGaugeSetStyle(&m_gui,pElemRef,GSLCX_GAUGE_STYLE_RAMP);%n"); } if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API progress bar P. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_ProgressBar_P(String pageEnum, ProgressBarModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(((ProgressBarModel)m).getIndicatorColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).isVertical()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countGauges); countGauges++; macro[n] = MIN_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).getMin()); macro[n] = MAX_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).getMax()); macro[n] = VALUE_MACRO; replacement[n++] = String.valueOf(((ProgressBarModel)m).getValue()); macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = null; template = loadTemplate(PROGRESSBAR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (m.isRampStyle()) { pw.printf(" gslc_ElemXGaugeSetStyle(&m_gui,pElemRef,GSLCX_GAUGE_STYLE_RAMP);%n"); } } /** * Output AP I radio button. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_RadioButton(String pageEnum, RadioButtonModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getMarkColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(m.isChecked()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countCheckBoxes); countCheckBoxes++; macro[n] = null; template = loadTemplate(RADIOBUTTON_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } String groupId = ((RadioButtonModel)m).getGroupId(); if (groupId.length() > 0) { n=0; macro[n] = GROUP_ID_MACRO; replacement[n++] = groupId; macro[n] = null; template = loadTemplate(GROUP_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API radio button P. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_RadioButton_P(String pageEnum, RadioButtonModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getMarkColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(m.isChecked()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countCheckBoxes); countCheckBoxes++; String groupId = m.getGroupId(); if (groupId.length() == 0) groupId = "GSLC_GROUP_ID_NONE"; macro[n] = GROUP_ID_MACRO; replacement[n++] = groupId; macro[n] = null; template = loadTemplate(RADIOBUTTON_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (!m.useDefaultColors()) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } /** * Output API slider. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Slider(String pageEnum, SliderModel m) { List<String> template = null; List<String> outputLines = null; int n = commonAPI(pageEnum, m); macro[n] = MARK_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getTickColor()); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(m.isVertical()); macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countSliders); countSliders++; macro[n] = MIN_MACRO; replacement[n++] = String.valueOf(m.getMin()); macro[n] = MAX_MACRO; replacement[n++] = String.valueOf(m.getMax()); macro[n] = VALUE_MACRO; replacement[n++] = String.valueOf(m.getValue()); macro[n] = STYLE_MACRO; replacement[n++] = String.valueOf(m.isTrimStyle()); macro[n] = TRIM_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getTrimColor()); macro[n] = DIVISIONS_MACRO; replacement[n++] = String.valueOf(m.getDivisions()); macro[n] = TICKSZ_MACRO; replacement[n++] = String.valueOf(m.getTickSize()); macro[n] = THUMBSZ_MACRO; replacement[n++] = String.valueOf(m.getThumbSize()); macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(SLIDER_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } /** * Output API text. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Text(String pageEnum, TextModel m) { String templateFile = null; List<String> template = null; List<String> outputLines = null; String fontId = ""; String strKey = ""; String strCount = ""; String strText = ""; int n =0; // setup common attributes macro[n] = ENUM_MACRO; replacement[n++] = m.getEnum(); macro[n] = PAGE_ENUM_MACRO; replacement[n++] = pageEnum; macro[n] = X_MACRO; replacement[n++] = String.valueOf(m.getX()); macro[n] = Y_MACRO; replacement[n++] = String.valueOf(m.getY()); macro[n] = WIDTH_MACRO; replacement[n++] = String.valueOf(m.getTargetWidth()); macro[n] = HEIGHT_MACRO; replacement[n++] = String.valueOf(m.getTargetHeight()); macro[n] = FONT_ID_MACRO; fontId = ff.getFontItem(m.getFontDisplayName()).getFontId(); replacement[n++] = fontId; macro[n] = FONT_COUNT_MACRO; replacement[n++] = String.valueOf(getFontIndex(fontId)); int ts = m.getTextStorage(); if (ts > 0) { macro[n] = SIZE_MACRO; replacement[n++] = String.valueOf(ts+1); // leave room for trailing '\0' in C Language macro[n] = TEXT_MACRO; strText = m.getText(); if (strText.length() > ts) strText = strText.substring(0, ts); replacement[n++] = strText; strKey = m.getKey(); ts = strKey.indexOf("$"); strCount = strKey.substring(ts+1, strKey.length()); macro[n] = ID_MACRO; replacement[n++] = strCount; templateFile = TEXT_UPDATE_TEMPLATE; } else { macro[n] = TEXT_MACRO; replacement[n++] = m.getText(); templateFile = TEXT_TEMPLATE; } macro[n] = null; template = loadTemplate(templateFile); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); String strAlign = m.getAlignment(); if (!strAlign.equals("Left")) { macro[0] = TEXT_ALIGN_MACRO; replacement[0] = convertAlignment(strAlign); macro[n] = null; template = loadTemplate(ALIGN_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } if (!m.useDefaultColors()) { if (!cf.getDefTextCol().equals(m.getTextColor())) { macro[0] = TEXT_COLOR_MACRO; replacement[0] = cf.colorAsString(m.getTextColor()); macro[n] = null; template = loadTemplate(TEXTCOLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } if (!cf.getDefFillCol().equals(m.getFillColor()) || !cf.getDefFrameCol().equals(m.getFrameColor()) || !cf.getDefGlowCol().equals(m.getSelectedColor())) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } if (m.isUTF8()) { pw.printf(" gslc_ElemSetTxtEnc(&m_gui,pElemRef,GSLC_TXT_ENC_UTF8);%n"); } if (!m.isFillEnabled()) { pw.printf(" gslc_ElemSetFillEn(&m_gui,pElemRef,false);%n"); } } /** * Output API text P. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_Text_P(String pageEnum, TextModel m) { String templateFile = null; List<String> template = null; List<String> outputLines = null; String fontId = ""; String strKey = ""; String strCount = ""; String strText = ""; int n =0; // setup common attributes macro[n] = ENUM_MACRO; replacement[n++] = m.getEnum(); macro[n] = PAGE_ENUM_MACRO; replacement[n++] = pageEnum; macro[n] = X_MACRO; replacement[n++] = String.valueOf(m.getX()); macro[n] = Y_MACRO; replacement[n++] = String.valueOf(m.getY()); macro[n] = WIDTH_MACRO; replacement[n++] = String.valueOf(m.getTargetWidth()); macro[n] = HEIGHT_MACRO; replacement[n++] = String.valueOf(m.getTargetHeight()); macro[n] = FONT_ID_MACRO; fontId = ff.getFontItem(m.getFontDisplayName()).getFontId(); replacement[n++] = fontId; macro[n] = FONT_COUNT_MACRO; replacement[n++] = String.valueOf(getFontIndex(fontId)); macro[n] = TEXT_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getTextColor()); macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = TEXT_ALIGN_MACRO; replacement[n++] = convertAlignment(m.getAlignment()); macro[n] = TEXT_MACRO; int ts = m.getTextStorage(); if (ts > 0) { macro[n] = SIZE_MACRO; replacement[n++] = String.valueOf(ts+1); // leave room for trailing '\0' in C Language macro[n] = TEXT_MACRO; strText = m.getText(); if (strText.length() > ts) strText = strText.substring(0, ts); replacement[n++] = strText; strKey = m.getKey(); ts = strKey.indexOf("$"); strCount = strKey.substring(ts+1, strKey.length()); macro[n] = ID_MACRO; replacement[n++] = strCount; templateFile = TEXT_UPDATE_TEMPLATE; } else { macro[n] = TEXT_MACRO; replacement[n++] = m.getText(); templateFile = TEXT_TEMPLATE; } macro[n] = null; template = loadTemplate(templateFile); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (m.isUTF8()) { pw.printf(" gslc_ElemSetTxtEnc(&m_gui,pElemRef,GSLC_TXT_ENC_UTF8);%n"); } if (!m.isFillEnabled()) { pw.printf(" gslc_ElemSetFillEn(&m_gui,pElemRef,false);%n"); } } /** * Output API text box. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_TextBox(String pageEnum, TextBoxModel m) { List<String> template = null; List<String> outputLines = null; String fontId = ""; String strKey = ""; String strCount = ""; int n = commonAPI(pageEnum, m); macro[n] = CHECKED_MACRO; replacement[n++] = String.valueOf(((TextBoxModel)m).wrapText()); strKey = m.getKey(); int tb = strKey.indexOf("$"); strCount = strKey.substring(tb+1, strKey.length()); macro[n] = ID_MACRO; replacement[n++] = strCount; macro[n] = COUNT_MACRO; replacement[n++] = String.valueOf(countSliders); countSliders++; macro[n] = ROWS_MACRO; replacement[n++] = String.valueOf(((TextBoxModel)m).getNumTextRows()); macro[n] = COLS_MACRO; replacement[n++] = String.valueOf(((TextBoxModel)m).getNumTextColumns()); macro[n] = FONT_ID_MACRO; fontId = ff.getFontItem(((TextBoxModel)m).getFontDisplayName()).getFontId(); replacement[n++] = fontId; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(TEXTBOX_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } /** * Output API txt button. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_TxtButton(String pageEnum, TxtButtonModel m) { List<String> template = null; List<String> outputLines = null; String fontId = ""; int n = commonAPI(pageEnum, m); macro[n] = FONT_ID_MACRO; fontId = ff.getFontItem(m.getFontDisplayName()).getFontId(); replacement[n++] = fontId; macro[n] = FONT_COUNT_MACRO; replacement[n++] = String.valueOf(getFontIndex(fontId)); macro[n] = TEXT_MACRO; replacement[n++] = m.getText(); macro[n] = null; template = loadTemplate(TXTBUTTON_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (!m.useDefaultColors()) { if (!cf.getDefTextCol().equals(m.getTextColor())) { macro[0] = TEXT_COLOR_MACRO; replacement[0] = cf.colorAsString(m.getTextColor()); macro[n] = null; template = loadTemplate(TEXTCOLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } if (!cf.getDefFillCol().equals(m.getFillColor()) || !cf.getDefFrameCol().equals(m.getFrameColor()) || !cf.getDefGlowCol().equals(m.getSelectedColor())) { n = 0; macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(COLOR_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); } } if (m.isUTF8()) { pw.printf(" gslc_ElemSetTxtEnc(&m_gui,pElemRef,GSLC_TXT_ENC_UTF8);%n"); } } /** * Output API txt button P. * * @param pageEnum * the page enum * @param m * the m */ private void outputAPI_TxtButton_P(String pageEnum, TxtButtonModel m) { List<String> template = null; List<String> outputLines = null; String fontId = ""; int n = commonAPI(pageEnum, m); macro[n] = FONT_ID_MACRO; fontId = ff.getFontItem(m.getFontDisplayName()).getFontId(); replacement[n++] = fontId; macro[n] = FONT_COUNT_MACRO; replacement[n++] = String.valueOf(getFontIndex(fontId)); macro[n] = TEXT_MACRO; replacement[n++] = m.getText(); macro[n] = TEXT_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getTextColor()); macro[n] = FILL_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFillColor()); macro[n] = FRAME_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getFrameColor()); macro[n] = GLOW_COLOR_MACRO; replacement[n++] = cf.colorAsString(m.getSelectedColor()); macro[n] = null; template = loadTemplate(TXTBUTTON_TEMPLATE); outputLines = expandMacros(template, macro, replacement); writeTemplate(outputLines); if (m.isUTF8()) { pw.printf(" gslc_ElemSetTxtEnc(&m_gui,pElemRef,GSLC_TXT_ENC_UTF8);%n"); } } /** * Output button CB. * * @param mList * the m list */ private void outputButtonCB(List<WidgetModel> mList) { if (mList.size() >= 1) { List<String> templateLines; List<String> templateStandard; List<String> templateChgPage; List<String> outputLines; String t = ""; int n =0; // create our callback section - start by opening our templates templateLines = loadTemplate(BUTTON_CB_TEMPLATE); for(int i=0; i<templateLines.size(); i++) { t = templateLines.get(i); pw.printf("%s%n", t); if (t.equals(BUTTON_ENUMS_SECTION)) { n = i; break; } } templateStandard = loadTemplate(BUTTON_LOOP_TEMPLATE); templateChgPage = loadTemplate(BUTTON_CHGPG_TEMPLATE); macro[0] = ENUM_MACRO; macro[1] = PAGE_ENUM_MACRO; macro[2] = null; for (WidgetModel m : mList) { replacement[0] = m.getEnum(); replacement[1] = ""; if (m.getType().equals(EnumFactory.TEXTBUTTON)) { if (((TxtButtonModel)m).isChangePageFunct()) { replacement[1] = ((TxtButtonModel)m).getChangePageEnum(); outputLines = expandMacros(templateChgPage, macro, replacement); writeTemplate(outputLines); } else { outputLines = expandMacros(templateStandard, macro, replacement); writeTemplate(outputLines); } } else if (((ImgButtonModel)m).isChangePageFunct()) { replacement[1] = ((ImgButtonModel)m).getChangePageEnum(); outputLines = expandMacros(templateChgPage, macro, replacement); writeTemplate(outputLines); } else { outputLines = expandMacros(templateStandard, macro, replacement); writeTemplate(outputLines); } } for(int j=n+1; j<templateLines.size(); j++) { pw.printf("%s%n", templateLines.get(j)); } } } /** * Output callback. * * @param eList * the e list * @param section * the section * @param cbTemplate * the cb template * @param loopTemplate * the loop template */ private void outputCallback(List<String> eList , String section, String cbTemplate, String loopTemplate) { if (eList.size() >= 1) { List<String> templateLines; List<String> loopLines; List<String> outputLines; String t = ""; int n =0; // create our callback section - start by opening our templates templateLines = loadTemplate(cbTemplate); for(int i=0; i<templateLines.size(); i++) { t = templateLines.get(i); pw.printf("%s%n", t); if (t.equals(section)) { n = i; break; } } loopLines = loadTemplate(loopTemplate); macro[0] = ENUM_MACRO; macro[1] = null; for (int e=0; e<eList.size(); e++) { replacement[0] = eList.get(e); outputLines = expandMacros(loopLines, macro, replacement); writeTemplate(outputLines); } for(int j=n+1; j<templateLines.size(); j++) { pw.printf("%s%n", templateLines.get(j)); } } } //Utility methods /** * Gets the list of enums. * * @param widgetTypes * the widget types * @return the list of enums */ private List<String> getListOfEnums(List<String> widgetTypes) { // build up a list of widgets that match List<String> eList = new ArrayList<String>(); List<WidgetModel> mList = new ArrayList<WidgetModel>(); for (PagePane p : pages) { getModelsByType(p.getWidgets(), widgetTypes, mList); } // now pull out from the models our matching widget's enums String ref = ""; String strKey = ""; String strCount = ""; int n; for (WidgetModel m : mList) { if (m.getType().equals(EnumFactory.TEXTBOX)) { // textbox has an embedded scrollbar so add it not TextBox ref = "E_SCROLLBAR"; strKey = m.getKey(); n = strKey.indexOf("$"); strCount = strKey.substring(n+1, strKey.length()); ref = ref + strCount; eList.add(ref); } else { eList.add(m.getEnum()); } } if (eList.size() > 1) { Collections.sort(eList); } return eList; } /** * Search for enum. * * @param lines * the lines * @param search * the search * @return <code>true</code>, if successful */ private boolean searchForEnum(List<String> lines, String search) { int n = 0; for(String l : lines) { n = l.indexOf(search); if (n >= 0) return true; } return false; } /** * Copy file. * * @param inFile * the in file * @param outFile * the out file */ public void copyFile(File inFile, File outFile) { InputStream inStream = null; OutputStream outStream = null; try{ inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); // System.out.println("File is copied successfully!"); }catch(IOException e){ e.printStackTrace(); } } /** * Read pass string. * * @param endString * the end string * @throws IOException * Signals that an I/O exception has occurred. */ private void readPassString(String endString) throws IOException { while ((line = br.readLine()) != null) { if (line.equals(endString)) break; } pw.printf("%s%n",endString); } /** * Load template. * * @param templateName * the template name * @return the <code>list</code> object */ private List<String> loadTemplate(String templateName) { Integer idx = Integer.valueOf(0); // always return something... if (templateMap.containsKey(templateName)) { idx = templateMap.get(templateName); } else { List<String> retErr = new ArrayList<String>(); retErr.add(new String("Missing template: " + templateName)); } return listOfTemplates[idx.intValue()]; } /** * Store templates. * * @param templateFileName * the template file name */ private void storeTemplates(String templateFileName) { templateMap = new HashMap<String, Integer>(64); String pathName = RESOURCES_PATH + templateFileName; BufferedReader tbr = new BufferedReader(new InputStreamReader( this.getClass().getResourceAsStream(pathName))); String l = ""; String templateName = ""; int i = 0; try { while((templateName = tbr.readLine()) != null) { if (templateName.equals(END_TEMPLATE)) break; List<String> lines = new ArrayList<String>(); while (!(l = tbr.readLine()).equals(STOP_TEMPLATE)) { lines.add(l); } templateMap.put(templateName, i); listOfTemplates[i] = lines; // System.out.println("Stored Template: " + templateName + " idx=" + i); i++; } } catch (IOException e) { e.printStackTrace(); } finally { try { tbr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Expand macros. * * @param lines * the lines * @param search * the search * @param replace * the replace * @return the <code>list</code> object */ private List<String> expandMacros(List<String> lines, String[] search, String[] replace) { List<String> outputList = new ArrayList<String>(); String l = ""; String r = ""; boolean bFoundMatch = false; for (int i=0; i<lines.size(); i++) { l = lines.get(i); r = new String(); String tokens[] = l.split("[$]"); for (String t : tokens) { bFoundMatch = false; for (int j=0; search[j]!=null; j++) { if(t.equals(search[j])) { r = r + replace[j]; bFoundMatch = true; break; } } if (!bFoundMatch) r = r + t; } outputList.add(r); } return outputList; } /** * Write template. * * @param lines * the lines */ private void writeTemplate(List<String> lines) { for (String l : lines) pw.printf("%s%n", l); } /** * Gets the widget models by type. * * @param widgets * the widgets * @param widgetTypes * the widget types * @param selected * the selected * @return the models by type */ private void getModelsByType(List<Widget> widgets, List<String> widgetTypes, List<WidgetModel> selected) { for (Widget w : widgets) { for (String type : widgetTypes) { if (w.getType().equals(type)) { selected.add(w.getModel()); } } } } /** * Count by type. * * @param widgets * the widgets * @param widgetTypes * the widget types * @return the <code>int</code> object */ private int countByType(List<Widget> widgets, List<String> widgetTypes) { int count = 0; for (Widget w : widgets) { for (String type : widgetTypes) { if (w.getType().equals(type)) { count++; } } } return count; } /** * Sort list and remove duplicates. * * @param list * the list */ private void sortListandRemoveDups(List<String> list) { if (list.size() > 1) { Collections.sort(list); String s = null; String prev = null; ListIterator<String> litr = list.listIterator(); while(litr.hasNext()) { s = litr.next(); if (s.equals(prev)) litr.remove(); else prev = s; } } } /** * Prints the enums. * * @param enumList * the enum list */ private void printEnums(List<String> enumList) { for (int i=0; i<enumList.size(); i++) { if (i%4 == 0 && i != 0) printState=OVERFLOW_LINE; switch (printState) { case BEGIN_LINE: pw.printf("enum {%s", enumList.get(i)); printState = WRITE_NEXT; break; case WRITE_NEXT: pw.printf(",%s", enumList.get(i)); break; case OVERFLOW_LINE: pw.printf("%n ,%s", enumList.get(i)); printState = WRITE_NEXT; break; } } pw.printf("};%n"); printState = BEGIN_LINE; return; } /** * getFontIndex() - scan fontList for fontId and return its index in the list. * * @param fontId * the font id * @return index */ private int getFontIndex(String fontId) { int i = 0; for (FontItem f : fontList) { if (f.getFontId().equals(fontId)) { break; } i++; } return i; } /** * Convert alignment. * * @param align * the align * @return the <code>string</code> object */ private String convertAlignment(String align) { switch (align) { case "Left": return "GSLC_ALIGN_MID_LEFT"; case "Center": return "GSLC_ALIGN_MID_MID"; case "Right": return "GSLC_ALIGN_MID_RIGHT"; default: return "UNKOWN_ALIGNMENT"; } } }
package icap_samplecode; import java.io.*; import java.net.Socket; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Map; import java.util.HashMap; class ICAP { private static final Charset StandardCharsetsUTF8 = Charset.forName("UTF-8"); private static final int BUFFER_SIZE = 32 * 1024; private static final int STD_RECIEVE_LENGTH = 8192; private static final int STD_SEND_LENGTH = 8192; private static final String VERSION = "1.0"; private static final String USERAGENT = "IT-Kartellet ICAP Client/1.1"; private static final String ICAPTERMINATOR = "\r\n\r\n"; private static final String HTTPTERMINATOR = "0\r\n\r\n"; private String serverIP; private int port; private Socket client; private DataOutputStream out; private DataInputStream in; private String icapService; private int stdPreviewSize; private String tempString; /** * Initializes the socket connection and IO streams. It asks the server for the available options and * changes settings to match it. * @param serverIP The IP address to connect to. * @param port The port in the host to use. * @param icapService The service to use (fx "avscan"). * @throws IOException * @throws ICAPException */ public ICAP(String serverIP, int port, String icapService) throws IOException, ICAPException{ this.icapService = icapService; this.serverIP = serverIP; this.port = port; //Initialize connection client = new Socket(serverIP, port); //Openening out stream OutputStream outToServer = client.getOutputStream(); out = new DataOutputStream(new BufferedOutputStream(outToServer, BUFFER_SIZE)); //Openening in stream InputStream inFromServer = client.getInputStream(); in = new DataInputStream(inFromServer); String parseMe = getOptions(); Map<String,String> responseMap = parseHeader(parseMe); if (responseMap.get("StatusCode") != null){ int status = Integer.parseInt(responseMap.get("StatusCode")); switch (status){ case 200: tempString = responseMap.get("Preview"); if (tempString != null){ stdPreviewSize=Integer.parseInt(tempString); };break; default: throw new ICAPException("Could not get preview size from server"); } } else{ throw new ICAPException("Could not get options from server"); } } /** * Initializes the socket connection and IO streams. This overload doesn't * use getOptions(), instead a previewSize is specified. * @param s The IP address to connect to. * @param p The port in the host to use. * @param icapService The service to use (fx "avscan"). * @param previewSize Amount of bytes to send as preview. * @throws IOException * @throws ICAPException */ public ICAP(String s,int p, String icapService, int previewSize) throws IOException, ICAPException{ this.icapService = icapService; serverIP = s; port = p; //Initialize connection client = new Socket(serverIP, port); //Openening out stream OutputStream outToServer = client.getOutputStream(); out = new DataOutputStream(outToServer); //Openening in stream InputStream inFromServer = client.getInputStream(); in = new DataInputStream(inFromServer); stdPreviewSize = previewSize; } /** * Given a filepath, it will send the file to the server and return true, * if the server accepts the file. Visa-versa, false if the server rejects it. * @param filename Relative or absolute filepath to a file. * @return Returns true when no infection is found. */ public boolean scanFile(String filename) throws IOException,ICAPException{ File file = new File(filename); try(InputStream inputStream = new FileInputStream(file)) { return scanFile(inputStream, file.length()); } } public boolean scanFile(InputStream fileInStream, long fileSize) throws IOException,ICAPException{ //First part of header String resBody = "Content-Length: "+fileSize+"\r\n\r\n"; int previewSize = stdPreviewSize; if (fileSize < stdPreviewSize){ previewSize = (int) fileSize; } String requestBuffer = "RESPMOD icap://"+serverIP+"/"+icapService+" ICAP/"+VERSION+"\r\n" +"Host: "+serverIP+"\r\n" +"User-Agent: "+USERAGENT+"\r\n" +"Allow: 204\r\n" +"Preview: "+previewSize+"\r\n" +"Encapsulated: res-hdr=0, res-body="+resBody.length()+"\r\n" +"\r\n" +resBody +Integer.toHexString(previewSize) +"\r\n"; sendString(requestBuffer); //Sending preview or, if smaller than previewSize, the whole file. byte[] chunk = new byte[previewSize]; fileInStream.read(chunk); sendBytes(chunk); sendString("\r\n"); if (fileSize<=previewSize){ sendString("0; ieof\r\n\r\n", true); } else if (previewSize != 0){ sendString("0\r\n\r\n", true); } // Parse the response! It might not be "100 continue" // if fileSize<previewSize, then this is acutally the respond // otherwise it is a "go" for the rest of the file. Map<String,String> responseMap = new HashMap<String,String>(); int status; if (fileSize>previewSize){ String parseMe = getHeader(ICAPTERMINATOR); responseMap = parseHeader(parseMe); tempString = responseMap.get("StatusCode"); if (tempString != null){ status = Integer.parseInt(tempString); switch (status){ case 100: break; //Continue transfer case 200: return false; case 204: return true; case 404: throw new ICAPException("404: ICAP Service not found"); default: throw new ICAPException("Server returned unknown status code:"+status); } } } //Sending remaining part of file if (fileSize > previewSize){ byte[] buffer = new byte[STD_SEND_LENGTH]; while ((fileInStream.read(buffer)) != -1) { sendString(Integer.toHexString(buffer.length) +"\r\n"); sendBytes(buffer); sendString("\r\n"); } //Closing file transfer. requestBuffer = "0\r\n\r\n"; sendString(requestBuffer, true); } responseMap.clear(); String response = getHeader(ICAPTERMINATOR); responseMap = parseHeader(response); tempString=responseMap.get("StatusCode"); if (tempString != null){ status = Integer.parseInt(tempString); if (status == 204){return true;} //Unmodified if (status == 200){ //OK - The ICAP status is ok, but the encapsulated HTTP status will likely be different response = getHeader(HTTPTERMINATOR); int x = response.indexOf("<title>",0); int y = response.indexOf("</title>",x); String statusCode = response.substring(x+7,y); if (statusCode.equals("ProxyAV: Access Denied")){ return false; } } } throw new ICAPException("Unrecognized or no status code in response header."); } /** * Automatically asks for the servers available options and returns the raw response as a String. * @return String of the servers response. * @throws IOException * @throws ICAPException */ private String getOptions() throws IOException, ICAPException{ //Send OPTIONS header and receive response //Sending and recieving String requestHeader = "OPTIONS icap://"+serverIP+"/"+icapService+" ICAP/"+VERSION+"\r\n" + "Host: "+serverIP+"\r\n" + "User-Agent: "+USERAGENT+"\r\n" + "Encapsulated: null-body=0\r\n" + "\r\n"; sendString(requestHeader, true); return getHeader(ICAPTERMINATOR); } /** * Receive an expected ICAP header as response of a request. The returned String should be parsed with parseHeader() * @param terminator * @return String of the raw response * @throws IOException * @throws ICAPException */ private String getHeader(String terminator) throws IOException, ICAPException{ byte[] endofheader = terminator.getBytes(StandardCharsetsUTF8); byte[] buffer = new byte[STD_RECIEVE_LENGTH]; int n; int offset=0; //STD_RECIEVE_LENGTH-offset is replaced by '1' to not receive the next (HTTP) header. while((offset < STD_RECIEVE_LENGTH) && ((n = in.read(buffer, offset, 1)) != -1)) { // first part is to secure against DOS offset += n; if (offset>endofheader.length+13){ // 13 is the smallest possible message "ICAP/1.0 xxx " byte[] lastBytes = Arrays.copyOfRange(buffer, offset-endofheader.length, offset); if (Arrays.equals(endofheader,lastBytes)){ return new String(buffer,0,offset, StandardCharsetsUTF8); } } } throw new ICAPException("Error in getHeader() method"); } /** * Given a raw response header as a String, it will parse through it and return a HashMap of the result * @param response A raw response header as a String. * @return HashMap of the key,value pairs of the response */ private Map<String,String> parseHeader(String response){ Map<String,String> headers = new HashMap<>(); // The status code is located between the first 2 whitespaces. // Read status code int x = response.indexOf(" ",0); int y = response.indexOf(" ",x+1); String statusCode = response.substring(x+1,y); headers.put("StatusCode", statusCode); // Each line in the sample is ended with "\r\n". // When (i+2==response.length()) The end of the header have been reached. // The +=2 is added to skip the "\r\n". // Read headers int i = response.indexOf("\r\n",y); i+=2; while (i+2!=response.length() && response.substring(i).contains(":")) { int n = response.indexOf(":",i); String key = response.substring(i, n); n += 2; i = response.indexOf("\r\n",n); String value = response.substring(n, i); headers.put(key, value); i+=2; } return headers; } /** * Sends a String through the socket connection. Used for sending ICAP/HTTP headers. * @param requestHeader * @throws IOException */ private void sendString(String requestHeader) throws IOException { sendString(requestHeader, false); } /** * Sends a String through the socket connection. Used for sending ICAP/HTTP headers. * @param requestHeader * @param withFlush * @throws IOException */ private void sendString(String requestHeader, boolean withFlush) throws IOException{ out.write(requestHeader.getBytes(StandardCharsetsUTF8)); if (withFlush) { out.flush(); } } /** * Sends bytes of data from a byte-array through the socket connection. Used to send filedata. * @param chunk The byte-array to send. * @throws IOException */ private void sendBytes(byte[] chunk) throws IOException{ for (byte aChunk : chunk) { out.write(aChunk); } } /** * Terminates the socket connecting to the ICAP server. * @throws IOException */ private void disconnect() throws IOException{ if(client != null) { client.close(); } } @Override protected void finalize() throws Throwable { try { disconnect(); } finally { super.finalize(); } } }
package ch.elexis.core.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.CompletableFuture; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.FormToolkit; import ch.elexis.core.ui.preferences.ConfigServicePreferenceStore; import ch.elexis.core.ui.preferences.ConfigServicePreferenceStore.Scope; import ch.rgw.tools.ExHandler; import ch.rgw.tools.StringTool; public class UiDesk { private static FormToolkit theToolkit = null; private static Display theDisplay = null; private static ImageRegistry theImageRegistry = null; private static ColorRegistry theColorRegistry = null; private static HashMap<String, Cursor> cursors = null; public static final String COL_RED = "rot"; //$NON-NLS-1$ public static final String COL_GREEN = "gruen"; //$NON-NLS-1$ public static final String COL_DARKGREEN = "dunkelgruen"; //$NON-NLS-1$ public static final String COL_BLUE = "blau"; //$NON-NLS-1$ public static final String COL_SKYBLUE = "himmelblau"; //$NON-NLS-1$ public static final String COL_LIGHTBLUE = "hellblau"; //$NON-NLS-1$ public static final String COL_BLACK = "schwarz"; //$NON-NLS-1$ public static final String COL_GREY = "grau"; //$NON-NLS-1$ public static final String COL_WHITE = "weiss"; //$NON-NLS-1$ public static final String COL_DARKGREY = "dunkelgrau"; //$NON-NLS-1$ public static final String COL_LIGHTGREY = "hellgrau"; //$NON-NLS-1$ public static final String COL_GREY60 = "grau60"; //$NON-NLS-1$ public static final String COL_GREY20 = "grau20"; //$NON-NLS-1$ public static final String CUR_HYPERLINK = "cursor_hyperlink"; //$NON-NLS-1$ public static ImageRegistry getImageRegistry() { if (theImageRegistry == null) { theImageRegistry = new ImageRegistry(getDisplay()); synchronized (theImageRegistry) { } } return theImageRegistry; } /** * Return an image with a specified name. This method is applicable for images * only, that has been registered beforehand. The default images resp. icons are * delivered by a separate plugin (in the core this is ch.elexis.core.ui.icons) * * @param name the name of the image to retrieve * @return the Image or null if no such image was found * * @since 3.0.0 will only serve pre-registered icons, <b>default icons have been * outsourced</b> */ public static Image getImage(String name) { Image ret = getImageRegistry().get(name); if (ret == null) { ImageDescriptor id = getImageRegistry().getDescriptor(name); if (id != null) { ret = id.createImage(); } } return ret; } /** shortcut for getColorRegistry().get(String col) */ public static Color getColor(String desc) { return getColorRegistry().get(desc); } public static ColorRegistry getColorRegistry() { if (theColorRegistry == null) { theColorRegistry = new ColorRegistry(getDisplay(), true); } return theColorRegistry; } public static FormToolkit getToolkit() { if (theToolkit == null) { theToolkit = new FormToolkit(getDisplay()); } return theToolkit; } public static Display getDisplay() { if (theDisplay == null) { if (PlatformUI.isWorkbenchRunning()) { theDisplay = PlatformUI.getWorkbench().getDisplay(); } } if (theDisplay == null) { theDisplay = PlatformUI.createDisplay(); } return theDisplay; } public static void updateFont(String cfgName) { FontRegistry fr = JFaceResources.getFontRegistry(); FontData[] fd = PreferenceConverter.getFontDataArray(new ConfigServicePreferenceStore(Scope.USER), cfgName); fr.put(cfgName, fd); } public static Font getFont(String cfgName) { FontRegistry fr = JFaceResources.getFontRegistry(); if (!fr.hasValueFor(cfgName)) { FontData[] fd = PreferenceConverter.getFontDataArray(new ConfigServicePreferenceStore(Scope.USER), cfgName); fr.put(cfgName, fd); } return fr.get(cfgName); } public static Font getFont(String name, int height, int style) { String key = name + ":" + Integer.toString(height) + ":" + Integer.toString(style); //$NON-NLS-1$ //$NON-NLS-2$ FontRegistry fr = JFaceResources.getFontRegistry(); if (!fr.hasValueFor(key)) { FontData[] fd = new FontData[] { new FontData(name, height, style) }; fr.put(key, fd); } return fr.get(key); } public static Cursor getCursor(String name) { if (cursors == null) { cursors = new HashMap<String, Cursor>(); } Cursor ret = cursors.get(name); if (ret == null) { if (name.equals(CUR_HYPERLINK)) { ret = getDisplay().getSystemCursor(SWT.CURSOR_HAND); cursors.put(name, ret); } } return ret; } /** * Eine Color aus einer RGB-Beschreibung als Hex-String herstellen * * @param coldesc Die Farbe als Beschreibung in Hex-Form * @return die Farbe als Color, ist in Regisry gespeichert */ public static Color getColorFromRGB(final String coldesc) { String col = StringTool.pad(StringTool.LEFT, '0', coldesc, 6); if (!getColorRegistry().hasValueFor(col)) { RGB rgb; try { rgb = new RGB(Integer.parseInt(col.substring(0, 2), 16), Integer.parseInt(col.substring(2, 4), 16), Integer.parseInt(col.substring(4, 6), 16)); } catch (NumberFormatException nex) { ExHandler.handle(nex); rgb = new RGB(100, 100, 100); } getColorRegistry().put(col, rgb); } return getColorRegistry().get(col); } /** * Eine Hex-String Beschreibung einer Farbe liefern * * @param rgb Die Farbe in RGB-Form * @return */ public static String createColor(final RGB rgb) { try { StringBuilder sb = new StringBuilder(); sb.append(StringTool.pad(StringTool.LEFT, '0', Integer.toHexString(rgb.red), 2)) .append(StringTool.pad(StringTool.LEFT, '0', Integer.toHexString(rgb.green), 2)) .append(StringTool.pad(StringTool.LEFT, '0', Integer.toHexString(rgb.blue), 2)); String srgb = sb.toString(); getColorRegistry().put(srgb, rgb); return srgb; } catch (NumberFormatException nex) { getColorRegistry().put("A0A0A0", new RGB(0xa0, 0xa0, 0xa0)); //$NON-NLS-1$ return "A0A0A0"; //$NON-NLS-1$ } } public static Shell getTopShell() { return getDisplay().getActiveShell(); } /** * Run a runnable asynchroneously in the UI Thread The method will immediately * return (not wait for the runnable to exit) */ public static void asyncExec(Runnable runnable) { Display disp = getDisplay(); if (!disp.isDisposed()) { disp.asyncExec(runnable); } } /** * Run a runnable synchroneously in the UI Thread. The method will not return * until the runnable exited * * @param runnable */ public static void syncExec(Runnable runnable) { getDisplay().syncExec(runnable); // BusyIndicator.showWhile(getDisplay(), runnable); } private static List<Runnable> waitForWorkbench; public synchronized static void runIfWorkbenchRunning(Runnable runnable) { if (!PlatformUI.isWorkbenchRunning()) { if (waitForWorkbench == null) { CompletableFuture.runAsync(() -> { // wait for running workbench while (!PlatformUI.isWorkbenchRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { // ignore } } waitForWorkbench.forEach(r -> r.run()); }); waitForWorkbench = new ArrayList<>(); } waitForWorkbench.add(runnable); } else { runnable.run(); } } }
package ch.softappeal.yass.core.remote.session; import ch.softappeal.yass.core.remote.Client; import ch.softappeal.yass.core.remote.ExceptionReply; import ch.softappeal.yass.core.remote.Message; import ch.softappeal.yass.core.remote.Reply; import ch.softappeal.yass.core.remote.Request; import ch.softappeal.yass.core.remote.Server; import ch.softappeal.yass.util.Check; import ch.softappeal.yass.util.Closer; import ch.softappeal.yass.util.Exceptions; import ch.softappeal.yass.util.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public abstract class Session extends Client implements Closer { public final Connection connection; protected Session(final Connection connection) { this.connection = Check.notNull(connection); } /** * Called if a session has been opened. * Must call {@link Runnable#run()} (possibly in an own thread). */ protected abstract void dispatchOpened(Runnable runnable) throws Exception; /** * Called for an incoming request. * Must call {@link Runnable#run()} (possibly in an own thread). */ protected abstract void dispatchServerInvoke(Server.Invocation invocation, Runnable runnable) throws Exception; private Server server; /** * Gets the server of this session. Called only once after creation of session. * This implementation returns {@link Server#EMPTY}. */ protected Server server() throws Exception { return Server.EMPTY; } /** * Called when the session has been opened. * This implementation does nothing. * Due to race conditions or exceptions it could not be called or be called after {@link #closed(Exception)}. * @see SessionFactory#create(Connection) */ protected void opened() throws Exception { // empty } /** * Called once when the session has been closed. * This implementation does nothing. * @param exception if (exception == null) regular close else reason for close * @see SessionFactory#create(Connection) */ protected void closed(final @Nullable Exception exception) throws Exception { // empty } private final AtomicBoolean closed = new AtomicBoolean(true); public final boolean isClosed() { return closed.get(); } private void unblockPromises() { final List<Invocation> invocations = new ArrayList<>(requestNumber2invocation.values()); for (final Invocation invocation : invocations) { try { invocation.settle(new ExceptionReply(new SessionClosedException())); } catch (final Exception ignore) { // empty } } } private void close(final boolean sendEnd, final @Nullable Exception exception) { if (closed.getAndSet(true)) { return; } try { try { try { unblockPromises(); } finally { closed(exception); } if (sendEnd) { connection.write(Packet.END); } } finally { connection.closed(); } } catch (final Exception e) { throw Exceptions.wrap(e); } } /** * Must be called if communication has failed. * This method is idempotent. */ public static void close(final Session session, final Exception e) { session.close(false, Check.notNull(e)); } @Override public void close() { close(true, null); } private void serverInvoke(final int requestNumber, final Request request) throws Exception { final Server.Invocation invocation = server.invocation(true, request); dispatchServerInvoke(invocation, () -> { try { invocation.invoke(reply -> { if (!invocation.methodMapping.oneWay) { try { connection.write(new Packet(requestNumber, reply)); } catch (final Exception e) { close(this, e); } } }); } catch (final Exception e) { close(this, e); } }); } /** * note: it's not worth to use {@link ConcurrentHashMap} here */ private final Map<Integer, Invocation> requestNumber2invocation = Collections.synchronizedMap(new HashMap<>(16)); private void received(final Packet packet) throws Exception { try { if (packet.isEnd()) { close(false, null); return; } final Message message = packet.message(); if (message instanceof Request) { serverInvoke(packet.requestNumber(), (Request)message); } else { requestNumber2invocation.remove(packet.requestNumber()).settle((Reply)message); // client invoke } } catch (final Exception e) { close(this, e); throw e; } } /** * Must be called if a packet has been received. * It must also be called if {@link Packet#isEnd()}; however, it must not be called again after that. */ public static void received(final Session session, final Packet packet) throws Exception { session.received(packet); } private final AtomicInteger nextRequestNumber = new AtomicInteger(Packet.END_REQUEST_NUMBER); @Override protected final void invoke(final Client.Invocation invocation) throws Exception { if (isClosed()) { throw new SessionClosedException(); } invocation.invoke(true, request -> { try { int requestNumber; do { // we can't use END_REQUEST_NUMBER as regular requestNumber requestNumber = nextRequestNumber.incrementAndGet(); } while (requestNumber == Packet.END_REQUEST_NUMBER); if (!invocation.methodMapping.oneWay) { requestNumber2invocation.put(requestNumber, invocation); if (isClosed()) { unblockPromises(); // needed due to race conditions } } connection.write(new Packet(requestNumber, request)); } catch (final Exception e) { close(this, e); throw e; } }); } private void created() { closed.set(false); try { server = Check.notNull(server()); dispatchOpened(() -> { try { opened(); } catch (final Exception e) { close(this, e); } }); } catch (final Exception e) { close(this, e); } } public static Session create(final SessionFactory sessionFactory, final Connection connection) throws Exception { final Session session = sessionFactory.create(connection); session.created(); return session; } }
// $Id: OutputStreamLogSink.java,v 1.4 2004/09/19 08:04:57 gregwilkins Exp $ package org.openqa.jetty.log; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.TimeZone; import org.openqa.jetty.util.ByteArrayISO8859Writer; import org.openqa.jetty.util.DateCache; import org.openqa.jetty.util.MultiException; import org.openqa.jetty.util.RolloverFileOutputStream; import org.openqa.jetty.util.StringBufferWriter; import org.openqa.jetty.util.StringUtil; /** A Log sink. * This class represents both a concrete or abstract sink of * Log data. The default implementation logs to System.err, but * other output stream or files may be specified. * * Currently this Stream only writes in ISO8859_1 encoding. For * Other encodings use the less efficient WriterLogSink. * * If a logFilename is specified, output is sent to that file. * If the filename contains "yyyy_mm_dd", the log file date format * is used to create the actual filename and the log file is rolled * over at local midnight. * If append is set, existing logfiles are appended to, otherwise * a backup is created with a timestamp. * Dated log files are deleted after retain days. * * <p> If the property LOG_DATE_FORMAT is set, then it is interpreted * as a format string for java.text.SimpleDateFormat and used to * format the log timestamps. Default value: HH:mm:ss.SSS * * <p> If LOG_TIMEZONE is set, it is used to set the timezone of the log date * format, otherwise GMT is used. * * @see org.openqa.jetty.util.LogSupport * @version $Id: OutputStreamLogSink.java,v 1.4 2004/09/19 08:04:57 gregwilkins Exp $ * @author Greg Wilkins (gregw) */ public class OutputStreamLogSink implements LogSink { private final static String __lineSeparator = System.getProperty("line.separator"); private int _retainDays=31; protected DateCache _dateFormat= new DateCache("HH:mm:ss.SSS"); protected String _logTimezone; protected boolean _logTimeStamps=true; protected boolean _logLabels=true; protected boolean _logTags=true; protected boolean _logStackSize=true; protected boolean _logStackTrace=false; protected boolean _logOneLine=false; protected boolean _suppressStack=false; private String _filename; private boolean _append=true; protected boolean _flushOn=true; protected int _bufferSize=2048; protected boolean _reopen=false; protected transient LogImpl _logImpl=null; protected transient boolean _started; protected transient OutputStream _out; protected transient ByteArrayISO8859Writer _buffer; /** Constructor. */ public OutputStreamLogSink() throws IOException { _filename=System.getProperty("LOG_FILE"); if (_filename==null) _out=LogStream.STDERR_STREAM; } public OutputStreamLogSink(String filename) { _filename=filename; } public String getLogDateFormat() { return _dateFormat.getFormatString(); } public void setLogDateFormat(String logDateFormat) { _dateFormat = new DateCache(logDateFormat); if (_logTimezone!=null) _dateFormat.getFormat().setTimeZone(TimeZone.getTimeZone(_logTimezone)); } /** * @deprecated Use getLogTimeZone() */ public String getLogTimezone() { return _logTimezone; } /** * @deprecated Use setLogTimeZone(String) */ public void setLogTimezone(String logTimezone) { _logTimezone=logTimezone; if (_dateFormat!=null && _logTimezone!=null) _dateFormat.getFormat().setTimeZone(TimeZone.getTimeZone(_logTimezone)); } public String getLogTimeZone() { return _logTimezone; } public void setLogTimeZone(String logTimezone) { _logTimezone=logTimezone; if (_dateFormat!=null && _logTimezone!=null) _dateFormat.getFormat().setTimeZone(TimeZone.getTimeZone(_logTimezone)); } public boolean isLogTimeStamps() { return _logTimeStamps; } public void setLogTimeStamps(boolean logTimeStamps) { _logTimeStamps = logTimeStamps; } public boolean isLogLabels() { return _logLabels; } public void setLogLabels(boolean logLabels) { _logLabels = logLabels; } public boolean isLogTags() { return _logTags; } public void setLogTags(boolean logTags) { _logTags = logTags; } public boolean isLogStackSize() { return _logStackSize; } public void setLogStackSize(boolean logStackSize) { _logStackSize = logStackSize; } public boolean isLogStackTrace() { return _logStackTrace; } public void setLogStackTrace(boolean logStackTrace) { _logStackTrace = logStackTrace; } public boolean isLogOneLine() { return _logOneLine; } public void setLogOneLine(boolean logOneLine) { _logOneLine = logOneLine; } public boolean isAppend() { return _append; } public void setAppend(boolean a) { _append=a; } public boolean isSuppressStack() { return _suppressStack; } public void setSuppressStack(boolean suppressStack) { _suppressStack = suppressStack; } public synchronized void setOutputStream(OutputStream out) { _reopen=isStarted() && out!=out; _filename=null; if (_buffer!=null) _buffer.resetWriter(); _out=out; } public OutputStream getOutputStream() { return _out; } public synchronized void setFilename(String filename) { if (filename!=null) { filename=filename.trim(); if (filename.length()==0) filename=null; } if (isStarted() && _filename!=null && filename==null) _out=null; _reopen=isStarted() && ((_filename==null && filename!=null)|| (_filename!=null && !_filename.equals(filename))); _filename=filename; if (!isStarted() && _filename!=null) _out=null; } public String getFilename() { return _filename; } public String getDatedFilename() { if (_filename==null) return null; if (_out==null || ! (_out instanceof RolloverFileOutputStream)) return null; return ((RolloverFileOutputStream)_out).getDatedFilename(); } public int getRetainDays() { return _retainDays; } public void setRetainDays(int retainDays) { _reopen=isStarted() && _retainDays!=retainDays; _retainDays = retainDays; } /** * @param on If true, log is flushed on every log. */ public void setFlushOn(boolean on) { _flushOn=on; if (on && _out!=null) { try{_out.flush();} catch(IOException e){e.printStackTrace();} } } /** * @return true, log is flushed on every log. */ public boolean getFlushOn() { return _flushOn; } /** Log a message. * This method formats the log information as a string and calls * log(String). It should only be specialized by a derived * implementation if the format of the logged messages is to be changed. * * @param tag Tag for type of log * @param o The message * @param frame The frame that generated the message. * @param time The time stamp of the message. */ public synchronized void log(String tag, Object o, Frame frame, long time) { StringBuffer buf = new StringBuffer(160); // Log the time stamp if (_logTimeStamps) { buf.append(_dateFormat.format(time)); buf.append(' '); } // Log the tag if (_logTags) buf.append(tag); // Log the label if (_logLabels && frame != null) { buf.append(frame.toString()); } // Log the stack depth. if (_logStackSize && frame != null) { buf.append(" >"); if (frame.getDepth()<10) buf.append('0'); buf.append(Integer.toString(frame.getDepth())); buf.append("> "); } // Determine the indent string for the message and append it // to the buffer. Only put a newline in the buffer if the first // line is not blank String nl=__lineSeparator; if (_logLabels && !_logOneLine && _buffer.size() > 0) buf.append(nl); // Log message formatObject(buf,o); // Add stack frame to message if (_logStackTrace && frame != null) { buf.append(nl); buf.append(frame.getStack()); } log(buf.toString()); } /** Log a message. * The formatted log string is written to the log sink. The default * implementation writes the message to an outputstream. * @param formattedLog */ public synchronized void log(String formattedLog) { if (_reopen || _out==null) { stop(); start(); } try { _buffer.write(formattedLog); _buffer.write(StringUtil.__LINE_SEPARATOR); if (_flushOn || _buffer.size()>_bufferSize) { _buffer.writeTo(_out); _buffer.resetWriter(); _out.flush(); } } catch(IOException e){e.printStackTrace();} } /** Start a log sink. * The default implementation does nothing */ public synchronized void start() { _buffer=new ByteArrayISO8859Writer(_bufferSize); _reopen=false; if (_started) return; if (_out==null && _filename!=null) { try { RolloverFileOutputStream rfos= new RolloverFileOutputStream(_filename,_append,_retainDays); _out=rfos; } catch(IOException e){e.printStackTrace();} } if (_out==null) _out=LogStream.STDERR_STREAM; _started=true; } /** Stop a log sink. * An opportunity for subclasses to clean up. The default * implementation does nothing */ public synchronized void stop() { _started=false; if (_out!=null) { try { if (_buffer.size()>0) { _buffer.writeTo(_out); } _out.flush(); _buffer=null; } catch(Exception e){if (_logImpl!=null && _logImpl.getDebug())e.printStackTrace();} Thread.yield(); } if (_out!=null && _out!=LogStream.STDERR_STREAM) { try{_out.close();} catch(Exception e){if (_logImpl!=null && _logImpl.getDebug())e.printStackTrace();} } if (_filename!=null) _out=null; } public boolean isStarted() { return _started; } /* (non-Javadoc) * @see org.openqa.jetty.log.LogSink#setLogImpl(org.openqa.jetty.log.LogImpl) */ public void setLogImpl(LogImpl impl) { _logImpl=impl; } private static final Class[] __noArgs=new Class[0]; private static final String[] __nestedEx = {"getTargetException","getTargetError","getException","getRootCause"}; /** Shared static instances, reduces object creation at expense * of lock contention in multi threaded debugging */ private static StringBufferWriter __stringBufferWriter = new StringBufferWriter(); private static PrintWriter __printWriter = new PrintWriter(__stringBufferWriter); void formatObject(StringBuffer buf,Object o) { int init_size=buf.length(); if (o==null) buf.append("null"); else if (o.getClass().isArray()) { int l=Array.getLength(o); for (int i=0;i<l;i++) formatObject(buf,Array.get(o,i)); } else if (o instanceof Throwable) { Throwable ex = (Throwable) o; buf.append('\n'); if (_suppressStack) { buf.append(ex.toString()); buf.append("\nNo stack available\n } else { synchronized(__printWriter) { __stringBufferWriter.setStringBuffer(buf); expandThrowable(ex); __printWriter.flush(); } } } else buf.append(o.toString()); int end_size=buf.length(); if (_logOneLine) { for (int i=init_size;i<end_size;i++) { char c=buf.charAt(i); if (c=='\n') buf.setCharAt(i,'|'); else if (c=='\r') buf.setCharAt(i,'<'); } } } private static void expandThrowable(Throwable ex) { ex.printStackTrace(__printWriter); if (ex instanceof MultiException) { MultiException mx = (MultiException)ex; for (int i=0;i<mx.size();i++) { __printWriter.print("["+i+"]="); Throwable ex2=mx.getException(i); expandThrowable(ex2); } } else { for (int i=0;i<__nestedEx.length;i++) { try { Method getTargetException = ex.getClass().getMethod(__nestedEx[i],__noArgs); Throwable ex2=(Throwable)getTargetException.invoke(ex,(java.lang.Object[])null); if (ex2!=null) { __printWriter.println(__nestedEx[i]+"():"); expandThrowable(ex2); } } catch(Exception ignore){} } } } };
package javaslang.collection; import javaslang.Value; import org.junit.Ignore; import org.junit.Test; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.*; import java.util.stream.Stream; import static javaslang.collection.Comparators.naturalComparator; public class TreeSetTest extends AbstractSortedSetTest { @Override protected <T> Collector<T, ArrayList<T>, ? extends TreeSet<T>> collector() { return TreeSet.collector(naturalComparator()); } @Override protected <T> TreeSet<T> empty() { return TreeSet.empty(toStringComparator()); } @Override protected boolean emptyShouldBeSingleton() { return false; } @Override protected <T> TreeSet<T> of(T element) { return TreeSet.of(toStringComparator(), element); } @SuppressWarnings("varargs") @SafeVarargs @Override protected final <T> TreeSet<T> of(T... elements) { boolean allLongs = true; boolean allNumbers = true; for (T element : elements) { if (!(element instanceof Number)) { allNumbers = false; } if (!(element instanceof Long)) { allLongs = false; } } if (allLongs) { return TreeSet.ofAll(toLongComparator(), Iterator.of(elements)); } else if (allNumbers) { return TreeSet.ofAll(toDoubleComparator(), Iterator.of(elements)); } else { return TreeSet.ofAll(toStringComparator(), Iterator.of(elements)); } } @Override protected <T> TreeSet<T> ofAll(Iterable<? extends T> elements) { return TreeSet.ofAll(toStringComparator(), elements); } @Override protected <T> TreeSet<T> ofJavaStream(Stream<? extends T> javaStream) { return TreeSet.ofAll(toStringComparator(), javaStream); } @Override protected TreeSet<Boolean> ofAll(boolean[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Byte> ofAll(byte[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Character> ofAll(char[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Double> ofAll(double[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Float> ofAll(float[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Integer> ofAll(int[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Long> ofAll(long[] array) { return TreeSet.ofAll(array); } @Override protected TreeSet<Short> ofAll(short[] array) { return TreeSet.ofAll(array); } @Override protected <T> TreeSet<T> tabulate(int n, Function<? super Integer, ? extends T> f) { return TreeSet.tabulate(toStringComparator(), n, f); } @Override protected <T> TreeSet<T> fill(int n, Supplier<? extends T> s) { return TreeSet.fill(toStringComparator(), n, s); } @Override protected boolean useIsEqualToInsteadOfIsSameAs() { return true; } @Override protected int getPeekNonNilPerformingAnAction() { return 1; } // -- static narrow @Test public void shouldNarrowTreeSet() { final TreeSet<Double> doubles = of(1.0d); final TreeSet<Number> numbers = TreeSet.narrow(doubles); final int actual = numbers.add(new BigDecimal("2.0")).sum().intValue(); assertThat(actual).isEqualTo(3); } // -- addAll @Test public void shouldKeepComparator() { List<?> list = TreeSet.empty(inverseIntComparator()).addAll(TreeSet.of(1, 2, 3)).toList(); assertThat(list).isEqualTo(List.of(3, 2, 1)); } // -- transform() @Test public void shouldTransform() { String transformed = of(42).transform(v -> String.valueOf(v.get())); assertThat(transformed).isEqualTo("42"); } // -- helpers private static Comparator<Integer> inverseIntComparator() { return (i1, i2) -> Integer.compare(i2, i1); } static Comparator<Object> toStringComparator() { return (Comparator<Object> & Serializable) (o1, o2) -> String.valueOf(o1).compareTo(String.valueOf(o2)); } private static <T> Comparator<T> toDoubleComparator() { return (Comparator<T> & Serializable) (o1, o2) -> { Double n1 = ((Number) o1).doubleValue(); Double n2 = ((Number) o2).doubleValue(); return n1.compareTo(n2); }; } private static <T> Comparator<T> toLongComparator() { return (Comparator<T> & Serializable) (o1, o2) -> { Long n1 = ((Number) o1).longValue(); Long n2 = ((Number) o2).longValue(); return n1.compareTo(n2); }; } @Override protected TreeSet<Character> range(char from, char toExclusive) { return TreeSet.range(from, toExclusive); } @Override protected TreeSet<Character> rangeBy(char from, char toExclusive, int step) { return TreeSet.rangeBy(from, toExclusive, step); } @Override protected TreeSet<Double> rangeBy(double from, double toExclusive, double step) { return TreeSet.rangeBy(from, toExclusive, step); } @Override protected TreeSet<Integer> range(int from, int toExclusive) { return TreeSet.range(from, toExclusive); } @Override protected TreeSet<Integer> rangeBy(int from, int toExclusive, int step) { return TreeSet.rangeBy(from, toExclusive, step); } @Override protected TreeSet<Long> range(long from, long toExclusive) { return TreeSet.range(from, toExclusive); } @Override protected TreeSet<Long> rangeBy(long from, long toExclusive, long step) { return TreeSet.rangeBy(from, toExclusive, step); } @Override protected TreeSet<Character> rangeClosed(char from, char toInclusive) { return TreeSet.rangeClosed(from, toInclusive); } @Override protected TreeSet<Character> rangeClosedBy(char from, char toInclusive, int step) { return TreeSet.rangeClosedBy(from, toInclusive, step); } @Override protected TreeSet<Double> rangeClosedBy(double from, double toInclusive, double step) { return TreeSet.rangeClosedBy(from, toInclusive, step); } @Override protected TreeSet<Integer> rangeClosed(int from, int toInclusive) { return TreeSet.rangeClosed(from, toInclusive); } @Override protected TreeSet<Integer> rangeClosedBy(int from, int toInclusive, int step) { return TreeSet.rangeClosedBy(from, toInclusive, step); } @Override protected TreeSet<Long> rangeClosed(long from, long toInclusive) { return TreeSet.rangeClosed(from, toInclusive); } @Override protected TreeSet<Long> rangeClosedBy(long from, long toInclusive, long step) { return TreeSet.rangeClosedBy(from, toInclusive, step); } // -- toSortedSet @Test public void shouldReturnSelfOnConvertToSortedSet() { Value<Integer> value = of(1, 2, 3); assertThat(value.toSortedSet()).isSameAs(value); } @Test public void shouldReturnSelfOnConvertToSortedSetWithSameComparator() { TreeSet<Integer> value = of(1, 2, 3); assertThat(value.toSortedSet(value.comparator())).isSameAs(value); } @Test public void shouldNotReturnSelfOnConvertToSortedSetWithDifferentComparator() { Value<Integer> value = of(1, 2, 3); assertThat(value.toSortedSet(Integer::compareTo)).isSameAs(value); } @Test public void shouldPreserveComparatorOnConvertToSortedSetWithoutDistinctComparator() { Value<Integer> value = TreeSet.of(Comparators.naturalComparator().reversed(), 1, 2, 3); assertThat(value.toSortedSet().mkString(",")).isEqualTo("3,2,1"); } }
public class SatEnum { public enum WaterLevelEnum {low, normal, high} public static void main (String args[]) { assert WaterLevelEnum.low != null; } }
package php.runtime.ext.core.classes; import php.runtime.Memory; import php.runtime.env.Environment; import php.runtime.ext.core.classes.stream.Stream; import php.runtime.lang.BaseObject; import php.runtime.loader.RuntimeClassLoader; import php.runtime.memory.StringMemory; import php.runtime.reflection.ClassEntity; import java.io.*; import java.net.URL; import java.util.Map; import java.util.Properties; import static php.runtime.annotation.Reflection.*; @Name("php\\lang\\System") final public class WrapSystem extends BaseObject { public WrapSystem(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature private Memory __construct(Environment env, Memory... args) { return Memory.NULL; } @Signature(@Arg("status")) public static Memory halt(Environment env, Memory... args) { System.exit(args[0].toInteger()); return Memory.NULL; } @Signature({ @Arg("name"), @Arg(value = "def", optional = @Optional("")) }) public static Memory getProperty(Environment env, Memory... args) { return StringMemory.valueOf(System.getProperty(args[0].toString(), args[1].toString())); } @Signature public static String setProperty(String name, String value) { return System.setProperty(name, value); } @Signature @Name("getProperties") public static Properties getProperties1() { return System.getProperties(); } @Signature public static void setProperties(Properties properties) { System.setProperties(properties); } @Signature public static Map<String, String> getEnv() { return System.getenv(); } @Signature public static Memory gc(Environment env, Memory... args) { System.gc(); return Memory.NULL; } @Signature public static InputStream in() { return System.in; } @Signature public static OutputStream err() { return System.err; } @Signature public static OutputStream out() { return System.out; } @Signature public static void setIn(Environment env, @Arg(typeClass = "php\\io\\Stream", nullable = true) Memory stream) { if (stream.isNull()) { System.setIn(null); } else { System.setIn(Stream.getInputStream(env, stream)); } } @Signature public static void setOut(Environment env, @Arg(typeClass = "php\\io\\Stream", nullable = true) Memory stream) throws UnsupportedEncodingException { setOut(env, stream, Memory.NULL); } @Signature public static void setOut(Environment env, @Arg(typeClass = "php\\io\\Stream", nullable = true) Memory stream, Memory encoding) throws UnsupportedEncodingException { if (stream.isNull()) { System.setOut(null); } else { if (encoding.isNotNull()) { System.setOut(new PrintStream(Stream.getOutputStream(env, stream), true, encoding.toString())); } else { System.setOut(new PrintStream(Stream.getOutputStream(env, stream), true)); } } } @Signature public static void setErr(Environment env, @Arg(typeClass = "php\\io\\Stream", nullable = true) Memory stream) throws UnsupportedEncodingException { setOut(env, stream, Memory.NULL); } @Signature public static void setErr(Environment env, @Arg(typeClass = "php\\io\\Stream", nullable = true) Memory stream, Memory encoding) throws UnsupportedEncodingException { if (stream.isNull()) { System.setErr(null); } else { if (encoding.isNotNull()) { System.setErr(new PrintStream(Stream.getOutputStream(env, stream), true, encoding.toString())); } else { System.setErr(new PrintStream(Stream.getOutputStream(env, stream), true)); } } } @Signature public static String tempDirectory() { return System.getProperty("java.io.tmpdir"); } @Signature public static String userHome() { return System.getProperty("user.home"); } @Signature public static String userDirectory() { return System.getProperty("user.dir"); } @Signature public static String userName() { return System.getProperty("user.name"); } @Signature public static String osName() { return System.getProperty("os.name"); } @Signature public static String osVersion() { return System.getProperty("os.version"); } @Signature public static void addClassPath(Environment env, File file) throws IOException { try { env.getScope().getClassLoader().addLibrary(file.toURI().toURL()); } catch (Throwable t) { throw new IOException("Error, could not add URL to system classloader, " + t.getMessage()); } } }
package jsettlers.logic.map.newGrid; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import jsettlers.common.Color; import jsettlers.common.CommonConstants; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.EBuildingType.BuildingAreaBitSet; import jsettlers.common.buildings.IBuilding; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.landscape.EResourceType; import jsettlers.common.logging.MilliStopWatch; import jsettlers.common.logging.StopWatch; import jsettlers.common.map.IGraphicsBackgroundListener; import jsettlers.common.map.IGraphicsGrid; import jsettlers.common.map.IMapData; import jsettlers.common.map.object.BuildingObject; import jsettlers.common.map.object.MapObject; import jsettlers.common.map.object.MapStoneObject; import jsettlers.common.map.object.MapTreeObject; import jsettlers.common.map.object.MovableObject; import jsettlers.common.map.object.StackObject; import jsettlers.common.map.shapes.FreeMapArea; import jsettlers.common.map.shapes.HexGridArea; import jsettlers.common.map.shapes.HexGridArea.HexGridAreaIterator; import jsettlers.common.map.shapes.MapCircle; import jsettlers.common.map.shapes.MapNeighboursArea; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.mapobject.IMapObject; import jsettlers.common.material.EMaterialType; import jsettlers.common.material.ESearchType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EMovableType; import jsettlers.common.movable.IMovable; import jsettlers.common.player.IPlayerable; import jsettlers.common.position.RelativePoint; import jsettlers.common.position.ShortPoint2D; import jsettlers.graphics.map.UIState; import jsettlers.input.IGuiInputGrid; import jsettlers.logic.algorithms.borders.BordersThread; import jsettlers.logic.algorithms.borders.IBordersThreadGrid; import jsettlers.logic.algorithms.construction.IConstructionMarkableMap; import jsettlers.logic.algorithms.fogofwar.IFogOfWarGrid; import jsettlers.logic.algorithms.fogofwar.IViewDistancable; import jsettlers.logic.algorithms.fogofwar.NewFogOfWar; import jsettlers.logic.algorithms.landmarks.ILandmarksThreadGrid; import jsettlers.logic.algorithms.landmarks.NewLandmarkCorrection; import jsettlers.logic.algorithms.path.IPathCalculateable; import jsettlers.logic.algorithms.path.Path; import jsettlers.logic.algorithms.path.area.IInAreaFinderMap; import jsettlers.logic.algorithms.path.area.InAreaFinder; import jsettlers.logic.algorithms.path.astar.normal.HexAStar; import jsettlers.logic.algorithms.path.astar.normal.IAStar; import jsettlers.logic.algorithms.path.astar.normal.IAStarPathMap; import jsettlers.logic.algorithms.path.dijkstra.DijkstraAlgorithm; import jsettlers.logic.algorithms.path.dijkstra.IDijkstraPathMap; import jsettlers.logic.buildings.Building; import jsettlers.logic.buildings.IBuildingsGrid; import jsettlers.logic.buildings.military.IOccupyableBuilding; import jsettlers.logic.buildings.military.OccupyingBuilding; import jsettlers.logic.buildings.workers.WorkerBuilding; import jsettlers.logic.map.newGrid.flags.FlagsGrid; import jsettlers.logic.map.newGrid.landscape.LandscapeGrid; import jsettlers.logic.map.newGrid.movable.MovableGrid; import jsettlers.logic.map.newGrid.objects.AbstractHexMapObject; import jsettlers.logic.map.newGrid.objects.IMapObjectsManagerGrid; import jsettlers.logic.map.newGrid.objects.MapObjectsManager; import jsettlers.logic.map.newGrid.objects.ObjectsGrid; import jsettlers.logic.map.newGrid.partition.IPartitionableGrid; import jsettlers.logic.map.newGrid.partition.PartitionsGrid; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableBearer; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableBricklayer; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableDigger; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableWorker; import jsettlers.logic.map.newGrid.partition.manager.manageables.interfaces.IBarrack; import jsettlers.logic.map.newGrid.partition.manager.manageables.interfaces.IDiggerRequester; import jsettlers.logic.map.newGrid.partition.manager.manageables.interfaces.IMaterialRequester; import jsettlers.logic.map.save.MapFileHeader; import jsettlers.logic.map.save.MapFileHeader.MapType; import jsettlers.logic.map.save.MapList; import jsettlers.logic.newmovable.NewMovable; import jsettlers.logic.newmovable.interfaces.INewMovableGrid; import jsettlers.logic.stack.IRequestsStackGrid; import synchronic.timer.NetworkTimer; /** * This is the main grid offering an interface for interacting with the grid. * * @author Andreas Eberle */ public class MainGrid implements Serializable { private static final long serialVersionUID = 3824511313693431423L; final short width; final short height; final LandscapeGrid landscapeGrid; final ObjectsGrid objectsGrid; final PartitionsGrid partitionsGrid; final MovableGrid movableGrid; final FlagsGrid flagsGrid; final MovablePathfinderGrid movablePathfinderGrid; final MapObjectsManager mapObjectsManager; final BuildingsGrid buildingsGrid; final NewFogOfWar fogOfWar; transient IGraphicsGrid graphicsGrid; transient NewLandmarkCorrection landmarksCorrection; transient ConstructionMarksGrid constructionMarksGrid; transient BordersThread bordersThread; transient IGuiInputGrid guiInputGrid; public MainGrid(short width, short height) { this.width = width; this.height = height; this.movablePathfinderGrid = new MovablePathfinderGrid(); this.mapObjectsManager = new MapObjectsManager(new MapObjectsManagerGrid()); this.landscapeGrid = new LandscapeGrid(width, height); this.objectsGrid = new ObjectsGrid(width, height); this.movableGrid = new MovableGrid(width, height, landscapeGrid); this.flagsGrid = new FlagsGrid(width, height); this.partitionsGrid = new PartitionsGrid(width, height, new PartitionableGrid()); this.buildingsGrid = new BuildingsGrid(); this.fogOfWar = new NewFogOfWar(width, height); initAdditionalGrids(); } private void initAdditionalGrids() { this.graphicsGrid = new GraphicsGrid(); this.landmarksCorrection = new NewLandmarkCorrection(new LandmarksGrid()); this.constructionMarksGrid = new ConstructionMarksGrid(); this.bordersThread = new BordersThread(new BordersThreadGrid()); this.guiInputGrid = new GUIInputGrid(); this.fogOfWar.startThread(new FogOfWarGrid()); this.partitionsGrid.initPartitionsAlgorithm(movablePathfinderGrid.aStar); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); initAdditionalGrids(); } private MainGrid(IMapData mapGrid) { this((short) mapGrid.getWidth(), (short) mapGrid.getHeight()); for (short y = 0; y < height; y++) { for (short x = 0; x < width; x++) { ELandscapeType landscape = mapGrid.getLandscape(x, y); setLandscapeTypeAt(x, y, landscape); landscapeGrid.setHeightAt(x, y, mapGrid.getLandscapeHeight(x, y)); landscapeGrid.setResourceAt(x, y, mapGrid.getResourceType(x, y), mapGrid.getResourceAmount(x, y)); } } flagsGrid.calculateBlockedPartitions(); // tow passes, we might need the base grid tiles to add blocking, ... // status for (short y = 0; y < height; y++) { for (short x = 0; x < width; x++) { MapObject object = mapGrid.getMapObject(x, y); if (object != null && isOccupyableBuilding(object)) { addMapObject(x, y, object); } if ((x + y / 2) % 4 == 0 && y % 4 == 0 && isInsideWater(x, y)) { mapObjectsManager.addWaves(x, y); if (landscapeGrid.getResourceAmountAt(x, y) > 50) { mapObjectsManager.addFish(x, y); } } } } for (short y = 0; y < height; y++) { for (short x = 0; x < width; x++) { MapObject object = mapGrid.getMapObject(x, y); if (object != null && !isOccupyableBuilding(object)) { addMapObject(x, y, object); } } } System.out.println("grid filled"); } private static boolean isOccupyableBuilding(MapObject object) { return object instanceof BuildingObject && ((BuildingObject) object).getType().getOccupyerPlaces().length > 0; } private boolean isInsideWater(short x, short y) { return isWaterSafe(x - 1, y) && isWaterSafe(x, y) && isWaterSafe(x + 1, y) && isWaterSafe(x - 1, y + 1) && isWaterSafe(x, y + 1) && isWaterSafe(x + 1, y + 1) && isWaterSafe(x, y + 2) && isWaterSafe(x + 1, y + 2) && isWaterSafe(x + 2, y + 2); } private boolean isWaterSafe(int x, int y) { return isInBounds((short) x, (short) y) && landscapeGrid.getLandscapeTypeAt((short) x, (short) y).isWater(); } public void stopThreads() { bordersThread.cancel(); fogOfWar.cancel(); } public static MainGrid create(IMapData mapGrid) { return new MainGrid(mapGrid); } private void addMapObject(short x, short y, MapObject object) { ShortPoint2D pos = new ShortPoint2D(x, y); if (object instanceof MapTreeObject) { if (isInBounds(x, y) && movablePathfinderGrid.pathfinderGrid.isTreePlantable(x, y)) { mapObjectsManager.plantAdultTree(pos); } } else if (object instanceof MapStoneObject) { mapObjectsManager.addStone(pos, ((MapStoneObject) object).getCapacity()); } else if (object instanceof StackObject) { placeStack(pos, ((StackObject) object).getType(), ((StackObject) object).getCount()); } else if (object instanceof BuildingObject) { Building building = Building.getBuilding(((BuildingObject) object).getType(), ((BuildingObject) object).getPlayer()); building.appearAt(buildingsGrid, pos); if (building instanceof IOccupyableBuilding) { NewMovable soldier = createNewMovableAt(((IOccupyableBuilding) building).getDoor(), EMovableType.SWORDSMAN_L1, building.getPlayer()); soldier.setOccupyableBuilding((IOccupyableBuilding) building); } } else if (object instanceof MovableObject) { createNewMovableAt(pos, ((MovableObject) object).getType(), ((MovableObject) object).getPlayer()); } } public MapFileHeader generateSaveHeader() { // TODO: description // TODO: count alive players, count all players return new MapFileHeader(MapType.SAVED_SINGLE, "saved game", "TODO: description", width, height, (short) 1, (short) 1, new Date(), new short[MapFileHeader.PREVIEW_IMAGE_SIZE * MapFileHeader.PREVIEW_IMAGE_SIZE]); } private void placeStack(ShortPoint2D pos, EMaterialType materialType, int count) { for (int i = 0; i < count; i++) { movablePathfinderGrid.dropMaterial(pos, materialType, true); } } public IGraphicsGrid getGraphicsGrid() { return graphicsGrid; } public IGuiInputGrid getGuiInputGrid() { return guiInputGrid; } /** * FOR TESTS ONLY!! * * @return */ public IAStarPathMap getPathfinderGrid() { return movablePathfinderGrid.pathfinderGrid; } public final boolean isInBounds(short x, short y) { return x >= 0 && x < width && y >= 0 && y < height; } public final NewMovable createNewMovableAt(ShortPoint2D pos, EMovableType type, byte player) { NewMovable movable = new NewMovable(movablePathfinderGrid, type, pos, player); return movable; } private final boolean isLandscapeBlocking(ELandscapeType landscape) { return landscape.isWater() || landscape == ELandscapeType.MOOR || landscape == ELandscapeType.MOORINNER || landscape == ELandscapeType.SNOW; } protected final void setLandscapeTypeAt(short x, short y, ELandscapeType newType) { if (isLandscapeBlocking(newType)) { flagsGrid.setBlockedAndProtected(x, y, true); } else { if (isLandscapeBlocking(landscapeGrid.getLandscapeTypeAt(x, y))) { flagsGrid.setBlockedAndProtected(x, y, false); } } landscapeGrid.setLandscapeTypeAt(x, y, newType); } final class PathfinderGrid implements IAStarPathMap, IDijkstraPathMap, IInAreaFinderMap, Serializable { private static final long serialVersionUID = -2775530442375843213L; @Override public boolean isBlocked(IPathCalculateable requester, short x, short y) { return flagsGrid.isBlocked(x, y) || (requester.needsPlayersGround() && requester.getPlayer() != partitionsGrid.getPlayerAt(x, y)); } @Override public final float getCost(short sx, short sy, short tx, short ty) { // return Constants.TILE_PATHFINDER_COST * (flagsGrid.isProtected(sx, sy) ? 3.5f : 1); return 1; } @Override public final void markAsOpen(short x, short y) { landscapeGrid.setDebugColor(x, y, Color.BLUE.getARGB()); } @Override public final void markAsClosed(short x, short y) { landscapeGrid.setDebugColor(x, y, Color.RED.getARGB()); } @Override public final void setDijkstraSearched(short x, short y) { markAsOpen(x, y); } @Override public final boolean fitsSearchType(short x, short y, ESearchType searchType, IPathCalculateable pathCalculable) { switch (searchType) { case FOREIGN_GROUND: return !flagsGrid.isBlocked(x, y) && !hasSamePlayer(x, y, pathCalculable) && !partitionsGrid.isEnforcedByTower(x, y); case CUTTABLE_TREE: return isInBounds((short) (x - 1), (short) (y - 1)) && objectsGrid.hasCuttableObject((short) (x - 1), (short) (y - 1), EMapObjectType.TREE_ADULT) && hasSamePlayer((short) (x - 1), (short) (y - 1), pathCalculable) && !isMarked(x, y); case PLANTABLE_TREE: return y < height - 1 && isTreePlantable(x, (short) (y + 1)) && !hasProtectedNeighbor(x, (short) (y + 1)) && hasSamePlayer(x, (short) (y + 1), pathCalculable) && !isMarked(x, y); case PLANTABLE_CORN: return isCornPlantable(x, y) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y) && !flagsGrid.isProtected(x, y); case CUTTABLE_CORN: return isCornCuttable(x, y) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y); case CUTTABLE_STONE: return y + 1 < height && x - 1 < width && objectsGrid.hasCuttableObject((short) (x - 1), (short) (y + 1), EMapObjectType.STONE) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y); case ENEMY: { IMovable movable = movableGrid.getMovableAt(x, y); return movable != null && movable.getPlayer() != pathCalculable.getPlayer(); } case RIVER: return isRiver(x, y) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y); case FISHABLE: return hasSamePlayer(x, y, pathCalculable) && hasNeighbourLandscape(x, y, ELandscapeType.WATER1); case NON_BLOCKED_OR_PROTECTED: return !(flagsGrid.isProtected(x, y) || flagsGrid.isBlocked(x, y)) && (!pathCalculable.needsPlayersGround() || hasSamePlayer(x, y, pathCalculable)) && movableGrid.getMovableAt(x, y) == null; case SOLDIER_BOWMAN: return isSoldierAt(x, y, searchType, pathCalculable.getPlayer()); case SOLDIER_SWORDSMAN: return isSoldierAt(x, y, searchType, pathCalculable.getPlayer()); case SOLDIER_PIKEMAN: return isSoldierAt(x, y, searchType, pathCalculable.getPlayer()); case RESOURCE_SIGNABLE: return isInBounds(x, y) && !flagsGrid.isMarked(x, y) && canAddRessourceSign(x, y); case FOREIGN_MATERIAL: return isInBounds(x, y) && !hasSamePlayer(x, y, pathCalculable) && mapObjectsManager.hasStealableMaterial(x, y); default: System.err.println("can't handle search type in fitsSearchType(): " + searchType); return false; } } protected final boolean canAddRessourceSign(short x, short y) { return x % 2 == 0 && y % 2 == 0 && landscapeGrid.getLandscapeTypeAt(x, y) == ELandscapeType.MOUNTAIN && !(objectsGrid.hasMapObjectType(x, y, EMapObjectType.FOUND_COAL) || objectsGrid.hasMapObjectType(x, y, EMapObjectType.FOUND_IRON) || objectsGrid.hasMapObjectType(x, y, EMapObjectType.FOUND_GOLD)); } private final boolean isSoldierAt(short x, short y, ESearchType searchType, byte player) { NewMovable movable = movableGrid.getMovableAt(x, y); if (movable == null) { return false; } else { if (movable.getPlayer() == player && movable.canOccupyBuilding()) { EMovableType type = movable.getMovableType(); switch (searchType) { case SOLDIER_BOWMAN: return type == EMovableType.BOWMAN_L1 || type == EMovableType.BOWMAN_L2 || type == EMovableType.BOWMAN_L3; case SOLDIER_SWORDSMAN: return type == EMovableType.SWORDSMAN_L1 || type == EMovableType.SWORDSMAN_L2 || type == EMovableType.SWORDSMAN_L3; case SOLDIER_PIKEMAN: return type == EMovableType.PIKEMAN_L1 || type == EMovableType.PIKEMAN_L2 || type == EMovableType.PIKEMAN_L3; default: return false; } } else { return false; } } } private final boolean isMarked(short x, short y) { return flagsGrid.isMarked(x, y); } private final boolean hasProtectedNeighbor(short x, short y) { for (EDirection currDir : EDirection.values) { if (flagsGrid.isProtected(currDir.getNextTileX(x), currDir.getNextTileY(y))) return true; } return false; } private final boolean hasNeighbourLandscape(short x, short y, ELandscapeType landscape) { for (ShortPoint2D pos : new MapNeighboursArea(new ShortPoint2D(x, y))) { short currX = pos.getX(); short currY = pos.getY(); if (isInBounds(currX, currY) && landscapeGrid.getLandscapeTypeAt(currX, currY) == landscape) { return true; } } return false; } private final boolean hasSamePlayer(short x, short y, IPathCalculateable requester) { return partitionsGrid.getPlayerAt(x, y) == requester.getPlayer(); } private final boolean isRiver(short x, short y) { ELandscapeType type = landscapeGrid.getLandscapeTypeAt(x, y); return type == ELandscapeType.RIVER1 || type == ELandscapeType.RIVER2 || type == ELandscapeType.RIVER3 || type == ELandscapeType.RIVER4; } final boolean isTreePlantable(short x, short y) { return landscapeGrid.getLandscapeTypeAt(x, y).isGrass() && !flagsGrid.isProtected(x, y) && !hasBlockedNeighbor(x, y); } private final boolean hasBlockedNeighbor(short x, short y) { for (EDirection currDir : EDirection.values) { short currX = currDir.getNextTileX(x); short currY = currDir.getNextTileY(y); if (!isInBounds(currX, currY) || flagsGrid.isBlocked(currX, currY)) { return true; } } return false; } private final boolean isCornPlantable(short x, short y) { ELandscapeType landscapeType = landscapeGrid.getLandscapeTypeAt(x, y); return (landscapeType.isGrass() || landscapeType == ELandscapeType.EARTH) && !flagsGrid.isProtected(x, y) && !hasProtectedNeighbor(x, y) && !objectsGrid.hasMapObjectType(x, y, EMapObjectType.CORN_GROWING) && !objectsGrid.hasMapObjectType(x, y, EMapObjectType.CORN_ADULT) && !objectsGrid.hasNeighborObjectType(x, y, EMapObjectType.CORN_ADULT) && !objectsGrid.hasNeighborObjectType(x, y, EMapObjectType.CORN_GROWING); } private final boolean isCornCuttable(short x, short y) { return objectsGrid.hasCuttableObject(x, y, EMapObjectType.CORN_ADULT); } @Override public void setDebugColor(short x, short y, Color color) { landscapeGrid.setDebugColor(x, y, color.getARGB()); } } final class GraphicsGrid implements IGraphicsGrid { @Override public final short getHeight() { return height; } @Override public final short getWidth() { return width; } @Override public final IMovable getMovableAt(int x, int y) { return movableGrid.getMovableAt((short) x, (short) y); } @Override public final IMapObject getMapObjectsAt(int x, int y) { return objectsGrid.getObjectsAt((short) x, (short) y); } @Override public final byte getHeightAt(int x, int y) { return landscapeGrid.getHeightAt((short) x, (short) y); } @Override public final ELandscapeType getLandscapeTypeAt(int x, int y) { return landscapeGrid.getLandscapeTypeAt((short) x, (short) y); } @Override public final int getDebugColorAt(int x, int y) { // short value = (short) (partitionsGrid.getPartitionAt((short) x, (short) y) + 1); // return Color.getARGB((value % 3) * 0.33f, ((value / 3) % 3) * 0.33f, ((value / 9) % 3) * 0.33f, 1); // short value = (short) (partitionsGrid.getTowerCounterAt((short) x, (short) y) + 1); // return new Color((value % 3) * 0.33f, ((value / 3) % 3) * 0.33f, ((value / 9) % 3) * 0.33f, 1); // short value = (short) (partitionsGrid.getPlayerAt((short) x, (short) y) + 1); // return new Color((value % 3) * 0.33f, ((value / 3) % 3) * 0.33f, ((value / 9) % 3) * 0.33f, 1); // return landscapeGrid.getDebugColor(x, y); return objectsGrid.getMapObjectAt((short) x, (short) y, EMapObjectType.ATTACKABLE_TOWER) != null ? Color.RED.getARGB() : flagsGrid .isBlocked((short) x, (short) y) ? Color.BLACK.getARGB() : (flagsGrid.isProtected((short) x, (short) y) ? Color.BLUE.getARGB() : (flagsGrid.isMarked((short) x, (short) y) ? Color.GREEN.getARGB() : 0)); } @Override public final boolean isBorder(int x, int y) { return flagsGrid.isBorderAt((short) x, (short) y); } @Override public final byte getPlayerAt(int x, int y) { return partitionsGrid.getPlayerAt((short) x, (short) y); } @Override public final byte getVisibleStatus(int x, int y) { return fogOfWar.getVisibleStatus(x, y); } @Override public final boolean isFogOfWarVisible(int x, int y) { return fogOfWar.isVisible(x, y); } @Override public final void setBackgroundListener(IGraphicsBackgroundListener backgroundListener) { landscapeGrid.setBackgroundListener(backgroundListener); } @Override public int nextDrawableX(int x, int y) { return x + 1; } } final class MapObjectsManagerGrid implements IMapObjectsManagerGrid { private static final long serialVersionUID = 6223899915568781576L; @Override public final void setLandscape(short x, short y, ELandscapeType landscapeType) { setLandscapeTypeAt(x, y, landscapeType); } @Override public final void setBlocked(short x, short y, boolean blocked) { flagsGrid.setBlockedAndProtected(x, y, blocked); } @Override public final AbstractHexMapObject removeMapObjectType(short x, short y, EMapObjectType mapObjectType) { return objectsGrid.removeMapObjectType(x, y, mapObjectType); } @Override public final boolean removeMapObject(short x, short y, AbstractHexMapObject mapObject) { return objectsGrid.removeMapObject(x, y, mapObject); } @Override public final boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y); } @Override public final AbstractHexMapObject getMapObject(short x, short y, EMapObjectType mapObjectType) { return objectsGrid.getMapObjectAt(x, y, mapObjectType); } @Override public final void addMapObject(short x, short y, AbstractHexMapObject mapObject) { objectsGrid.addMapObjectAt(x, y, mapObject); } @Override public final short getWidth() { return width; } @Override public final short getHeight() { return height; } @Override public final boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public final void setProtected(short x, short y, boolean protect) { flagsGrid.setProtected(x, y, protect); } @Override public EResourceType getRessourceTypeAt(short x, short y) { return landscapeGrid.getResourceTypeAt(x, y); } @Override public byte getRessourceAmountAt(short x, short y) { return landscapeGrid.getResourceAmountAt(x, y); } } final class LandmarksGrid implements ILandmarksThreadGrid { @Override public final boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y); } @Override public final boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public final short getPartitionAt(short x, short y) { return partitionsGrid.getPartitionAt(x, y); } @Override public final void setPartitionAndPlayerAt(short x, short y, short partition) { partitionsGrid.setPartitionAndPlayerAt(x, y, partition); bordersThread.checkPosition(new ShortPoint2D(x, y)); AbstractHexMapObject building = objectsGrid.getMapObjectAt(x, y, EMapObjectType.BUILDING); if (building != null && ((IPlayerable) building).getPlayer() != partitionsGrid.getPlayerAt(x, y)) { ((Building) building).kill(); } } @Override public short getHeight() { return height; } @Override public short getWidth() { return width; } } final class ConstructionMarksGrid implements IConstructionMarkableMap { @Override public final void setConstructMarking(short x, short y, byte value) { mapObjectsManager.setConstructionMarking(x, y, value); } @Override public final short getWidth() { return width; } @Override public final short getHeight() { return height; } final boolean canConstructAt(short x, short y, EBuildingType type, byte player) { ELandscapeType[] landscapes = type.getGroundtypes(); for (RelativePoint curr : type.getProtectedTiles()) { short currX = curr.calculateX(x); short currY = curr.calculateY(y); if (!canUsePositionForConstruction(currX, currY, landscapes, player)) { return false; } } return getConstructionMarkValue(x, y, type) >= 0; } @Override public final boolean canUsePositionForConstruction(short x, short y, ELandscapeType[] landscapeTypes, byte player) { return MainGrid.this.isInBounds(x, y) && !flagsGrid.isProtected(x, y) && partitionsGrid.getPlayerAt(x, y) == player && isAllowedLandscape(x, y, landscapeTypes); } private final boolean isAllowedLandscape(short x, short y, ELandscapeType[] landscapes) { ELandscapeType landscapeAt = landscapeGrid.getLandscapeTypeAt(x, y); for (byte i = 0; i < landscapes.length; i++) { if (landscapeAt == landscapes[i]) { return true; } } return false; } @Override public final boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public byte getConstructionMarkValue(short mapX, short mapY, EBuildingType buildingType) { final BuildingAreaBitSet buildingSet = buildingType.getBuildingAreaBitSet(); int sum = 0; for (short x = buildingSet.minX; x <= buildingSet.maxX; x++) { for (short y = buildingSet.minX; y <= buildingSet.maxX; y++) { if (buildingSet.get(x, y)) { sum += landscapeGrid.getHeightAt((short) (mapX + x), (short) (mapY + y)); } } } int avg = sum / buildingSet.numberOfPositions; float diff = 0; for (short x = buildingSet.minX; x <= buildingSet.maxX; x++) { for (short y = buildingSet.minX; y <= buildingSet.maxX; y++) { if (buildingSet.get(x, y)) { float currDiff = Math.abs(landscapeGrid.getHeightAt((short) (mapX + x), (short) (mapY + y))) - avg; diff += currDiff; } } } diff /= buildingSet.numberOfPositions; int result = (int) (2 * diff); if (result <= Byte.MAX_VALUE) { return (byte) result; } else { return -1; } } } final class MovablePathfinderGrid implements INewMovableGrid, Serializable { private static final long serialVersionUID = 4006228724969442801L; transient IAStar aStar; transient DijkstraAlgorithm dijkstra; private transient InAreaFinder inAreaFinder; private transient PathfinderGrid pathfinderGrid; public MovablePathfinderGrid() { initPathfinders(); } private final void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); initPathfinders(); } private final void initPathfinders() { pathfinderGrid = new PathfinderGrid(); aStar = new HexAStar(pathfinderGrid, width, height); dijkstra = new DijkstraAlgorithm(pathfinderGrid, aStar, width, height); inAreaFinder = new InAreaFinder(pathfinderGrid, width, height); } @Override public final boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y); } @Override public final boolean isProtected(short x, short y) { return flagsGrid.isProtected(x, y); } @Override public final boolean isBlockedOrProtected(short x, short y) { return isBlocked(x, y) || isProtected(x, y); } @Override public final boolean canPop(ShortPoint2D position, EMaterialType material) { return mapObjectsManager.canPop(position.getX(), position.getY(), material); } @Override public final byte getHeightAt(ShortPoint2D position) { return landscapeGrid.getHeightAt(position.getX(), position.getY()); } @Override public final void setMarked(ShortPoint2D position, boolean marked) { flagsGrid.setMarked(position.getX(), position.getY(), marked); } @Override public final boolean isMarked(ShortPoint2D position) { return flagsGrid.isMarked(position.getX(), position.getY()); } @Override public final byte getPlayerAt(short x, short y) { return partitionsGrid.getPlayerAt(x, y); } @Override public final boolean executeSearchType(ShortPoint2D position, ESearchType searchType) { return mapObjectsManager.executeSearchType(position, searchType); } @Override public final void placeSmoke(ShortPoint2D pos, boolean place) { if (place) { mapObjectsManager.addSimpleMapObject(pos, EMapObjectType.SMOKE, false, (byte) 0); } else { mapObjectsManager.removeMapObjectType(pos.getX(), pos.getY(), EMapObjectType.SMOKE); } } @Override public void changePlayerAt(ShortPoint2D position, byte player) { partitionsGrid.changePlayerAt(position.getX(), position.getY(), player); bordersThread.checkPosition(position); landmarksCorrection.reTest(position.getX(), position.getY()); } // @Override // public final boolean isProtected(short x, short y) { // return flagsGrid.isProtected(x, y); // @Override // public final boolean isEnforcedByTower(ShortPoint2D pos) { // return partitionsGrid.isEnforcedByTower(pos.getX(), pos.getY()); @Override public final boolean isValidPosition(IPathCalculateable pathRequester, ShortPoint2D pos) { short x = pos.getX(), y = pos.getY(); return MainGrid.this.isInBounds(x, y) && !isBlocked(x, y) && (!pathRequester.needsPlayersGround() || pathRequester.getPlayer() == partitionsGrid.getPlayerAt(x, y)); } // @Override // public final EResourceType getResourceTypeAt(short x, short y) { // return landscapeGrid.getResourceTypeAt(x, y); // @Override // public final byte getResourceAmountAt(short x, short y) { // return landscapeGrid.getResourceAmountAt(x, y); // @Override // public final boolean canAddRessourceSign(ShortPoint2D pos) { // return super.canAddRessourceSign(pos.getX(), pos.getY()); // @Override // public final EMaterialType stealMaterialAt(ShortPoint2D pos) { // EMaterialType materialType = mapObjectsManager.stealMaterialAt(pos.getX(), pos.getY()); // if (materialType != null) { // partitionsGrid.removeOfferAt(pos, materialType); // return materialType; @Override public float getResourceAmountAround(short x, short y, EResourceType type) { return landscapeGrid.getResourceAmountAround(x, y, type); } @Override public void addJoblessBearer(IManageableBearer bearer) { partitionsGrid.addJobless(bearer); } @Override public void addJoblessWorker(IManageableWorker worker) { partitionsGrid.addJobless(worker); } @Override public void addJoblessDigger(IManageableDigger digger) { partitionsGrid.addJobless(digger); } @Override public void addJoblessBricklayer(IManageableBricklayer bricklayer) { partitionsGrid.addJobless(bricklayer); } @Override public boolean takeMaterial(ShortPoint2D position, EMaterialType materialType) { if (mapObjectsManager.popMaterial(position.getX(), position.getY(), materialType)) { return true; } else return false; } @Override public boolean dropMaterial(ShortPoint2D position, EMaterialType materialType, boolean offer) { if (mapObjectsManager.pushMaterial(position.getX(), position.getY(), materialType)) { if (offer) { partitionsGrid.pushMaterial(position, materialType); } return true; } else return false; } @Override public EDirection getDirectionOfSearched(ShortPoint2D position, ESearchType searchType) { if (searchType == ESearchType.FISHABLE) { for (EDirection direction : EDirection.values) { ShortPoint2D currPos = direction.getNextHexPoint(position); short x = currPos.getX(), y = currPos.getY(); if (isInBounds(x, y) && landscapeGrid.getLandscapeTypeAt(x, y).isWater()) { return direction; } } return null; } else if (searchType == ESearchType.RIVER) { for (EDirection direction : EDirection.values) { ShortPoint2D currPos = direction.getNextHexPoint(position); short x = currPos.getX(), y = currPos.getY(); ELandscapeType landscapeTypeAt = landscapeGrid.getLandscapeTypeAt(x, y); if (isInBounds(x, y) && (landscapeTypeAt == ELandscapeType.RIVER1 || landscapeTypeAt == ELandscapeType.RIVER2 || landscapeTypeAt == ELandscapeType.RIVER3 || landscapeTypeAt == ELandscapeType.RIVER4)) { return direction; } } return null; } else { return null; } } @Override public EMaterialType popToolProductionRequest(ShortPoint2D pos) { return partitionsGrid.popToolProduction(pos); } @Override public final boolean isPigAdult(ShortPoint2D pos) { return mapObjectsManager.isPigAdult(pos); } @Override public void placePigAt(ShortPoint2D pos, boolean place) { mapObjectsManager.placePig(pos, place); } @Override public boolean hasPigAt(ShortPoint2D position) { return mapObjectsManager.isPigThere(position); } @Override public boolean canPushMaterial(ShortPoint2D position) { return mapObjectsManager.canPush(position); } @Override public void changeHeightTowards(short x, short y, byte targetHeight) { byte currHeight = landscapeGrid.getHeightAt(x, y); landscapeGrid.setHeightAt(x, y, (byte) (currHeight + Math.signum(targetHeight - currHeight))); landscapeGrid.setLandscapeTypeAt(x, y, ELandscapeType.FLATTENED); } @Override public boolean hasNoMovableAt(short x, short y) { return movableGrid.getMovableAt(x, y) == null; } @Override public void leavePosition(ShortPoint2D position, NewMovable movable) { movableGrid.movableLeft(position, movable); } @Override public void enterPosition(ShortPoint2D position, NewMovable movable) { movableGrid.movableEntered(position, movable); } @Override public Path calculatePathTo(IPathCalculateable pathRequester, ShortPoint2D targetPos) { return aStar.findPath(pathRequester, targetPos); } @Override public Path searchDijkstra(IPathCalculateable pathCalculateable, short centerX, short centerY, short radius, ESearchType searchType) { return dijkstra.find(pathCalculateable, centerX, centerY, (short) 1, radius, searchType); } @Override public Path searchInArea(IPathCalculateable pathCalculateable, short centerX, short centerY, short radius, ESearchType searchType) { ShortPoint2D target = inAreaFinder.find(pathCalculateable, centerX, centerY, radius, searchType); if (target != null) { return calculatePathTo(pathCalculateable, target); } else { return null; } } @Override public NewMovable getMovableAt(short x, short y) { return movableGrid.getMovableAt(x, y); } @Override public void addSelfDeletingMapObject(ShortPoint2D position, EMapObjectType mapObjectType, int duration, byte player) { mapObjectsManager.addSelfDeletingMapObject(position, mapObjectType, duration, player); } @Override public boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public boolean fitsSearchType(IPathCalculateable pathCalculable, ShortPoint2D pos, ESearchType searchType) { return pathfinderGrid.fitsSearchType(pos.getX(), pos.getY(), searchType, pathCalculable); } } public final class MovableNeighborIterator implements Iterator<NewMovable> { private final HexGridAreaIterator hexIterator; private NewMovable currMovable; public MovableNeighborIterator(ShortPoint2D pos, byte radius) { this.hexIterator = new HexGridArea(pos.getX(), pos.getY(), (short) 0, radius).iterator(); } @Override public boolean hasNext() { while (hexIterator.hasNext()) { if (isInBounds(hexIterator.getNextX(), hexIterator.getNextY()) && (currMovable = movableGrid.getMovableAt(hexIterator.getNextX(), hexIterator.getNextY())) != null) { return true; } } return false; } @Override public NewMovable next() { return currMovable; } @Override public void remove() { throw new UnsupportedOperationException(); } public final int getCurrRadius() { return hexIterator.getCurrRadius(); } } final class BordersThreadGrid implements IBordersThreadGrid { @Override public final byte getPlayerAt(short x, short y) { return partitionsGrid.getPlayerAt(x, y); } @Override public final void setBorderAt(short x, short y, boolean isBorder) { flagsGrid.setBorderAt(x, y, isBorder); } @Override public final boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } } final class BuildingsGrid implements IBuildingsGrid, Serializable { private static final long serialVersionUID = -5567034251907577276L; private final RequestStackGrid requestStackGrid = new RequestStackGrid(); @Override public final byte getHeightAt(ShortPoint2D position) { return landscapeGrid.getHeightAt(position.getX(), position.getY()); } @Override public final void pushMaterialsTo(ShortPoint2D position, EMaterialType type, byte numberOf) { for (int i = 0; i < numberOf; i++) { movablePathfinderGrid.dropMaterial(position, type, true); } } @Override public final boolean setBuilding(ShortPoint2D position, Building newBuilding) { if (MainGrid.this.isInBounds(position.getX(), position.getY())) { FreeMapArea area = new FreeMapArea(position, newBuilding.getBuildingType().getProtectedTiles()); if (canConstructAt(area)) { setProtectedState(area, true); mapObjectsManager.addBuildingTo(position, newBuilding); return true; } else { return false; } } else { return false; } } private final void setProtectedState(FreeMapArea area, boolean setProtected) { for (ShortPoint2D curr : area) { if (MainGrid.this.isInBounds(curr.getX(), curr.getY())) flagsGrid.setProtected(curr.getX(), curr.getY(), setProtected); } } private final boolean canConstructAt(FreeMapArea area) { boolean isFree = true; for (ShortPoint2D curr : area) { short x = curr.getX(); short y = curr.getY(); if (!isInBounds(x, y) || flagsGrid.isProtected(x, y) || flagsGrid.isBlocked(x, y)) { isFree = false; } } return isFree; } @Override public final void removeBuildingAt(ShortPoint2D pos) { IBuilding building = (IBuilding) objectsGrid.getMapObjectAt(pos.getX(), pos.getY(), EMapObjectType.BUILDING); mapObjectsManager.removeMapObjectType(pos.getX(), pos.getY(), EMapObjectType.BUILDING); FreeMapArea area = new FreeMapArea(pos, building.getBuildingType().getProtectedTiles()); for (ShortPoint2D curr : area) { if (isInBounds(curr.getX(), curr.getY())) { flagsGrid.setBlockedAndProtected(curr.getX(), curr.getY(), false); } } } @Override public final void occupyArea(MapCircle toBeOccupied, ShortPoint2D occupiersPosition, byte player) { List<ShortPoint2D> occupiedPositions = partitionsGrid.occupyArea(toBeOccupied, occupiersPosition, player); bordersThread.checkPositions(occupiedPositions); landmarksCorrection.addLandmarkedPositions(occupiedPositions); } @Override public final void freeOccupiedArea(MapCircle occupied, ShortPoint2D pos) { List<ShortPoint2D> totallyFreed = partitionsGrid.freeOccupiedArea(occupied, pos); if (!totallyFreed.isEmpty()) { StopWatch watch = new MilliStopWatch(); watch.start(); List<OccupyingBuilding> allOccupying = OccupyingBuilding.getAllOccupyingBuildings(); int maxSqDistance = 6 * CommonConstants.TOWERRADIUS * CommonConstants.TOWERRADIUS; List<OccupyingDistanceCombi> occupyingInRange = new LinkedList<OccupyingDistanceCombi>(); for (OccupyingBuilding curr : allOccupying) { ShortPoint2D currPos = curr.getPos(); int dx = currPos.getX() - pos.getX(); int dy = currPos.getY() - pos.getY(); int sqDistance = dx * dx + dy * dy; if (sqDistance <= maxSqDistance && sqDistance > 0) { // > 0 to remove the tower just freeing the position occupyingInRange.add(new OccupyingDistanceCombi(sqDistance, curr)); } } if (!occupyingInRange.isEmpty()) { Collections.sort(occupyingInRange); FreeMapArea freedArea = new FreeMapArea(totallyFreed); for (OccupyingDistanceCombi currOcc : occupyingInRange) { MapCircle currOccArea = currOcc.building.getOccupyablePositions(); Iterator<ShortPoint2D> iter = freedArea.iterator(); for (ShortPoint2D currPos = iter.next(); iter.hasNext(); currPos = iter.next()) { if (currOccArea.contains(currPos)) { iter.remove(); partitionsGrid.occupyAt(currPos.getX(), currPos.getY(), currOcc.building.getPlayer()); bordersThread.checkPosition(currPos); landmarksCorrection.reTest(currPos.getX(), currPos.getY()); } } if (freedArea.isEmpty()) { break; } } } watch.stop(" } } private final class OccupyingDistanceCombi implements Comparable<OccupyingDistanceCombi> { final int sqDistance; final OccupyingBuilding building; OccupyingDistanceCombi(int sqDistance, OccupyingBuilding building) { this.sqDistance = sqDistance; this.building = building; } @Override public final int compareTo(OccupyingDistanceCombi arg) { return sqDistance - arg.sqDistance; } } @Override public final void setBlocked(FreeMapArea area, boolean blocked) { for (ShortPoint2D curr : area) { if (MainGrid.this.isInBounds(curr.getX(), curr.getY())) flagsGrid.setBlockedAndProtected(curr.getX(), curr.getY(), blocked); } } @Override public final short getWidth() { return width; } @Override public final short getHeight() { return height; } @Override public final NewMovable getMovable(ShortPoint2D position) { return movableGrid.getMovableAt(position.getX(), position.getY()); } @Override public final MapObjectsManager getMapObjectsManager() { return mapObjectsManager; } @Override public final INewMovableGrid getMovableGrid() { return movablePathfinderGrid; } @Override public final void requestDiggers(IDiggerRequester requester, byte amount) { partitionsGrid.requestDiggers(requester, amount); } @Override public final void requestBricklayer(Building building, ShortPoint2D bricklayerTargetPos, EDirection direction) { partitionsGrid.requestBricklayer(building, bricklayerTargetPos, direction); } @Override public final IRequestsStackGrid getRequestStackGrid() { return requestStackGrid; } @Override public final void requestBuildingWorker(EMovableType workerType, WorkerBuilding workerBuilding) { partitionsGrid.requestBuildingWorker(workerType, workerBuilding); } @Override public final void requestSoilderable(IBarrack barrack) { partitionsGrid.requestSoilderable(barrack); } @Override public final DijkstraAlgorithm getDijkstra() { return movablePathfinderGrid.dijkstra; } private class RequestStackGrid implements IRequestsStackGrid, Serializable { private static final long serialVersionUID = 1278397366408051067L; @Override public final void request(IMaterialRequester requester, EMaterialType materialType, byte priority) { partitionsGrid.request(requester, materialType, priority); } @Override public final boolean hasMaterial(ShortPoint2D position, EMaterialType materialType) { return mapObjectsManager.canPop(position.getX(), position.getY(), materialType); } @Override public final void popMaterial(ShortPoint2D position, EMaterialType materialType) { mapObjectsManager.popMaterial(position.getX(), position.getY(), materialType); } @Override public final byte getStackSize(ShortPoint2D position, EMaterialType materialType) { return mapObjectsManager.getStackSize(position.getX(), position.getY(), materialType); } @Override public final void releaseRequestsAt(ShortPoint2D position, EMaterialType materialType) { partitionsGrid.releaseRequestsAt(position, materialType); byte stackSize = mapObjectsManager.getStackSize(position.getX(), position.getY(), materialType); for (byte i = 0; i < stackSize; i++) { partitionsGrid.pushMaterial(position, materialType); } } } } final class GUIInputGrid implements IGuiInputGrid { @Override public final NewMovable getMovable(short x, short y) { return movableGrid.getMovableAt(x, y); } @Override public final short getWidth() { return width; } @Override public final short getHeight() { return height; } @Override public final IBuilding getBuildingAt(short x, short y) { return (IBuilding) objectsGrid.getMapObjectAt(x, y, EMapObjectType.BUILDING); } @Override public final boolean isInBounds(ShortPoint2D position) { return MainGrid.this.isInBounds(position.getX(), position.getY()); } @Override public final IBuildingsGrid getBuildingsGrid() { return buildingsGrid; } @Override public final byte getPlayerAt(ShortPoint2D position) { return partitionsGrid.getPlayerAt(position); } @Override public final void resetDebugColors() { landscapeGrid.resetDebugColors(); } @Override public final ShortPoint2D getConstructablePositionAround(ShortPoint2D pos, EBuildingType type) { byte player = partitionsGrid.getPlayerAt(pos); if (constructionMarksGrid.canConstructAt(pos.getX(), pos.getY(), type, player)) { return pos; } else { for (ShortPoint2D neighbour : new MapNeighboursArea(pos)) { if (constructionMarksGrid.canConstructAt(neighbour.getX(), neighbour.getY(), type, player)) { return neighbour; } } return null; } } @Override public final void save() throws FileNotFoundException, IOException, InterruptedException { boolean pausing = NetworkTimer.isPausing(); NetworkTimer.get().setPausing(true); try { Thread.sleep(30); // FIXME @Andreas serializer should wait until // threads did their work! } catch (InterruptedException e) { e.printStackTrace(); } MapList list = MapList.getDefaultList(); // TODO: pass on ui state. list.saveMap(new UIState(0, new ShortPoint2D(0, 0)), MainGrid.this); NetworkTimer.get().setPausing(pausing); } @Override public final void toggleFogOfWar() { fogOfWar.toggleEnabled(); } @Override public IConstructionMarkableMap getConstructionMarksGrid() { return constructionMarksGrid; } } final class PartitionableGrid implements IPartitionableGrid, Serializable { private static final long serialVersionUID = 5631266851555264047L; @Override public final boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y); } @Override public final void changedPartitionAt(short x, short y) { landmarksCorrection.reTest(x, y); } @Override public final void setDebugColor(final short x, final short y, Color color) { landscapeGrid.setDebugColor(x, y, color.getARGB()); } } final class FogOfWarGrid implements IFogOfWarGrid { @Override public final IMovable getMovableAt(short x, short y) { return movableGrid.getMovableAt(x, y); } @Override public final IMapObject getMapObjectsAt(short x, short y) { return objectsGrid.getObjectsAt(x, y); } @Override public final ConcurrentLinkedQueue<? extends IViewDistancable> getMovableViewDistancables() { return NewMovable.getAllMovables(); } @Override public final ConcurrentLinkedQueue<? extends IViewDistancable> getBuildingViewDistancables() { return Building.getAllBuildings(); } } }
package ca.cumulonimbus.pressurenetsdk; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import android.app.Service; import android.content.Intent; import android.database.Cursor; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.os.Handler; import android.os.IBinder; import android.os.SystemClock; import android.provider.Settings.Secure; /** * Represent developer-facing pressureNET API * Background task; manage and run everything * Handle Intents * * @author jacob * */ public class CbService extends Service { private CbDataCollector dataCollector; private CbLocationManager locationManager; private CbDb db; private String mAppDir; IBinder mBinder; private final Handler mHandler = new Handler(); /** * Find all the data for an observation. * * Location, Measurement values, etc. * * @return */ public CbObservation collectNewObservation() { try { CbObservation pressureObservation = new CbObservation(); log("cb collecting new observation"); // Location values locationManager = new CbLocationManager(getApplicationContext()); locationManager.startGettingLocations(); // Measurement values dataCollector = new CbDataCollector(getID(), getApplicationContext()); pressureObservation = dataCollector.getPressureObservation(); pressureObservation.setLocation(locationManager.getCurrentBestLocation()); // stop listening for locations locationManager.stopGettingLocations(); return pressureObservation; } catch(Exception e) { e.printStackTrace(); return new CbObservation(); } } /** * Find all the data for an observation group. * * Location, Measurement values, etc. * * @return */ public CbObservationGroup collectNewObservationGroup() { ArrayList<CbObservation> observations = new ArrayList<CbObservation>(); CbObservation pressureObservation = new CbObservation(); // Location values locationManager = new CbLocationManager(this); locationManager.startGettingLocations(); // Measurement values dataCollector = new CbDataCollector(getID(), getApplicationContext()); pressureObservation = dataCollector.getPressureObservation(); // Put everything together observations.add(pressureObservation); CbObservationGroup newGroup = new CbObservationGroup(); newGroup.setGroup(observations); return newGroup; } /** * Collect and send data in a different thread. * This runs itself every "settingsHandler.getDataCollectionFrequency()" milliseconds */ private class ReadingSender implements Runnable { private CbSettingsHandler singleAppSettings; public ReadingSender(CbSettingsHandler settings) { this.singleAppSettings = settings; } public void run() { log("collecting and submitting " + singleAppSettings.getServerURL()); long base = SystemClock.uptimeMillis(); CbObservation singleObservation = new CbObservation(); if(singleAppSettings.isCollectingData()) { // Collect singleObservation = collectNewObservation(); log("lat" + singleObservation.getLocation().getLatitude()); if(singleAppSettings.isSharingData()) { // Send sendCbObservation(singleObservation, singleAppSettings); } } mHandler.postAtTime(this, base + (singleAppSettings.getDataCollectionFrequency())); } }; /** * Stop all listeners, active sensors, etc, and shut down. * */ public void shutDownService() { if(locationManager!=null) { locationManager.stopGettingLocations(); } if(dataCollector != null) { dataCollector.stopCollectingPressure(); } //stopSelf(); } /** * Send the observation group to the server * * @param group * @return */ public boolean sendCbObservationGroup(CbObservationGroup group) { // TODO: Implement log("send observation group"); return false; } /** * Send the observation to the server * * @param group * @return */ public boolean sendCbObservation(CbObservation observation, CbSettingsHandler settings) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settings,locationManager); sender.execute(observation.getObservationAsParams()); return true; }catch (Exception e) { return false; } } /** * Send a new account to the server * * @param group * @return */ public boolean sendCbAccount(CbAccount account, CbSettingsHandler settings) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settings,locationManager); sender.execute(account.getAccountAsParams()); return true; }catch(Exception e) { return false; } } /** * Start the periodic data collection. */ public void start(CbSettingsHandler settings) { log("CbService: Starting to collect data."); //mHandler.postDelayed(mSubmitReading, 0); //Thread cbThread = new Thread(mSubmitReading); ReadingSender sender = new ReadingSender(settings); mHandler.post(sender); } @Override public void onDestroy() { log("on destroy"); shutDownService(); super.onDestroy(); } @Override public void onCreate() { setUpFiles(); log("cb on create"); db = new CbDb(getApplicationContext()); super.onCreate(); } /** * Start running background data collection methods. * */ @Override public int onStartCommand(Intent intent, int flags, int startId) { log("cb onstartcommand"); // Check the intent for Settings initialization if (intent != null) { if(intent.hasExtra("serverURL")) { startWithIntent(intent); } else { startWithDatabase(); } return START_STICKY; } else { log("INTENT NULL; checking db"); startWithDatabase(); } super.onStartCommand(intent, flags, startId); return START_STICKY; } public void startWithIntent(Intent intent) { try { log( "intent url " + intent.getExtras().getString("serverURL")); CbSettingsHandler settings = new CbSettingsHandler(getApplicationContext()); settings.setServerURL(intent.getStringExtra("serverURL")); settings.setAppID(getID()); // Seems like new settings. Try adding to the db. settings.saveSettings(); // are we creating a new user? if (intent.hasExtra("add_account")) { log("adding new user"); CbAccount account = new CbAccount(); account.setEmail(intent.getStringExtra("email")); account.setTimeRegistered(intent.getLongExtra("time", 0)); account.setUserID(intent.getStringExtra("userID")); sendCbAccount(account, settings); } // Start a new thread and return start(settings); } catch(Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } public void startWithDatabase() { try { db.open(); // Check the database for Settings initialization CbSettingsHandler settings = new CbSettingsHandler(getApplicationContext()); //db.clearDb(); Cursor allSettings = db.fetchAllSettings(); log("cb intent null; checking db, size " + allSettings.getCount()); while(allSettings.moveToNext()) { settings.setAppID(allSettings.getString(1)); settings.setDataCollectionFrequency(allSettings.getLong(2)); settings.setServerURL(allSettings.getString(3)); start(settings); // but just once break; } db.close(); } catch(Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } /** * Get a hash'd device ID * * @return */ public String getID() { try { MessageDigest md = MessageDigest.getInstance("MD5"); String actual_id = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID); byte[] bytes = actual_id.getBytes(); byte[] digest = md.digest(bytes); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString(); } catch (Exception e) { return " } } // Used to write a log to SD card. Not used unless logging enabled. public void setUpFiles() { try { File homeDirectory = getExternalFilesDir(null); if(homeDirectory!=null) { mAppDir = homeDirectory.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); } } // Log data to SD card for debug purposes. // To enable logging, ensure the Manifest allows writing to SD card. public void logToFile(String text) { try { OutputStream output = new FileOutputStream(mAppDir + "/log.txt", true); String logString = (new Date()).toString() + ": " + text + "\n"; output.write(logString.getBytes()); output.close(); } catch(FileNotFoundException e) { e.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { log("on bind"); // bind return mBinder; } @Override public void onRebind(Intent intent) { log("on rebind"); super.onRebind(intent); } public void log(String message) { //logToFile(message); System.out.println(message); } public CbDataCollector getDataCollector() { return dataCollector; } public void setDataCollector(CbDataCollector dataCollector) { this.dataCollector = dataCollector; } public CbLocationManager getLocationManager() { return locationManager; } public void setLocationManager(CbLocationManager locationManager) { this.locationManager = locationManager; } }
package ca.cumulonimbus.pressurenetsdk; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Date; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.Settings.Secure; import android.widget.TextView; /** * Represent developer-facing pressureNET API Background task; manage and run * everything Handle Intents * * @author jacob * */ public class CbService extends Service { private CbDataCollector dataCollector; private CbLocationManager locationManager; private CbSettingsHandler settingsHandler; private CbDb db; public CbService service = this; private String mAppDir; IBinder mBinder; ReadingSender sender; String serverURL = "https://pressurenet.cumulonimbus.ca/"; // Service Interaction API Messages public static final int MSG_OKAY = 0; public static final int MSG_STOP = 1; public static final int MSG_GET_BEST_LOCATION = 2; public static final int MSG_BEST_LOCATION = 3; public static final int MSG_GET_BEST_PRESSURE = 4; public static final int MSG_BEST_PRESSURE = 5; public static final int MSG_START_AUTOSUBMIT = 6; public static final int MSG_STOP_AUTOSUBMIT = 7; public static final int MSG_SET_SETTINGS = 8; public static final int MSG_GET_SETTINGS = 9; public static final int MSG_SETTINGS = 10; public static final int MSG_START_DATA_STREAM = 11; public static final int MSG_DATA_STREAM = 12; public static final int MSG_STOP_DATA_STREAM = 13; // pressureNET Live API public static final int MSG_GET_LOCAL_RECENTS = 14; public static final int MSG_LOCAL_RECENTS = 15; public static final int MSG_GET_API_RECENTS = 16; public static final int MSG_API_RECENTS = 17; public static final int MSG_MAKE_API_CALL = 18; public static final int MSG_API_RESULT_COUNT = 19; // pressureNET API Cache public static final int MSG_CLEAR_LOCAL_CACHE = 20; public static final int MSG_REMOVE_FROM_PRESSURENET = 21; public static final int MSG_CLEAR_API_CACHE = 22; // Current Conditions public static final int MSG_ADD_CURRENT_CONDITION = 23; public static final int MSG_GET_CURRENT_CONDITIONS = 24; public static final int MSG_CURRENT_CONDITIONS = 25; // Sending Data public static final int MSG_SEND_OBSERVATION = 26; public static final int MSG_SEND_CURRENT_CONDITION = 27; // Current Conditions API public static final int MSG_MAKE_CURRENT_CONDITIONS_API_CALL = 28; // ... User-unique table public static final int MSG_GET_API_UNIQUE_RECENTS = 29; public static final int MSG_API_UNIQUE_RECENTS = 30; long lastAPICall = System.currentTimeMillis(); private final Handler mHandler = new Handler(); Messenger mMessenger = new Messenger(new IncomingHandler()); ArrayList<CbObservation> offlineBuffer = new ArrayList<CbObservation>(); /** * Find all the data for an observation. * * Location, Measurement values, etc. * * @return */ public CbObservation collectNewObservation() { try { CbObservation pressureObservation = new CbObservation(); log("cb collecting new observation"); // Location values locationManager = new CbLocationManager(getApplicationContext()); locationManager.startGettingLocations(); // Measurement values pressureObservation = dataCollector.getPressureObservation(); pressureObservation.setLocation(locationManager .getCurrentBestLocation()); // stop listening for locations locationManager.stopGettingLocations(); return pressureObservation; } catch (Exception e) { e.printStackTrace(); return new CbObservation(); } } /** * Collect and send data in a different thread. This runs itself every * "settingsHandler.getDataCollectionFrequency()" milliseconds */ private class ReadingSender implements Runnable { public void run() { log("collecting and submitting " + settingsHandler.getServerURL()); long base = SystemClock.uptimeMillis(); dataCollector.startCollectingData(null); CbObservation singleObservation = new CbObservation(); if (settingsHandler.isCollectingData()) { // Collect singleObservation = collectNewObservation(); if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { // Send if we're online if (isNetworkAvailable()) { log("online and sending"); singleObservation.setClientKey(getApplicationContext().getPackageName()); sendCbObservation(singleObservation); // also check and send the offline buffer if(offlineBuffer.size() > 0) { System.out.println("sending " + offlineBuffer.size() + " offline buffered obs"); for(CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send"); /// offline buffer variable // TODO: put this in the DB to survive longer offlineBuffer.add(singleObservation); } } } catch (Exception e) { e.printStackTrace(); } } } else { log("tried collecting, reading zero"); } mHandler.postAtTime(this, base + (settingsHandler.getDataCollectionFrequency())); } }; public boolean isNetworkAvailable() { log("is net available?"); ConnectivityManager cm = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { log("yes"); return true; } else { log("no"); return false; } } /** * Stop all listeners, active sensors, etc, and shut down. * */ public void stopAutoSubmit() { if (locationManager != null) { locationManager.stopGettingLocations(); } if (dataCollector != null) { dataCollector.stopCollectingData(); } mHandler.removeCallbacks(sender); } /** * Send the observation to the server * * @param observation * @return */ public boolean sendCbObservation(CbObservation observation) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, dataCollector ); sender.execute(observation.getObservationAsParams()); return true; } catch (Exception e) { return false; } } /** * Send a new account to the server * * @param account * @return */ public boolean sendCbAccount(CbAccount account) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, dataCollector); sender.execute(account.getAccountAsParams()); return true; } catch (Exception e) { return false; } } /** * Send the current condition to the server * * @param observation * @return */ public boolean sendCbCurrentCondition(CbCurrentCondition condition) { log("sending cbcurrent condition"); try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, dataCollector ); sender.execute(condition.getCurrentConditionAsParams()); return true; } catch (Exception e) { return false; } } /** * Start the periodic data collection. */ public void startAutoSubmit() { log("CbService: Starting to auto-collect and submit data."); sender = new ReadingSender(); mHandler.post(sender); } @Override public void onDestroy() { log("on destroy"); stopAutoSubmit(); super.onDestroy(); } @Override public void onCreate() { setUpFiles(); log("cb on create"); db = new CbDb(getApplicationContext()); super.onCreate(); } /** * Start running background data collection methods. * */ @Override public int onStartCommand(Intent intent, int flags, int startId) { log("cb onstartcommand"); // Check the intent for Settings initialization dataCollector = new CbDataCollector(getID(), getApplicationContext()); if (intent != null) { startWithIntent(intent); return START_STICKY; } else { log("INTENT NULL; checking db"); startWithDatabase(); } super.onStartCommand(intent, flags, startId); return START_STICKY; } /** * Convert time ago text to ms. TODO: not this. values in xml. * @param timeAgo * @return */ private long stringTimeToLongHack(String timeAgo) { if (timeAgo.equals("1 minute")) { return 1000 * 60; } else if (timeAgo.equals("5 minutes")) { return 1000 * 60 * 5; } else if (timeAgo.equals("10 minutes")) { return 1000 * 60 * 10; } else if (timeAgo.equals("30 minutes")) { return 1000 * 60 * 30; } else if (timeAgo.equals("1 hour")) { return 1000 * 60 * 60; } return 1000 * 60 * 5; } public void startWithIntent(Intent intent) { try { settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.setServerURL(serverURL); settingsHandler.setAppID(getID()); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String preferenceCollectionFrequency = sharedPreferences.getString( "autofrequency", "10 minutes"); boolean preferenceShareData = sharedPreferences.getBoolean("autoupdate", true); String preferenceShareLevel = sharedPreferences.getString( "sharing_preference", "Us, Researchers and Forecasters"); System.out.println(stringTimeToLongHack(preferenceCollectionFrequency) + ", from " + preferenceCollectionFrequency); settingsHandler.setDataCollectionFrequency(stringTimeToLongHack(preferenceCollectionFrequency)); // Seems like new settings. Try adding to the db. settingsHandler.saveSettings(); // are we creating a new user? if (intent.hasExtra("add_account")) { log("adding new user"); CbAccount account = new CbAccount(); account.setEmail(intent.getStringExtra("email")); account.setTimeRegistered(intent.getLongExtra("time", 0)); account.setUserID(intent.getStringExtra("userID")); sendCbAccount(account); } // Start a new thread and return startAutoSubmit(); } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } public void startWithDatabase() { try { db.open(); // Check the database for Settings initialization settingsHandler = new CbSettingsHandler(getApplicationContext()); // db.clearDb(); Cursor allSettings = db.fetchAllSettings(); log("cb intent null; checking db, size " + allSettings.getCount()); while (allSettings.moveToNext()) { settingsHandler.setAppID(allSettings.getString(1)); settingsHandler.setDataCollectionFrequency(allSettings .getLong(2)); settingsHandler.setServerURL(serverURL); startAutoSubmit(); // but just once break; } db.close(); } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_STOP: log("message. bound service says stop"); stopAutoSubmit(); break; case MSG_GET_BEST_LOCATION: log("message. bound service requesting location"); if (locationManager != null) { Location best = locationManager.getCurrentBestLocation(); try { log("service sending best location"); msg.replyTo.send(Message.obtain(null, MSG_BEST_LOCATION, best)); } catch (RemoteException re) { re.printStackTrace(); } } else { log("error: location null, not returning"); } break; case MSG_GET_BEST_PRESSURE: log("message. bound service requesting pressure"); if (dataCollector != null) { CbObservation pressure = dataCollector .getPressureObservation(); try { log("service sending best pressure"); msg.replyTo.send(Message.obtain(null, MSG_BEST_PRESSURE, pressure)); } catch (RemoteException re) { re.printStackTrace(); } } else { log("error: data collector null, not returning"); } break; case MSG_START_AUTOSUBMIT: log("start autosubmit"); startWithDatabase(); break; case MSG_STOP_AUTOSUBMIT: log("stop autosubmit"); stopAutoSubmit(); break; case MSG_GET_SETTINGS: log("get settings"); try { msg.replyTo.send(Message.obtain(null, MSG_SETTINGS, settingsHandler)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_START_DATA_STREAM: startDataStream(msg.replyTo); break; case MSG_STOP_DATA_STREAM: stopDataStream(); break; case MSG_SET_SETTINGS: log("set settings"); CbSettingsHandler newSettings = (CbSettingsHandler) msg.obj; newSettings.saveSettings(); break; case MSG_GET_LOCAL_RECENTS: log("get recents"); CbApiCall apiCall = (CbApiCall) msg.obj; System.out.println(apiCall); if(apiCall == null) { System.out.println("apicall null, bailing"); break; } // run API call db.open(); Cursor cursor = db.runLocalAPICall(apiCall.getMinLat(), apiCall.getMaxLat(), apiCall.getMinLon(), apiCall.getMaxLon(), apiCall.getStartTime(), apiCall.getEndTime(), 2000); System.out.println("local api cursor count " + cursor.getCount()); ArrayList<CbObservation> results = new ArrayList<CbObservation>(); while (cursor.moveToNext()) { // TODO: This is duplicated in CbDataCollector. Fix that CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cursor.getDouble(1)); location.setLongitude(cursor.getDouble(2)); location.setAltitude(cursor.getDouble(3)); location.setAccuracy(cursor.getInt(4)); location.setProvider(cursor.getString(5)); obs.setLocation(location); obs.setObservationType(cursor.getString(6)); obs.setObservationUnit(cursor.getString(7)); obs.setObservationValue(cursor.getDouble(8)); obs.setSharing(cursor.getString(9)); obs.setTime(cursor.getLong(10)); obs.setTimeZoneOffset(cursor.getInt(11)); obs.setUser_id(cursor.getString(12)); obs.setTrend(cursor.getString(18)); // TODO: Add sensor information results.add(obs); } db.close(); log("cbservice: " + results.size() + " local api results"); try { msg.replyTo.send(Message.obtain(null, MSG_LOCAL_RECENTS, results)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_GET_API_RECENTS: CbApiCall apiCacheCall = (CbApiCall) msg.obj; log("get api recents " + apiCacheCall.toString()); // run API call db.open(); Cursor cacheCursor = db.runAPICacheCall( apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(), apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(), apiCacheCall.getStartTime(), apiCacheCall.getEndTime(), apiCacheCall.getLimit()); ArrayList<CbObservation> cacheResults = new ArrayList<CbObservation>(); System.out.println("cache cursor count " + cacheCursor.getCount()); while (cacheCursor.moveToNext()) { CbObservation obs = new CbObservation(); obs.setObservationValue(cacheCursor.getDouble(1)); obs.setTime(cacheCursor.getLong(2)); cacheResults.add(obs); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS, cacheResults)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_GET_API_UNIQUE_RECENTS: CbApiCall apiUniqueCacheCall = (CbApiCall) msg.obj; log("get api recents " + apiUniqueCacheCall.toString()); // run API call db.open(); Cursor cacheUniqueCursor = db.runRecentReadingsCacheCall( apiUniqueCacheCall.getMinLat(), apiUniqueCacheCall.getMaxLat(), apiUniqueCacheCall.getMinLon(), apiUniqueCacheCall.getMaxLon(), apiUniqueCacheCall.getStartTime(), apiUniqueCacheCall.getEndTime(), apiUniqueCacheCall.getLimit()); ArrayList<CbObservation> cacheUniqueResults = new ArrayList<CbObservation>(); System.out.println("cache unique cursor count " + cacheUniqueCursor.getCount()); while (cacheUniqueCursor.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheUniqueCursor.getDouble(1)); location.setLongitude(cacheUniqueCursor.getDouble(2)); location.setAltitude(cacheUniqueCursor.getDouble(3)); location.setAccuracy(cacheUniqueCursor.getInt(4)); location.setProvider(cacheUniqueCursor.getString(5)); obs.setLocation(location); obs.setObservationType(cacheUniqueCursor.getString(6)); obs.setObservationUnit(cacheUniqueCursor.getString(7)); obs.setObservationValue(cacheUniqueCursor.getDouble(8)); obs.setSharing(cacheUniqueCursor.getString(9)); obs.setTime(cacheUniqueCursor.getLong(10)); obs.setTimeZoneOffset(cacheUniqueCursor.getInt(11)); obs.setUser_id(cacheUniqueCursor.getString(12)); //obs.setTrend(cacheUniqueCursor.getString(18)); cacheUniqueResults.add(obs); } try { msg.replyTo.send(Message.obtain(null, MSG_API_UNIQUE_RECENTS, cacheUniqueResults)); } catch (RemoteException re) { re.printStackTrace(); } db.close(); break; case MSG_MAKE_API_CALL: CbApi api = new CbApi(getApplicationContext()); CbApiCall liveApiCall = (CbApiCall) msg.obj; liveApiCall.setCallType("Readings"); long timeDiff = System.currentTimeMillis() - lastAPICall; lastAPICall = api.makeAPICall(liveApiCall, service, msg.replyTo, "Readings"); break; case MSG_MAKE_CURRENT_CONDITIONS_API_CALL: CbApi conditionApi = new CbApi(getApplicationContext()); CbApiCall conditionApiCall = (CbApiCall) msg.obj; conditionApiCall.setCallType("Conditions"); conditionApi.makeAPICall(conditionApiCall, service, msg.replyTo, "Conditions"); break; case MSG_CLEAR_LOCAL_CACHE: db.open(); db.clearLocalCache(); db.close(); break; case MSG_REMOVE_FROM_PRESSURENET: // TODO: Implement break; case MSG_CLEAR_API_CACHE: db.open(); db.clearAPICache(); db.close(); break; case MSG_ADD_CURRENT_CONDITION: CbCurrentCondition cc = (CbCurrentCondition) msg.obj; db.open(); db.addCondition(cc); db.close(); break; case MSG_GET_CURRENT_CONDITIONS: db.open(); CbApiCall currentConditionAPI = (CbApiCall) msg.obj; Cursor ccCursor = db.getCurrentConditions( currentConditionAPI.getMinLat(), currentConditionAPI.getMaxLat(), currentConditionAPI.getMinLon(), currentConditionAPI.getMaxLon(), currentConditionAPI.getStartTime(), currentConditionAPI.getEndTime(), 1000); ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>(); while(ccCursor.moveToNext()) { CbCurrentCondition cur = new CbCurrentCondition(); Location location = new Location("network"); location.setLatitude(ccCursor.getDouble(1)); location.setLongitude(ccCursor.getDouble(2)); location.setAltitude(ccCursor.getDouble(3)); location.setAccuracy(ccCursor.getInt(4)); location.setProvider(ccCursor.getString(5)); cur.setLocation(location); cur.setTime(ccCursor.getLong(6)); cur.setTime(ccCursor.getLong(7)); cur.setUser_id(ccCursor.getString(9)); cur.setGeneral_condition(ccCursor.getString(10)); cur.setWindy(ccCursor.getString(11)); cur.setFog_thickness(ccCursor.getString(12)); cur.setCloud_type(ccCursor.getString(13)); cur.setPrecipitation_type(ccCursor.getString(14)); cur.setPrecipitation_amount(ccCursor.getDouble(15)); cur.setPrecipitation_unit(ccCursor.getString(16)); cur.setThunderstorm_intensity(ccCursor.getString(17)); cur.setUser_comment(ccCursor.getString(18)); conditions.add(cur); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_CURRENT_CONDITIONS, conditions)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_SEND_CURRENT_CONDITION: CbCurrentCondition condition = (CbCurrentCondition) msg.obj; condition.setSharing_policy(settingsHandler.getShareLevel()); sendCbCurrentCondition(condition); break; case MSG_SEND_OBSERVATION: // TODO: Implement break; default: super.handleMessage(msg); } } } public boolean notifyAPIResult(Messenger reply, int count) { try { if (reply == null) { System.out.println("cannot notify, reply is null"); } else { reply.send(Message.obtain(null, MSG_API_RESULT_COUNT, count, 0)); } } catch (RemoteException re) { re.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } return false; } public CbObservation recentPressureFromDatabase() { CbObservation obs = new CbObservation(); long rowId = db.fetchObservationMaxID(); double pressure = 0.0; Cursor c = db.fetchObservation(rowId); while (c.moveToNext()) { pressure = c.getDouble(8); } log(pressure + " pressure from db"); if (pressure == 0.0) { log("returning null"); return null; } obs.setObservationValue(pressure); return obs; } private class StreamObservation extends AsyncTask<Messenger, Void, String> { @Override protected String doInBackground(Messenger... m) { try { for (Messenger msgr : m) { if (msgr != null) { msgr.send(Message.obtain(null, MSG_DATA_STREAM, recentPressureFromDatabase())); } else { log("messenger is null"); } } } catch (RemoteException re) { re.printStackTrace(); } return " } @Override protected void onPostExecute(String result) { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } public void startDataStream(Messenger m) { log("cbService starting stream " + (m == null)); dataCollector.startCollectingData(m); new StreamObservation().execute(m); } public void stopDataStream() { log("cbservice stopping stream"); dataCollector.stopCollectingData(); } /** * Get a hash'd device ID * * @return */ public String getID() { try { MessageDigest md = MessageDigest.getInstance("MD5"); String actual_id = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID); byte[] bytes = actual_id.getBytes(); byte[] digest = md.digest(bytes); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString(); } catch (Exception e) { return " } } // Used to write a log to SD card. Not used unless logging enabled. public void setUpFiles() { try { File homeDirectory = getExternalFilesDir(null); if (homeDirectory != null) { mAppDir = homeDirectory.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); } } // Log data to SD card for debug purposes. // To enable logging, ensure the Manifest allows writing to SD card. public void logToFile(String text) { try { OutputStream output = new FileOutputStream(mAppDir + "/log.txt", true); String logString = (new Date()).toString() + ": " + text + "\n"; output.write(logString.getBytes()); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { log("on bind"); return mMessenger.getBinder(); } @Override public void onRebind(Intent intent) { log("on rebind"); super.onRebind(intent); } public void log(String message) { // logToFile(message); System.out.println(message); } public CbDataCollector getDataCollector() { return dataCollector; } public void setDataCollector(CbDataCollector dataCollector) { this.dataCollector = dataCollector; } public CbLocationManager getLocationManager() { return locationManager; } public void setLocationManager(CbLocationManager locationManager) { this.locationManager = locationManager; } }
package ca.patricklam.judodb.client; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.FormElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.ValueBoxBase; import com.google.gwt.user.client.ui.Widget; public class ClientWidget extends Composite { interface MyUiBinder extends UiBinder<Widget, ClientWidget> {} public static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); private final JudoDB jdb; @UiField DivElement cid; @UiField HTMLPanel clientMain; @UiField TextBox nom; @UiField TextBox prenom; @UiField TextBox ddn_display; @UiField Hidden ddn; @UiField TextBox sexe; @UiField Anchor copysib; @UiField TextBox adresse; @UiField TextBox ville; @UiField TextBox codePostal; @UiField TextBox tel; @UiField TextBox courriel; @UiField TextBox affiliation; @UiField TextBox grade; @UiField Anchor showgrades; @UiField TextBox date_grade; @UiField TextBox carte_anjou; @UiField TextBox nom_recu_impot; @UiField TextBox tel_contact_urgence; @UiField ListBox date_inscription; @UiField InlineLabel semaines; @UiField Anchor inscrire; @UiField Anchor modifier; @UiField Anchor desinscrire; @UiField TextBox saisons; @UiField CheckBox verification; @UiField TextBox categorie; @UiField TextBox categorieFrais; @UiField ListBox cours; @UiField ListBox sessions; @UiField ListBox escompte; @UiField TextBox cas_special_note; @UiField TextBox cas_special_pct; @UiField TextBox escompteFrais; @UiField CheckBox sans_affiliation; @UiField CheckBox affiliation_initiation; @UiField TextBox affiliationFrais; @UiField ListBox judogi; @UiField CheckBox passeport; @UiField CheckBox non_anjou; @UiField TextBox suppFrais; @UiField CheckBox solde; @UiField TextBox frais; @UiField Hidden grades_encoded; @UiField Hidden grade_dates_encoded; @UiField Hidden date_inscription_encoded; @UiField Hidden saisons_encoded; @UiField Hidden verification_encoded; @UiField Hidden categorieFrais_encoded; @UiField Hidden cours_encoded; @UiField Hidden sessions_encoded; @UiField Hidden escompte_encoded; @UiField Hidden cas_special_note_encoded; @UiField Hidden cas_special_pct_encoded; @UiField Hidden escompteFrais_encoded; @UiField Hidden sans_affiliation_encoded; @UiField Hidden affiliation_initiation_encoded; @UiField Hidden affiliationFrais_encoded; @UiField Hidden judogi_encoded; @UiField Hidden passeport_encoded; @UiField Hidden non_anjou_encoded; @UiField Hidden suppFrais_encoded; @UiField Hidden solde_encoded; @UiField Hidden frais_encoded; @UiField Hidden guid_on_form; @UiField Hidden sid; @UiField Hidden deleted; @UiField Button saveClientButton; @UiField Button saveAndReturnClientButton; @UiField Button deleteClientButton; @UiField Button discardClientButton; @UiField HTMLPanel blurb; @UiField HTMLPanel gradeHistory; @UiField Grid gradeTable; @UiField Anchor saveGrades; @UiField Anchor annulerGrades; private final FormElement clientform; private static final String PULL_ONE_CLIENT_URL = JudoDB.BASE_URL + "pull_one_client.php?id="; private static final String CALLBACK_URL_SUFFIX = "&callback="; private static final String PUSH_ONE_CLIENT_URL = JudoDB.BASE_URL + "push_one_client.php"; private static final String CONFIRM_PUSH_URL = JudoDB.BASE_URL + "confirm_push.php?guid="; private int pushTries; public interface BlurbTemplate extends SafeHtmlTemplates { @Template ("<p>Je {0} certifie que les informations inscrites sur ce formulaire sont véridiques. "+ "En adhèrant au Club Judo Anjou, j'accepte tous les risques d'accident liés à la pratique du "+ "judo qui pourraient survenir dans les locaux ou lors d'activités extérieurs organisées par le Club. "+ "J'accepte de respecter les règlements du Club en tout temps y compris lors des déplacements.</p>"+ "<h4>Politique de remboursement</h4>"+ "<p>Aucun remboursement ne sera accordé sans présentation d'un certificat médical du participant. "+ "Seuls les frais de cours correspondant à la période restante sont remboursables. "+ "En cas d'annulation par le participant, un crédit pourra être émis par le Club, "+ "pour les frais de cours correspondant à la période restante.</p>"+ "<p>Signature {1}: <span style='float:right'>Date: _________</span></p>"+ "<p>Signature résponsable du club: <span style='float:right'>Date: {2}</span></p>") SafeHtml blurb(String nom, String membreOuParent, String today); } private static final BlurbTemplate BLURB = GWT.create(BlurbTemplate.class); private ClientData cd; private String guid; private int currentServiceNumber; public int getCurrentServiceNumber() { return currentServiceNumber; } private String sibid; private List<ChangeHandler> onPopulated = new ArrayList<ChangeHandler>(); public ClientWidget(int cid, JudoDB jdb) { this.jdb = jdb; initWidget(uiBinder.createAndBindUi(this)); clientform = FormElement.as(clientMain.getElementById("clientform")); clientform.setAction(PUSH_ONE_CLIENT_URL); deleted.setValue(""); for (Constants.Cours c : Constants.COURS) { cours.addItem(c.name, c.seqno); } sessions.addItem("1"); sessions.addItem("2"); for (Constants.Escompte e : Constants.ESCOMPTES) { escompte.addItem(e.name, Integer.toString(e.amount)); } for (Constants.Judogi j : Constants.JUDOGIS) { judogi.addItem(j.name, j.seqno); } gradeHistory.setVisible(false); categorie.setReadOnly(true); saisons.setReadOnly(true); categorieFrais.setReadOnly(true); categorieFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); cas_special_pct.setAlignment(ValueBoxBase.TextAlignment.RIGHT); escompteFrais.setReadOnly(true); escompteFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); affiliationFrais.setReadOnly(true); affiliationFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); suppFrais.setReadOnly(true); suppFrais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); frais.setReadOnly(true); frais.setAlignment(ValueBoxBase.TextAlignment.RIGHT); ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(Display.NONE); sessions.setItemSelected(1, true); inscrire.addClickHandler(inscrireClickHandler); modifier.addClickHandler(modifierClickHandler); desinscrire.addClickHandler(desinscrireClickHandler); showgrades.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { gradeHistory.setVisible(true); } ; }); saveGrades.addClickHandler(saveGradesHandler); annulerGrades.addClickHandler(annulerGradesHandler); adresse.addChangeHandler(updateCopySibHandler); ville.addChangeHandler(updateCopySibHandler); codePostal.addChangeHandler(updateCopySibHandler); tel.addChangeHandler(updateCopySibHandler); tel_contact_urgence.addChangeHandler(updateCopySibHandler); courriel.addChangeHandler(updateCopySibHandler); ddn_display.addChangeHandler(recomputeHandler); grade.addChangeHandler(directGradeChangeHandler); date_grade.addChangeHandler(directGradeDateChangeHandler); grade.addChangeHandler(recomputeHandler); date_inscription.addChangeHandler(changeSaisonHandler); sessions.addChangeHandler(recomputeHandler); escompte.addChangeHandler(changeEscompteHandler); cas_special_pct.addChangeHandler(clearEscompteAmtAndRecomputeHandler); escompteFrais.addChangeHandler(clearEscomptePctAndRecomputeHandler); sans_affiliation.addValueChangeHandler(recomputeValueHandler); affiliation_initiation.addValueChangeHandler(recomputeValueHandler); judogi.addChangeHandler(recomputeHandler); passeport.addValueChangeHandler(recomputeValueHandler); non_anjou.addValueChangeHandler(recomputeValueHandler); saveAndReturnClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(); ClientWidget.this.jdb.popMode(); } }); saveClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushClientDataToServer(); } }); discardClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { ClientWidget.this.jdb.clearStatus(); ClientWidget.this.jdb.popMode(); } }); deleteClientButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { pushDeleteToServer(); ClientWidget.this.jdb.popMode(); } }); copysib.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { copysib(); } }); if (!jdb.isAuthenticated) return; jdb.pleaseWait(); if (cid != -1) getJsonForPull(jdb.jsonRequestId++, PULL_ONE_CLIENT_URL + cid + CALLBACK_URL_SUFFIX, this); else { this.cd = JavaScriptObject.createObject().cast(); this.cd.setID(null); this.cd.setNom(""); this.cd.makeDefault(); JsArray<ServiceData> sa = JavaScriptObject.createArray().cast(); ServiceData sd = ServiceData.newServiceData(); sd.inscrireAujourdhui(); sa.set(0, sd); this.cd.setServices(sa); // new client: first service, // which exists because we called inscrireAujourdhui currentServiceNumber = 0; JsArray<GradeData> ga = JavaScriptObject.createArray().cast(); GradeData gd = JavaScriptObject.createObject().cast(); gd.setGrade("Blanche"); gd.setDateGrade(Constants.DB_DATE_FORMAT.format(new Date())); ga.set(0, gd); this.cd.setGrades(ga); loadClientData(); jdb.clearStatus(); } } @SuppressWarnings("deprecation") private void updateBlurb() { if (cd.getDDNString() == null) return; Date ddn = cd.getDDN(), today = new Date(); if (cd.getDDN() == null) return; int by = ddn.getYear(), bm = ddn.getMonth(), bd = ddn.getDate(), ny = today.getYear(), nm = today.getMonth(), nd = ddn.getDate(); int y = ny - by; if (bm > nm || (bm == nm && bd > nd)) y String nom = cd.getPrenom() + " " + cd.getNom(); String nn, mm; if (y >= 18) { nn = nom; mm = "membre"; } else { nn = "__________________________, parent ou tuteur du membre indiqué plus haut,"; mm = "parent ou tuteur"; } SafeHtml blurbContents = BLURB.blurb(nn, mm, Constants.STD_DATE_FORMAT.format(today)); blurb.clear(); blurb.add(new HTMLPanel(blurbContents)); } /** Takes data from ClientData into the form. */ private void loadClientData () { cid.setInnerText(cd.getID()); nom.setText(cd.getNom()); prenom.setText(cd.getPrenom()); Date ddns = cd.getDDN(); ddn_display.setText(ddns == null ? Constants.STD_DUMMY_DATE : Constants.STD_DATE_FORMAT.format(ddns)); ddn.setValue(ddns == null ? Constants.DB_DUMMY_DATE : Constants.DB_DATE_FORMAT.format(ddns)); sexe.setText(cd.getSexe()); adresse.setText(cd.getAdresse()); ville.setText(cd.getVille()); codePostal.setText(cd.getCodePostal()); tel.setText(cd.getTel()); courriel.setText(cd.getCourriel()); affiliation.setText(cd.getJudoQC()); carte_anjou.setText(cd.getCarteAnjou()); nom_recu_impot.setText(cd.getNomRecuImpot()); tel_contact_urgence.setText(cd.getTelContactUrgence()); ServiceData sd; if (currentServiceNumber == -1) { sd = ServiceData.newServiceData(); sd.inscrireAujourdhui(); } else sd = cd.getServices().get(currentServiceNumber); loadGradesData(); date_inscription.clear(); boolean hasToday = false, isToday = false; boolean hasThisSession = cd.getServiceFor(Constants.currentSession()) != null; String todayString = Constants.DB_DATE_FORMAT.format(new Date()); for (int i = 0; i < cd.getServices().length(); i++) { ServiceData ssd = cd.getServices().get(i); if (todayString.equals(ssd.getDateInscription())) { hasToday = true; isToday = (i == currentServiceNumber); } date_inscription.addItem(Constants.dbToStdDate(ssd.getDateInscription()), Integer.toString(i)); } date_inscription.setSelectedIndex(currentServiceNumber); inscrire.setVisible(!hasToday && !hasThisSession); modifier.setVisible(!hasToday && hasThisSession); desinscrire.setVisible(cd.getServices().length() > 0); // categories is set in recompute(). saisons.setText(sd.getSaisons()); verification.setValue(sd.getVerification()); int cnum = Integer.parseInt(sd.getCours()); if (cnum >= 0 && cnum < cours.getItemCount()) cours.setItemSelected(cnum, true); sessions.setItemSelected(sd.getSessionCount()-1, true); sessions.setEnabled(isToday); categorieFrais.setText(sd.getCategorieFrais()); sans_affiliation.setValue(sd.getSansAffiliation()); sans_affiliation.setEnabled(isToday); affiliation_initiation.setValue(sd.getAffiliationInitiation()); affiliation_initiation.setEnabled(isToday); affiliationFrais.setText(sd.getAffiliationFrais()); escompte.setSelectedIndex(sd.getEscompteType()); escompte.setEnabled(isToday); cas_special_note.setText(sd.getCasSpecialNote()); cas_special_note.setReadOnly(!isToday); cas_special_pct.setValue(sd.getCasSpecialPct()); cas_special_pct.setReadOnly(!isToday); escompteFrais.setText(sd.getEscompteFrais()); for (Constants.Judogi j : Constants.JUDOGIS) { if (j.amount.equals(sd.getJudogi())) judogi.setSelectedIndex(Integer.parseInt(j.seqno)); } judogi.setEnabled(isToday); passeport.setValue(sd.getPasseport()); passeport.setEnabled(isToday); non_anjou.setValue(sd.getNonAnjou()); non_anjou.setEnabled(isToday); suppFrais.setText(sd.getSuppFrais()); frais.setText(sd.getFrais()); solde.setValue(sd.getSolde()); updateDynamicFields(); } /** Puts data from the form back onto ClientData. */ private void saveClientData() { cd.setNom(nom.getText()); cd.setPrenom(prenom.getText()); cd.setDDNString(Constants.stdToDbDate(ddn_display.getText())); cd.setSexe(sexe.getText()); cd.setAdresse(adresse.getText()); cd.setVille(ville.getText()); cd.setCodePostal(codePostal.getText()); cd.setTel(tel.getText()); cd.setCourriel(courriel.getText()); cd.setJudoQC(affiliation.getText()); cd.setCarteAnjou(carte_anjou.getText()); cd.setNomRecuImpot(nom_recu_impot.getText()); cd.setTelContactUrgence(tel_contact_urgence.getText()); if (currentServiceNumber == -1) return; ServiceData sd = cd.getServices().get(currentServiceNumber); sd.setDateInscription(removeCommas(Constants.stdToDbDate(date_inscription.getItemText(currentServiceNumber)))); sd.setSaisons(removeCommas(saisons.getText())); sd.setVerification(verification.getValue()); sd.setCours(Integer.toString(cours.getSelectedIndex())); sd.setSessionCount(sessions.getSelectedIndex()+1); sd.setCategorieFrais(stripDollars(categorieFrais.getText())); sd.setSansAffiliation(sans_affiliation.getValue()); sd.setAffiliationInitiation(affiliation_initiation.getValue()); sd.setAffiliationFrais(stripDollars(affiliationFrais.getText())); sd.setEscompteType(escompte.getSelectedIndex()); sd.setCasSpecialNote(removeCommas(cas_special_note.getText())); sd.setCasSpecialPct(stripDollars(cas_special_pct.getText())); sd.setEscompteFrais(stripDollars(escompteFrais.getText())); sd.setJudogi(Constants.judogi(judogi.getValue(judogi.getSelectedIndex()))); sd.setPasseport(passeport.getValue()); sd.setNonAnjou(non_anjou.getValue()); sd.setSuppFrais(stripDollars(suppFrais.getText())); sd.setFrais(stripDollars(frais.getText())); sd.setSolde(solde.getValue()); } /** Load grades data from ClientData into the gradeTable & grade/date_grade. */ private void loadGradesData() { gradeTable.clear(); gradeTable.resize(cd.getGrades().length()+2, 2); gradeTable.setText(0, 0, "Grade"); gradeTable.getCellFormatter().setStyleName(0, 0, "{style.lwp}"); gradeTable.setText(0, 1, "Date"); gradeTable.getCellFormatter().setStyleName(0, 1, "{style.lwp}"); JsArray<GradeData> grades_ = cd.getGrades(); GradeData[] grades = new GradeData[grades_.length()]; for (int i = 0; i < grades_.length(); i++) grades[i] = grades_.get(i); Arrays.sort(grades, new GradeData.GradeComparator()); for (int i = 0; i < grades.length; i++) { setGradesTableRow(i+1, grades[i].getGrade(), Constants.dbToStdDate(grades[i].getDateGrade())); } setGradesTableRow(grades.length+1, "", ""); grade.setText(cd.getGrade()); date_grade.setText(Constants.dbToStdDate(cd.getDateGrade())); } private void setGradesTableRow(int row, String grade, String dateGrade) { TextBox g = new TextBox(); TextBox gd = new TextBox(); g.setValue(grade); g.setVisibleLength(5); gd.setValue(dateGrade); gd.setVisibleLength(10); gradeTable.setWidget(row, 0, g); gradeTable.setWidget(row, 1, gd); ((TextBox)gradeTable.getWidget(row, 0)).addChangeHandler(ensureGradeSpace); ((TextBox)gradeTable.getWidget(row, 1)).addChangeHandler(ensureGradeSpace); } private TextBox getGradeTableTextBox(int row, int col) { return (TextBox) gradeTable.getWidget(row, col); } /** If there are any empty rows in the middle, move them up. * If there is no empty row at the end, create one. */ private ChangeHandler ensureGradeSpace = new ChangeHandler() { public void onChange(ChangeEvent e) { int rc = gradeTable.getRowCount(); for (int i = 1; i < rc-2; i++) { if (getGradeTableTextBox(i, 0).getText().equals("") && getGradeTableTextBox(i, 1).getText().equals("")) { for (int j = i; j < rc-1; j++) { getGradeTableTextBox(j, 0).setText(getGradeTableTextBox(j+1, 0).getText()); getGradeTableTextBox(j, 1).setText(getGradeTableTextBox(j+1, 1).getText()); } getGradeTableTextBox(rc-1, 0).setText(""); getGradeTableTextBox(rc-1, 1).setText(""); } } if (!getGradeTableTextBox(rc-1, 0).getText().equals("") && !getGradeTableTextBox(rc-1, 1).getText().equals("")) { gradeTable.resize(rc+1, 2); setGradesTableRow(rc, "", ""); } } }; /** Save data from the grades table into the ClientData. */ private void saveGradesData() { JsArray<GradeData> newGradesJS = JavaScriptObject.createArray().cast(); ArrayList<GradeData> newGradesList = new ArrayList<GradeData>(); for (int i = 1; i < gradeTable.getRowCount(); i++) { String g = getGradeTableTextBox(i, 0).getText(), gdate = getGradeTableTextBox(i, 1).getText(); if (!g.equals("")) { GradeData gd = GradeData.createObject().cast(); gd.setGrade(g.replaceAll(",", ";")); gd.setDateGrade(Constants.stdToDbDate(gdate).replaceAll(",", ";")); newGradesList.add(gd); } } Collections.sort(newGradesList, new GradeData.GradeComparator()); int gi = 0; for (GradeData gd : newGradesList) { newGradesJS.set(gi++, gd); } cd.setGrades(newGradesJS); } private String encodeGrades() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getGrade()); } return sb.toString(); } private String encodeGradeDates() { StringBuffer sb = new StringBuffer(); JsArray<GradeData> grades = cd.getGrades(); for (int i = 0; i < grades.length(); i++) { GradeData gd = grades.get(i); if (i > 0) sb.append(","); sb.append(gd.getDateGrade()); } return sb.toString(); } private final ChangeHandler directGradeChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // either no previous grade or no previous date-grade; // erase the old grade if (date_grade.getText().equals(Constants.STD_DUMMY_DATE) || cd.getGrade().equals("")) { date_grade.setText(Constants.STD_DATE_FORMAT.format(new Date())); setGradesTableRow(1, grade.getText(), date_grade.getText()); saveGradesData(); } else { // old grade set, and has date; keep the old grade-date in the array // and update the array. ensureGradeSpace.onChange(null); date_grade.setText(Constants.STD_DATE_FORMAT.format(new Date())); setGradesTableRow(0, grade.getText(), date_grade.getText()); saveGradesData(); } } }; private final ChangeHandler directGradeDateChangeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { // TODO: if you change the grade-date, and grade is not empty, then // update the array. } }; private final ChangeHandler changeEscompteHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { if (escompte.getValue(escompte.getSelectedIndex()).equals("-1") && cas_special_pct.getValue().equals("-1")) cas_special_pct.setValue("0"); updateDynamicFields(); } }; private final ChangeHandler recomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateDynamicFields(); } }; private final ChangeHandler changeSaisonHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { saveClientData(); currentServiceNumber = Integer.parseInt(date_inscription.getValue(date_inscription.getSelectedIndex())); loadClientData(); } }; private final ChangeHandler updateCopySibHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { updateCopySib(); } }; private final ValueChangeHandler<Boolean> recomputeValueHandler = new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> e) { updateDynamicFields(); } }; private final ChangeHandler clearEscomptePctAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { cas_special_pct.setValue("-1"); regularizeEscompte(); updateDynamicFields(); } }; private final ChangeHandler clearEscompteAmtAndRecomputeHandler = new ChangeHandler() { public void onChange(ChangeEvent e) { escompteFrais.setValue("-1"); regularizeEscompte(); updateDynamicFields(); } }; /** Create a new inscription for the current session. */ private final ClickHandler inscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { saveClientData(); ServiceData sd = cd.getServiceFor(Constants.currentSession()); if (sd == null) { sd = ServiceData.newServiceData(); cd.getServices().push(sd); } // actually, sd != null should not occur; that should be modify. sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; /** Resets the date d'inscription for the current session to today's date. */ private final ClickHandler modifierClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { ServiceData sd = cd.getServiceFor(Constants.currentSession()); // shouldn't happen, actually. if (sd == null) return; saveClientData(); sd.inscrireAujourdhui(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; private final ClickHandler desinscrireClickHandler = new ClickHandler() { public void onClick(ClickEvent e) { saveClientData(); JsArray<ServiceData> newServices = JavaScriptObject.createArray().cast(); for (int i = 0, j = 0; i < cd.getServices().length(); i++) { if (i != currentServiceNumber) newServices.set(j++, cd.getServices().get(i)); } cd.setServices(newServices); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); updateDynamicFields(); } }; private int emptyGradeDates() { int empty = 0; for (int i = 1; i < gradeTable.getRowCount(); i++) { String gv = getGradeTableTextBox(i, 0).getText(); String gdv = getGradeTableTextBox(i, 1).getText(); if (gdv.equals(Constants.STD_DUMMY_DATE) || (!gv.equals("") && gv.equals(""))) empty++; } return empty; } private final ClickHandler saveGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { if (emptyGradeDates() > 1) { jdb.setStatus("Seulement une grade sans date est permise."); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); return; } saveGradesData(); loadGradesData(); gradeHistory.setVisible(false); } }; private final ClickHandler annulerGradesHandler = new ClickHandler() { public void onClick(ClickEvent e) { loadGradesData(); gradeHistory.setVisible(false); } }; /** We use , as a separator, so get rid of it in the input. */ private String removeCommas(String s) { return s.replaceAll(",", ";"); } // argh NumberFormat doesn't work for me at all! // stupidly, it says that you have to use ',' as the decimal separator, but people use both '.' and ','. private String stripDollars(String s) { StringBuffer ss = new StringBuffer(""); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '$' || s.charAt(i) == ' ' || s.charAt(i) == ')' || s.charAt(i) == '\u00a0') continue; if (s.charAt(i) == ',') ss.append("."); else if (s.charAt(i) == '(') ss.append("-"); else ss.append(s.charAt(i)); } return ss.toString(); } private static native float parseFloat(String s) /*-{ return parseFloat(s); }-*/; @SuppressWarnings("deprecation") private boolean sameDate(Date d1, Date d2) { return d1.getYear() == d2.getYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate(); } /** Enables user to edit both % escompte and escompte amount by putting them in synch. * Works directly at the View level, not the Model level. */ private void regularizeEscompte() { ServiceData sd = cd.getServices().get(currentServiceNumber); double dCategorieFrais = CostCalculator.proratedFraisCours(cd, sd); if (CostCalculator.isCasSpecial(sd)) { NumberFormat nf = NumberFormat.getDecimalFormat(); if (cas_special_pct.getValue().equals("-1")) { float actualEscompteFrais = parseFloat(stripDollars(escompteFrais.getValue())); if (actualEscompteFrais > 0) { actualEscompteFrais *= -1; escompteFrais.setValue(nf.format(actualEscompteFrais)); } cas_special_pct.setValue(nf.format(-100 * actualEscompteFrais / dCategorieFrais)); } else if (escompteFrais.getValue().equals("-1")) { String cpct = stripDollars(cas_special_pct.getValue()); float fCpct = parseFloat(cpct); if (fCpct < 0) { fCpct *= -1; cas_special_pct.setValue(nf.format(fCpct)); } escompteFrais.setValue(nf.format(-fCpct * dCategorieFrais / 100.0)); } } } /** View-level method to pull information from ServiceData and put it onto the form in currency format. */ private void updateFrais() { NumberFormat cf = NumberFormat.getCurrencyFormat("CAD"); ServiceData sd = cd.getServices().get(currentServiceNumber); Date dateInscription = Constants.DB_DATE_FORMAT.parse(sd.getDateInscription()); int sessionCount = sd.getSessionCount(); semaines.setText(CostCalculator.getWeeksSummary(Constants.currentSessionNo(), dateInscription)); escompteFrais.setReadOnly(!CostCalculator.isCasSpecial(sd)); saisons.setText(Constants.getCurrentSessionIds(sessionCount)); categorieFrais.setText (cf.format(Double.parseDouble(sd.getCategorieFrais()))); affiliationFrais.setText (cf.format(Double.parseDouble(sd.getAffiliationFrais()))); escompteFrais.setValue(cf.format(Double.parseDouble(sd.getEscompteFrais()))); suppFrais.setText(cf.format(Double.parseDouble(sd.getSuppFrais()))); frais.setText(cf.format(Double.parseDouble(sd.getFrais()))); } private void updateCopySib() { copysib.setVisible(false); // check 1) address fields are empty and 2) there exists a sibling // Note that the following check relies on the data being saved // to the ClientData, which is true after you enter the birthday. if (!cd.isDefault()) return; // oh well, tough luck! if (jdb.allClients == null) return; for (int i = 0; i < jdb.allClients.length(); i++) { ClientSummary cs = jdb.allClients.get(i); if (cs.getId().equals(cd.getID())) continue; String csn = cs.getNom().toLowerCase(); String n = nom.getText().toLowerCase(); if (n.equals(csn)) { sibid = cs.getId(); copysib.setVisible(true); } } } private void copysib() { final ClientWidget cp = new ClientWidget(Integer.parseInt(sibid), jdb); cp.onPopulated.add (new ChangeHandler () { public void onChange(ChangeEvent e) { cp.actuallyCopy(ClientWidget.this); } }); } private void actuallyCopy(ClientWidget d) { d.adresse.setText(adresse.getText()); d.ville.setText(ville.getText()); d.codePostal.setText(codePostal.getText()); d.tel.setText(tel.getText()); d.tel_contact_urgence.setText(tel_contact_urgence.getText()); d.courriel.setText(courriel.getText()); d.updateCopySib(); } private void updateDynamicFields() { saveClientData(); ServiceData sd = cd.getServices().get(currentServiceNumber); CostCalculator.recompute(cd, sd, true); /* view stuff here */ Display d = Display.NONE; if (escompte.getValue(escompte.getSelectedIndex()).equals("-1")) d = Display.INLINE; ((Element)cas_special_note.getElement().getParentNode()).getStyle().setDisplay(d); ((Element)cas_special_pct.getElement().getParentNode()).getStyle().setDisplay(d); if (sd != null && !sd.getSaisons().equals("")) { Constants.Division c = cd.getDivision(Constants.session(sd.getSaisons()).effective_year); categorie.setText(c.abbrev); } updateBlurb(); updateFrais(); updateCopySib(); } private void encodeServices() { StringBuffer di = new StringBuffer(), sais = new StringBuffer(), v = new StringBuffer(), cf = new StringBuffer(), c = new StringBuffer(), sess = new StringBuffer(), e = new StringBuffer(), csn = new StringBuffer(), csp = new StringBuffer(), ef = new StringBuffer(), sa = new StringBuffer(), ai = new StringBuffer(), af = new StringBuffer(), j = new StringBuffer(), p = new StringBuffer(), n = new StringBuffer(), sf = new StringBuffer(), s = new StringBuffer(), f = new StringBuffer(); JsArray<ServiceData> services = cd.getServices(); for (int i = 0; i < services.length(); i++) { ServiceData sd = services.get(i); di.append(sd.getDateInscription()+","); sais.append(sd.getSaisons()+","); v.append(sd.getVerification() ? "1," : "0,"); cf.append(sd.getCategorieFrais()+","); c.append(sd.getCours()+","); sess.append(Integer.toString(sd.getSessionCount())+","); e.append(Integer.toString(sd.getEscompteType())+","); csn.append(sd.getCasSpecialNote()+","); csp.append(sd.getCasSpecialPct()+","); ef.append(sd.getEscompteFrais()+","); sa.append(sd.getSansAffiliation() ? "1," : "0,"); ai.append(sd.getAffiliationInitiation() ? "1," : "0,"); af.append(sd.getAffiliationFrais()+","); j.append(sd.getJudogi()+","); p.append(sd.getPasseport()+","); n.append(sd.getNonAnjou()+","); sf.append(sd.getSuppFrais()+","); s.append(sd.getSolde() ? "1,":"0,"); f.append(sd.getFrais()+","); } date_inscription_encoded.setValue(di.toString()); saisons_encoded.setValue(sais.toString()); verification_encoded.setValue(v.toString()); categorieFrais_encoded.setValue(cf.toString()); cours_encoded.setValue(c.toString()); sessions_encoded.setValue(sess.toString()); escompte_encoded.setValue(e.toString()); cas_special_note_encoded.setValue(csn.toString()); cas_special_pct_encoded.setValue(csp.toString()); escompteFrais_encoded.setValue(ef.toString()); sans_affiliation_encoded.setValue(sa.toString()); affiliation_initiation_encoded.setValue(ai.toString()); affiliationFrais_encoded.setValue(af.toString()); judogi_encoded.setValue(j.toString()); passeport_encoded.setValue(p.toString()); non_anjou_encoded.setValue(n.toString()); suppFrais_encoded.setValue(sf.toString()); solde_encoded.setValue(s.toString()); frais_encoded.setValue(f.toString()); } private void pushClientDataToServer() { if (cd.getNom().equals("") || cd.getPrenom().equals("")) { jdb.displayError("pas de nom ou prenom"); return; } guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); grades_encoded.setValue(encodeGrades()); grade_dates_encoded.setValue(encodeGradeDates()); saveClientData(); loadClientData(); encodeServices(); clientform.submit(); pushTries = 0; new Timer() { public void run() { getJsonForStageTwoPush(jdb.jsonRequestId++, CONFIRM_PUSH_URL + guid + CALLBACK_URL_SUFFIX, ClientWidget.this); } }.schedule(500); } private void pushDeleteToServer() { // no need to delete if there's no ID yet. if (cd.getID().equals("")) return; guid = UUID.uuid(); sid.setValue(cd.getID()); guid_on_form.setValue(guid); deleted.setValue("true"); clientform.submit(); pushTries = 0; new Timer() { public void run() { getJsonForStageTwoPush(jdb.jsonRequestId++, CONFIRM_PUSH_URL + guid + CALLBACK_URL_SUFFIX, ClientWidget.this); } }.schedule(500); } /** * Make call to remote server to request client information. */ public native static void getJsonForPull(int requestId, String url, ClientWidget handler) /*-{ var callback = "callback" + requestId; var script = document.createElement("script"); script.setAttribute("src", url+callback); script.setAttribute("type", "text/javascript"); window[callback] = function(jsonObj) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonPullResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj); window[callback + "done"] = true; } setTimeout(function() { if (!window[callback + "done"]) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonPullResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null); } document.body.removeChild(script); delete window[callback]; delete window[callback + "done"]; }, 5000); document.body.appendChild(script); }-*/; /** * Handle the response to the request for data from a remote server. */ public void handleJsonPullResponse(JavaScriptObject jso) { if (jso == null) { jdb.displayError("Couldn't retrieve JSON"); return; } this.cd = jso.cast(); currentServiceNumber = cd.getMostRecentServiceNumber(); loadClientData(); jdb.clearStatus(); for (ChangeHandler ch : onPopulated) { ch.onChange(null); } } /** * Make call to remote server to request client information. */ public native static void getJsonForStageTwoPush(int requestId, String url, ClientWidget handler) /*-{ var callback = "callback" + requestId; var script = document.createElement("script"); script.setAttribute("src", url+callback); script.setAttribute("type", "text/javascript"); window[callback] = function(jsonObj) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonStageTwoPushResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj); window[callback + "done"] = true; } setTimeout(function() { if (!window[callback + "done"]) { handler.@ca.patricklam.judodb.client.ClientWidget::handleJsonStageTwoPushResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null); } document.body.removeChild(script); delete window[callback]; delete window[callback + "done"]; }, 5000); document.body.appendChild(script); }-*/; /** * Handle the response to the request for data from a remote server. */ public void handleJsonStageTwoPushResponse(JavaScriptObject jso) { if (jso == null) { if (pushTries == 3) { jdb.displayError("pas de réponse"); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); return; } else { tryConfirmPushAgain(); } } ConfirmResponseObject cro = jso.cast(); if (cro.getResult().equals("NOTYET")) { tryConfirmPushAgain(); return; } if (!cro.getResult().equals("OK")) { jdb.displayError("le serveur n'a pas accepté les données"); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); } else { jdb.setStatus("Sauvegardé."); jdb.invalidateListWidget(); new Timer() { public void run() { jdb.clearStatus(); } }.schedule(2000); if (cd.getID() == null || cd.getID().equals("")) { cd.setID(Integer.toString(cro.getSid())); loadClientData(); } } } private void tryConfirmPushAgain() { pushTries++; new Timer() { public void run() { ClientWidget.getJsonForStageTwoPush (jdb.jsonRequestId++, CONFIRM_PUSH_URL + guid + CALLBACK_URL_SUFFIX, ClientWidget.this); }}.schedule(1000); } }
package ch.hsr.ifs.pystructure.playground; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.ClassDef; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Tuple; import org.python.pydev.parser.jython.ast.Yield; import org.python.pydev.parser.jython.ast.exprType; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.StructureDefinition; import ch.hsr.ifs.pystructure.typeinference.visitors.StructuralVisitor; public class Spider extends StructuralVisitor { private static final HashSet<java.lang.Class<?>> IGNORE = new HashSet<java.lang.Class<?>>(); static { IGNORE.add(Tuple.class); IGNORE.add(Yield.class); } private Map<StructureDefinition, List<exprType>> typables; public Spider() { typables = new HashMap<StructureDefinition, List<exprType>>(); } protected void run(Module module) { super.run(module); } public Map<StructureDefinition, List<exprType>> getTypables() { return typables; } @Override public Object visitModule(org.python.pydev.parser.jython.ast.Module node) throws Exception { Module module = getDefinitionFor(node); super.visitModule(node); visitChildren(module); return null; } @Override public Object visitClassDef(ClassDef node) throws Exception { Class klass = getDefinitionFor(node); if (isFirstVisit(klass)) { return null; } super.visitClassDef(node); visitChildren(klass); return null; } @Override public Object visitFunctionDef(FunctionDef node) throws Exception { Function function = getDefinitionFor(node); if (isFirstVisit(function)) { return null; } super.visitFunctionDef(node); visitChildren(function); return null; } @Override public void traverse(SimpleNode node) throws Exception { if (node instanceof exprType) { if (IGNORE.contains(node.getClass())) { } else { exprType expression = (exprType) node; StructureDefinition definition = getCurrentStructureDefinition(); List<exprType> list = typables.get(definition); if (list == null) { list = new ArrayList<exprType>(); typables.put(definition, list); } list.add(expression); } } node.traverse(this); } }
package chronotext.android.cinder; import android.app.Activity; import android.os.Handler; import android.os.Message; import android.view.View; import chronotext.android.gl.GLView; /* * WARNING: BE SURE TO DEFINE android:screenOrientation IN THE MANIFEST * OR TO CALL setRequestedOrientation() INSIDE Activity.onCreate() * BECAUSE THE CURRENT SYSTEM IS NOT HANDLING AUTO-ROTATION */ public class CinderDelegate extends Handler { protected Activity mActivity; protected Handler mHandler; protected GLView mView; public CinderDelegate(Activity activity) { mActivity = activity; mHandler = this; mView = new GLView(activity); mView.setRenderer(new CinderRenderer(activity, this)); // WILL START THE RENDERER'S THREAD } public CinderDelegate(Activity activity, Handler handler) { this(activity); mHandler = handler; } public Activity getActivity() { return mActivity; } public Handler getHandler() { return mHandler; } public GLView getView() { return mView; } public void showView() { if (mView.getVisibility() == View.GONE) { mView.setVisibility(View.VISIBLE); } } public void hideView() { if (mView.getVisibility() == View.VISIBLE) { mView.setVisibility(View.GONE); } } public void onPause() { mView.onPause(); } public void onResume() { mView.onResume(); } public void onDestroy() { mView.onDestroy(); } public void sendMessageToSketch(int what) { sendMessageToSketch(what, null); } /* * THIS WILL BE SENT ON THE RENDERER'S THREAD */ public void sendMessageToSketch(int what, String body) { mView.sendMessage(what, body); } /* * THIS IS RECEIVED ON THE RENDERER'S THREAD */ public void receiveMessageFromSketch(int what, String body) { if (mHandler != null) { mHandler.sendMessage(Message.obtain(mHandler, what, body)); } } }
package io.silverspoon; import org.apache.camel.CamelException; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.log4j.Logger; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.silverspoon.bulldog.core.io.bus.i2c.I2cBus; import io.silverspoon.bulldog.core.io.bus.i2c.I2cConnection; public class I2cProducer extends BulldogProducer { private static final Logger log = Logger.getLogger(I2cProducer.class); private static final Object lock = new Object(); private final I2cBus i2c; private static final Pattern BODY_PATTERN = Pattern.compile("([0-9a-fA-F][0-9a-fA-F])*"); public I2cProducer(BulldogEndpoint endpoint) { super(endpoint); i2c = getEndpoint().getBoard().getI2cBuses().get(0); } public void process(Exchange exchange) throws Exception { final int length = getEndpoint().getReadLength(); final byte[] buffer = new byte[length]; final Message message = exchange.getIn(); final String address = message.getHeader("address").toString(); synchronized (lock) { if(log.isDebugEnabled()){ log.debug("Initializing I2C connection to address: " + address); } final I2cConnection connection = i2c.createI2cConnection(Byte.decode(address)); final String body = message.getBody().toString(); final Matcher bodyMatcher = BODY_PATTERN.matcher(body); if (bodyMatcher.matches()) { try { byte[] requestBuffer = new byte[body.length() / 2]; if(log.isTraceEnabled()){ log.trace("Preparing I2C message"); } for (int i = 0; i < requestBuffer.length; i++) { final String value = "0x" + body.substring(2 * i, 2 * (i + 1)); requestBuffer[i] = Integer.decode(value).byteValue(); if(log.isTraceEnabled()){ log.trace("Appending byte: " + value); } } if(log.isTraceEnabled()){ log.trace("Sending I2C message..."); } connection.writeBytes(requestBuffer); if(log.isTraceEnabled()){ log.trace("I2C message sent"); } } catch (IOException ioe) { ioe.printStackTrace(); throw new IOException("Unable to write values to I2C bus (" + i2c.getName() + ") at address " + address + "!"); } try { if (length > 0) { if(log.isTraceEnabled()){ log.trace("Recieving I2C response: "); } connection.readBytes(buffer); final StringBuffer response = new StringBuffer(); for (int i = 0; i < length; i++) { response.append(Integer.toHexString(buffer[i])); } if(log.isTraceEnabled()){ log.trace(response); } exchange.getIn().setBody(response.toString()); } else { exchange.getIn().setBody("OK"); } } catch (IOException ioe) { ioe.printStackTrace(); throw new IOException("Unable to read values from I2C bus (" + i2c.getName() + ") at address " + address + "!"); } } else { throw new CamelException("Message body [" + body + "] is invalid. It should be a sequence of hexadecimal character pairs."); } } } }
package com.dmdirc.commandline; import com.dmdirc.util.InvalidAddressException; import com.dmdirc.util.IrcAddress; import com.dmdirc.Main; import com.dmdirc.config.IdentityManager; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.updater.components.LauncherComponent; import com.dmdirc.util.resourcemanager.DMDircResourceManager; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; /** * Parses command line arguments for the client. * * @author Chris */ public class CommandLineParser { /** * The arguments that the client supports, in groups of four, in the * following order: short option, long option, description, whether or not * the option takes an argument. */ private static final Object[][] ARGUMENTS = new Object[][]{ {'c', "connect", "Connect to the specified server", Boolean.TRUE}, {'d', "directory", "Use the specified configuration directory", Boolean.TRUE}, {'e', "existing", "Try to use an existing instance of DMDirc (use with -c)", Boolean.FALSE}, {'h', "help", "Show command line options and exit", Boolean.FALSE}, {'l', "launcher", "Specifies the version of DMDirc's launcher", Boolean.TRUE}, {'p', "portable", "Enable portable mode", Boolean.FALSE}, {'r', "disable-reporting", "Disable automatic error reporting", Boolean.FALSE}, {'v', "version", "Display client version and exit", Boolean.FALSE}, }; /** A list of addresses to autoconnect to. */ private final List<IrcAddress> addresses = new ArrayList<IrcAddress>(); /** Whether to disable error reporting or not. */ private boolean disablereporting; /** The version string passed for the launcher. */ private String launcherVersion = ""; /** The RMI server we're using. */ private RemoteInterface server; /** * Creates a new instance of CommandLineParser. * * @param arguments The arguments to be parsed */ public CommandLineParser(final String ... arguments) { boolean inArg = false; char previousArg = '.'; for (String arg : arguments) { if (inArg) { processArgument(previousArg, arg); inArg = false; } else { if (arg.startsWith(" previousArg = processLongArg(arg.substring(2)); inArg = checkArgument(previousArg); } else if (arg.charAt(0) == '-') { previousArg = processShortArg(arg.substring(1)); inArg = checkArgument(previousArg); } else { doUnknownArg("Unknown argument: " + arg); } } } if (inArg) { doUnknownArg("Missing parameter for argument: " + previousArg); } if (server != null) { try { server.connect(addresses); System.exit(0); } catch (RemoteException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to execute remote connection", ex); } } RemoteServer.bind(); } /** * Checks whether the specified arg type takes an argument. If it does, * this method returns true. If it doesn't, the method processes the * argument and returns false. * * @param argument The short code of the argument * @return True if the arg requires an argument, false otherwise */ private boolean checkArgument(final char argument) { boolean needsArg = false; for (int i = 0; i < ARGUMENTS.length; i++) { if (argument == ARGUMENTS[i][0]) { needsArg = (Boolean) ARGUMENTS[i][3]; break; } } if (needsArg) { return true; } else { processArgument(argument, null); return false; } } /** * Processes the specified string as a single long argument. * * @param arg The string entered * @return The short form of the corresponding argument */ private char processLongArg(final String arg) { for (int i = 0; i < ARGUMENTS.length; i++) { if (arg.equalsIgnoreCase((String) ARGUMENTS[i][1])) { return (Character) ARGUMENTS[i][0]; } } doUnknownArg("Unknown argument: " + arg); exit(); return '.'; } /** * Processes the specified string as a single short argument. * * @param arg The string entered * @return The short form of the corresponding argument */ private char processShortArg(final String arg) { for (int i = 0; i < ARGUMENTS.length; i++) { if (arg.equals(String.valueOf(ARGUMENTS[i][0]))) { return (Character) ARGUMENTS[i][0]; } } doUnknownArg("Unknown argument: " + arg); exit(); return '.'; } /** * Processes the sepcified command-line argument. * * @param arg The short form of the argument used * @param param The (optional) string parameter for the option */ private void processArgument(final char arg, final String param) { switch (arg) { case 'c': doConnect(param); break; case 'd': doDirectory(param); break; case 'e': doExisting(); break; case 'h': doHelp(); break; case 'l': launcherVersion = param; break; case 'p': doDirectory(DMDircResourceManager.getCurrentWorkingDirectory()); break; case 'r': disablereporting = true; break; case 'v': doVersion(); break; default: // This really shouldn't ever happen, but we'll handle it nicely // anyway. doUnknownArg("Unknown argument: " + arg); break; } } /** * Informs the user that they entered an unknown argument, prints the * client help, and exits. * * @param message The message about the unknown argument to be displayed */ private void doUnknownArg(final String message) { System.out.println(message); System.out.println(); doHelp(); } /** * Exits DMDirc. */ private void exit() { System.exit(0); } /** * Handles the --connect argument. * * @param address The address the user told us to connect to */ private void doConnect(final String address) { IrcAddress myAddress = null; try { myAddress = new IrcAddress(address); addresses.add(myAddress); } catch (InvalidAddressException ex) { doUnknownArg("Invalid address specified: " + ex.getMessage()); } } /** * Handles the --existing argument. */ private void doExisting() { server = RemoteServer.getServer(); if (server == null) { System.err.println("Unable to connect to existing instance"); } } /** * Sets the config directory to the one specified. * * @param dir The new config directory */ private void doDirectory(final String dir) { Main.setConfigDir(dir); } /** * Prints out the client version and exits. */ private void doVersion() { System.out.println("DMDirc - a cross-platform, open-source IRC client."); System.out.println(); System.out.println(" Version: " + Main.VERSION); System.out.println(" SVN revision: " + Main.SVN_REVISION); System.out.println(" Channel: " + Main.UPDATE_CHANNEL); exit(); } /** * Prints out client help and exits. */ private void doHelp() { System.out.println("Usage: java -jar DMDirc.jar [options]"); System.out.println(); System.out.println("Valid options:"); System.out.println(); int maxLength = 0; for (Object[] arg : ARGUMENTS) { final String needsArg = ((Boolean) arg[3]) ? " <argument>" : ""; if ((arg[1] + needsArg).length() > maxLength) { maxLength = (arg[1] + needsArg).length(); } } for (Object[] arg : ARGUMENTS) { final String needsArg = ((Boolean) arg[3]) ? " <argument>" : ""; final StringBuilder desc = new StringBuilder(maxLength + 1); desc.append(arg[1]); while (desc.length() < maxLength + 1) { desc.append(' '); } System.out.print(" -" + arg[0] + needsArg); System.out.println(" --" + desc + needsArg + " " + arg[2]); System.out.println(); } exit(); } /** * Applies any applicable settings to the config identity. */ public void applySettings() { if (disablereporting) { IdentityManager.getConfigIdentity().setOption("temp", "noerrorreporting", true); } if (!launcherVersion.isEmpty()) { LauncherComponent.setLauncherInfo(launcherVersion); } } /** * Processes arguments once the client has been loaded properly. * This allows us to auto-connect to servers, etc. */ public void processArguments() { for (IrcAddress address : addresses) { address.connect(); } } }
package com.google.sps.data; import java.util.ArrayList; /* This class stores data on various features in the model */ public class FeatureData { private static ArrayList<Precinct> precinctData; private final int NUMBER_OF_PRECINCTS = 10; static { precinctData = new ArrayList<Precinct>(); Precinct southern = new Precinct(); southern.setName("Southern"); southern.setPopulation(40384); southern.setAverageHouseholdIncome(153727.5f); southern.setCrimeRate(calculateRate(72, 40384)); southern.setPoliceStationRating(3.0f); Precinct mission = new Precinct(); mission.setName("Mission"); mission.setPopulation(128223); mission.setAverageHouseholdIncome(164227.67f); mission.setCrimeRate(calculateRate(139, 128223)); mission.setPoliceStationRating(4.3f); Precinct bayview = new Precinct(); bayview.setName("Bayview"); bayview.setPopulation(50538); bayview.setAverageHouseholdIncome(138774.5f); bayview.setCrimeRate(calculateRate(115, 50538)); bayview.setPoliceStationRating(4.3f); Precinct tenderloin = new Precinct(); tenderloin.setName("Tenderloin"); tenderloin.setPopulation(56322); tenderloin.setAverageHouseholdIncome(134441f); tenderloin.setCrimeRate(calculateRate(37, 56322)); tenderloin.setPoliceStationRating(2.9f); Precinct central = new Precinct(); central.setName("Central"); central.setPopulation(56322); central.setAverageHouseholdIncome(134441f); central.setCrimeRate(calculateRate(132, 56322)); central.setPoliceStationRating(3.3f); Precinct ingleside = new Precinct(); ingleside.setName("Ingleside"); ingleside.setPopulation(175634); ingleside.setAverageHouseholdIncome(155101.67f); ingleside.setCrimeRate(calculateRate(102, 175634)); ingleside.setPoliceStationRating(3.6f); Precinct taraval = new Precinct(); taraval.setName("Taraval"); taraval.setPopulation(171554); taraval.setAverageHouseholdIncome(136967f); taraval.setCrimeRate(calculateRate(89, 171554)); taraval.setPoliceStationRating(4.2f); Precinct park = new Precinct(); park.setName("Park"); park.setPopulation(152902); park.setAverageHouseholdIncome(179955.2f); park.setCrimeRate(calculateRate(71, 152902)); park.setPoliceStationRating(2.4f); Precinct northern = new Precinct(); northern.setName("Northern"); northern.setPopulation(117963); northern.setAverageHouseholdIncome(180944.67f); northern.setCrimeRate(calculateRate(199, 117963)); northern.setPoliceStationRating(2.6f); Precinct richmond = new Precinct(); richmond.setName("Richmond"); richmond.setPopulation(136904); richmond.setAverageHouseholdIncome(146030f); richmond.setCrimeRate(calculateRate(104, 136904)); richmond.setPoliceStationRating(2.8f); precinctData.add(southern); precinctData.add(mission); precinctData.add(bayview); precinctData.add(tenderloin); precinctData.add(central); precinctData.add(ingleside); precinctData.add(taraval); precinctData.add(park); precinctData.add(richmond); precinctData.add(northern); } /** * Calculates the crime per 1,000 residents * * @param numCrimes Total reported crimes in a precinct for the current month * @param population Population of the precinct * @return float Crime rate for the precinct */ public static float calculateRate(int numCrimes, int population) { final int PER_RESIDENTS = 1000; return (float) numCrimes / ((float) population / PER_RESIDENTS); } /** * Find and return a precinct by name * * @param name Name of the precinct * @return Precinct precinct with matching name */ public static Precinct getPrecinct(String name) { for (Precinct p : precinctData) { String precinctName = p.getName(); if (precinctName.equals(name)) { return p; } } return null; } }