diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/tests/src/com/android/contacts/ContactLoaderTest.java b/tests/src/com/android/contacts/ContactLoaderTest.java index d923bfa9b..1d3fb20de 100644 --- a/tests/src/com/android/contacts/ContactLoaderTest.java +++ b/tests/src/com/android/contacts/ContactLoaderTest.java @@ -1,355 +1,355 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts; import com.android.contacts.tests.mocks.ContactsMockContext; import com.android.contacts.tests.mocks.MockContentProvider; import android.content.ContentUris; import android.net.Uri; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.DisplayNameSources; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.StatusUpdates; import android.test.LoaderTestCase; import android.test.suitebuilder.annotation.LargeTest; /** * Runs ContactLoader tests for the the contact-detail and editor view. */ @LargeTest public class ContactLoaderTest extends LoaderTestCase { ContactsMockContext mMockContext; MockContentProvider mContactsProvider; @Override protected void setUp() throws Exception { super.setUp(); mMockContext = new ContactsMockContext(getContext()); mContactsProvider = mMockContext.getContactsProvider(); } @Override protected void tearDown() throws Exception { super.tearDown(); } private ContactLoader.Result assertLoadContact(Uri uri) { final ContactLoader loader = new ContactLoader(mMockContext, uri); return getLoaderResultSynchronously(loader); } public void testNullUri() { ContactLoader.Result result = assertLoadContact(null); assertEquals(ContactLoader.Result.ERROR, result); } public void testEmptyUri() { ContactLoader.Result result = assertLoadContact(Uri.EMPTY); assertEquals(ContactLoader.Result.ERROR, result); } public void testInvalidUri() { ContactLoader.Result result = assertLoadContact(Uri.parse("content://wtf")); assertEquals(ContactLoader.Result.ERROR, result); } public void testLoadContactWithContactIdUri() { // Use content Uris that only contain the ID final long contactId = 1; final long rawContactId = 11; final long dataId = 21; final String lookupKey = "aa%12%@!"; final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); final Uri entityUri = Uri.withAppendedPath(baseUri, Contacts.Entity.CONTENT_DIRECTORY); final Uri lookupUri = ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId); ContactQueries queries = new ContactQueries(); mContactsProvider.expectTypeQuery(baseUri, Contacts.CONTENT_ITEM_TYPE); queries.fetchAllData(entityUri, contactId, rawContactId, dataId, lookupKey); ContactLoader.Result contact = assertLoadContact(baseUri); assertEquals(contactId, contact.getId()); assertEquals(rawContactId, contact.getNameRawContactId()); assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource()); assertEquals(lookupKey, contact.getLookupKey()); assertEquals(lookupUri, contact.getLookupUri()); assertEquals(1, contact.getEntities().size()); assertEquals(1, contact.getStatuses().size()); mContactsProvider.verify(); } public void testLoadContactWithOldStyleUri() { // Use content Uris that only contain the ID but use the format used in Donut final long contactId = 1; final long rawContactId = 11; final long dataId = 21; final String lookupKey = "aa%12%@!"; final Uri legacyUri = ContentUris.withAppendedId( Uri.parse("content://contacts"), rawContactId); final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); final Uri lookupUri = ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId); final Uri entityUri = Uri.withAppendedPath(lookupUri, Contacts.Entity.CONTENT_DIRECTORY); ContactQueries queries = new ContactQueries(); queries.fetchContactIdAndLookupFromRawContactUri(rawContactUri, contactId, lookupKey); queries.fetchAllData(entityUri, contactId, rawContactId, dataId, lookupKey); ContactLoader.Result contact = assertLoadContact(legacyUri); assertEquals(contactId, contact.getId()); assertEquals(rawContactId, contact.getNameRawContactId()); assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource()); assertEquals(lookupKey, contact.getLookupKey()); assertEquals(lookupUri, contact.getLookupUri()); assertEquals(1, contact.getEntities().size()); assertEquals(1, contact.getStatuses().size()); mContactsProvider.verify(); } public void testLoadContactWithRawContactIdUri() { // Use content Uris that only contain the ID but use the format used in Donut final long contactId = 1; final long rawContactId = 11; final long dataId = 21; final String lookupKey = "aa%12%@!"; final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); final Uri lookupUri = ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId); final Uri entityUri = Uri.withAppendedPath(lookupUri, Contacts.Entity.CONTENT_DIRECTORY); ContactQueries queries = new ContactQueries(); mContactsProvider.expectTypeQuery(rawContactUri, RawContacts.CONTENT_ITEM_TYPE); queries.fetchContactIdAndLookupFromRawContactUri(rawContactUri, contactId, lookupKey); queries.fetchAllData(entityUri, contactId, rawContactId, dataId, lookupKey); ContactLoader.Result contact = assertLoadContact(rawContactUri); assertEquals(contactId, contact.getId()); assertEquals(rawContactId, contact.getNameRawContactId()); assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource()); assertEquals(lookupKey, contact.getLookupKey()); assertEquals(lookupUri, contact.getLookupUri()); assertEquals(1, contact.getEntities().size()); assertEquals(1, contact.getStatuses().size()); mContactsProvider.verify(); } public void testLoadContactWithContactLookupUri() { // Use lookup-style Uris that do not contain the Contact-ID final long contactId = 1; final long rawContactId = 11; final long dataId = 21; final String lookupKey = "aa%12%@!"; final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); final Uri lookupNoIdUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey); final Uri lookupUri = ContentUris.withAppendedId(lookupNoIdUri, contactId); final Uri entityUri = Uri.withAppendedPath(lookupNoIdUri, Contacts.Entity.CONTENT_DIRECTORY); ContactQueries queries = new ContactQueries(); mContactsProvider.expectTypeQuery(lookupNoIdUri, Contacts.CONTENT_ITEM_TYPE); queries.fetchAllData(entityUri, contactId, rawContactId, dataId, lookupKey); ContactLoader.Result contact = assertLoadContact(lookupNoIdUri); assertEquals(contactId, contact.getId()); assertEquals(rawContactId, contact.getNameRawContactId()); assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource()); assertEquals(lookupKey, contact.getLookupKey()); assertEquals(lookupUri, contact.getLookupUri()); assertEquals(1, contact.getEntities().size()); assertEquals(1, contact.getStatuses().size()); mContactsProvider.verify(); } public void testLoadContactWithContactLookupAndIdUri() { // Use lookup-style Uris that also contain the Contact-ID final long contactId = 1; final long rawContactId = 11; final long dataId = 21; final String lookupKey = "aa%12%@!"; final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); final Uri lookupUri = ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId); final Uri entityUri = Uri.withAppendedPath(lookupUri, Contacts.Entity.CONTENT_DIRECTORY); ContactQueries queries = new ContactQueries(); mContactsProvider.expectTypeQuery(lookupUri, Contacts.CONTENT_ITEM_TYPE); queries.fetchAllData(entityUri, contactId, rawContactId, dataId, lookupKey); ContactLoader.Result contact = assertLoadContact(lookupUri); assertEquals(contactId, contact.getId()); assertEquals(rawContactId, contact.getNameRawContactId()); assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource()); assertEquals(lookupKey, contact.getLookupKey()); assertEquals(lookupUri, contact.getLookupUri()); assertEquals(1, contact.getEntities().size()); assertEquals(1, contact.getStatuses().size()); mContactsProvider.verify(); } public void testLoadContactWithContactLookupWithIncorrectIdUri() { // Use lookup-style Uris that contain incorrect Contact-ID // (we want to ensure that still the correct contact is chosen) final long contactId = 1; final long wrongContactId = 2; final long rawContactId = 11; final long wrongRawContactId = 12; final long dataId = 21; final String lookupKey = "aa%12%@!"; final String wrongLookupKey = "ab%12%@!"; final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); final Uri wrongBaseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, wrongContactId); final Uri lookupUri = ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), contactId); final Uri lookupWithWrongIdUri = ContentUris.withAppendedId( Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey), wrongContactId); final Uri entityUri = Uri.withAppendedPath(lookupWithWrongIdUri, Contacts.Entity.CONTENT_DIRECTORY); ContactQueries queries = new ContactQueries(); mContactsProvider.expectTypeQuery(lookupWithWrongIdUri, Contacts.CONTENT_ITEM_TYPE); queries.fetchAllData(entityUri, contactId, rawContactId, dataId, lookupKey); ContactLoader.Result contact = assertLoadContact(lookupWithWrongIdUri); assertEquals(contactId, contact.getId()); assertEquals(rawContactId, contact.getNameRawContactId()); assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource()); assertEquals(lookupKey, contact.getLookupKey()); assertEquals(lookupUri, contact.getLookupUri()); assertEquals(1, contact.getEntities().size()); assertEquals(1, contact.getStatuses().size()); mContactsProvider.verify(); } class ContactQueries { public void fetchAllData( Uri baseUri, long contactId, long rawContactId, long dataId, String encodedLookup) { mContactsProvider.expectQuery(baseUri) .withProjection(new String[] { Contacts.NAME_RAW_CONTACT_ID, Contacts.DISPLAY_NAME_SOURCE, Contacts.LOOKUP_KEY, Contacts.DISPLAY_NAME, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.PHONETIC_NAME, Contacts.PHOTO_ID, Contacts.STARRED, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.Entity.CONTACT_ID, Contacts.Entity.RAW_CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DIRTY, RawContacts.VERSION, RawContacts.SOURCE_ID, RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, RawContacts.SYNC4, RawContacts.DELETED, RawContacts.NAME_VERIFIED, Contacts.Entity.DATA_ID, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.MIMETYPE, Data.RES_PACKAGE, GroupMembership.GROUP_SOURCE_ID, Data.PRESENCE, Data.CHAT_CAPABILITY, Data.STATUS, Data.STATUS_RES_PACKAGE, Data.STATUS_ICON, Data.STATUS_LABEL, Data.STATUS_TIMESTAMP, Contacts.PHOTO_URI, }) .withSortOrder(Contacts.Entity.RAW_CONTACT_ID) .returnRow( rawContactId, 40, "aa%12%@!", "John Doe", "Doe, John", "jdo", 0, 0, StatusUpdates.AVAILABLE, "Having lunch", 0, "mockPkg1", 10, contactId, rawContactId, "mockAccountName", "mockAccountType", 0, 1, 0, "sync1", "sync2", "sync3", "sync4", - 0, 0, 0, + 0, 0, dataId, "dat1", "dat2", "dat3", "dat4", "dat5", "dat6", "dat7", "dat8", "dat9", "dat10", "dat11", "dat12", "dat13", "dat14", "dat15", "syn1", "syn2", "syn3", "syn4", 0, 0, 0, StructuredName.CONTENT_ITEM_TYPE, "mockPkg2", "groupId", StatusUpdates.INVISIBLE, null, "Having dinner", "mockPkg3", 0, 20, 0, "content:some.photo.uri" ); } void fetchLookupAndId(final Uri sourceUri, final long expectedContactId, final String expectedEncodedLookup) { mContactsProvider.expectQuery(sourceUri) .withProjection(Contacts.LOOKUP_KEY, Contacts._ID) .returnRow(expectedEncodedLookup, expectedContactId); } void fetchContactIdAndLookupFromRawContactUri(final Uri rawContactUri, final long expectedContactId, final String expectedEncodedLookup) { // TODO: use a lighter query by joining rawcontacts with contacts in provider // (See ContactContracts.java) final Uri dataUri = Uri.withAppendedPath(rawContactUri, RawContacts.Data.CONTENT_DIRECTORY); mContactsProvider.expectQuery(dataUri) .withProjection(RawContacts.CONTACT_ID, Contacts.LOOKUP_KEY) .returnRow(expectedContactId, expectedEncodedLookup); } } }
true
true
public void fetchAllData( Uri baseUri, long contactId, long rawContactId, long dataId, String encodedLookup) { mContactsProvider.expectQuery(baseUri) .withProjection(new String[] { Contacts.NAME_RAW_CONTACT_ID, Contacts.DISPLAY_NAME_SOURCE, Contacts.LOOKUP_KEY, Contacts.DISPLAY_NAME, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.PHONETIC_NAME, Contacts.PHOTO_ID, Contacts.STARRED, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.Entity.CONTACT_ID, Contacts.Entity.RAW_CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DIRTY, RawContacts.VERSION, RawContacts.SOURCE_ID, RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, RawContacts.SYNC4, RawContacts.DELETED, RawContacts.NAME_VERIFIED, Contacts.Entity.DATA_ID, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.MIMETYPE, Data.RES_PACKAGE, GroupMembership.GROUP_SOURCE_ID, Data.PRESENCE, Data.CHAT_CAPABILITY, Data.STATUS, Data.STATUS_RES_PACKAGE, Data.STATUS_ICON, Data.STATUS_LABEL, Data.STATUS_TIMESTAMP, Contacts.PHOTO_URI, }) .withSortOrder(Contacts.Entity.RAW_CONTACT_ID) .returnRow( rawContactId, 40, "aa%12%@!", "John Doe", "Doe, John", "jdo", 0, 0, StatusUpdates.AVAILABLE, "Having lunch", 0, "mockPkg1", 10, contactId, rawContactId, "mockAccountName", "mockAccountType", 0, 1, 0, "sync1", "sync2", "sync3", "sync4", 0, 0, 0, dataId, "dat1", "dat2", "dat3", "dat4", "dat5", "dat6", "dat7", "dat8", "dat9", "dat10", "dat11", "dat12", "dat13", "dat14", "dat15", "syn1", "syn2", "syn3", "syn4", 0, 0, 0, StructuredName.CONTENT_ITEM_TYPE, "mockPkg2", "groupId", StatusUpdates.INVISIBLE, null, "Having dinner", "mockPkg3", 0, 20, 0, "content:some.photo.uri" ); }
public void fetchAllData( Uri baseUri, long contactId, long rawContactId, long dataId, String encodedLookup) { mContactsProvider.expectQuery(baseUri) .withProjection(new String[] { Contacts.NAME_RAW_CONTACT_ID, Contacts.DISPLAY_NAME_SOURCE, Contacts.LOOKUP_KEY, Contacts.DISPLAY_NAME, Contacts.DISPLAY_NAME_ALTERNATIVE, Contacts.PHONETIC_NAME, Contacts.PHOTO_ID, Contacts.STARRED, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_LABEL, Contacts.Entity.CONTACT_ID, Contacts.Entity.RAW_CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DIRTY, RawContacts.VERSION, RawContacts.SOURCE_ID, RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, RawContacts.SYNC4, RawContacts.DELETED, RawContacts.NAME_VERIFIED, Contacts.Entity.DATA_ID, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, Data.SYNC1, Data.SYNC2, Data.SYNC3, Data.SYNC4, Data.DATA_VERSION, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.MIMETYPE, Data.RES_PACKAGE, GroupMembership.GROUP_SOURCE_ID, Data.PRESENCE, Data.CHAT_CAPABILITY, Data.STATUS, Data.STATUS_RES_PACKAGE, Data.STATUS_ICON, Data.STATUS_LABEL, Data.STATUS_TIMESTAMP, Contacts.PHOTO_URI, }) .withSortOrder(Contacts.Entity.RAW_CONTACT_ID) .returnRow( rawContactId, 40, "aa%12%@!", "John Doe", "Doe, John", "jdo", 0, 0, StatusUpdates.AVAILABLE, "Having lunch", 0, "mockPkg1", 10, contactId, rawContactId, "mockAccountName", "mockAccountType", 0, 1, 0, "sync1", "sync2", "sync3", "sync4", 0, 0, dataId, "dat1", "dat2", "dat3", "dat4", "dat5", "dat6", "dat7", "dat8", "dat9", "dat10", "dat11", "dat12", "dat13", "dat14", "dat15", "syn1", "syn2", "syn3", "syn4", 0, 0, 0, StructuredName.CONTENT_ITEM_TYPE, "mockPkg2", "groupId", StatusUpdates.INVISIBLE, null, "Having dinner", "mockPkg3", 0, 20, 0, "content:some.photo.uri" ); }
diff --git a/src/main/java/net/minecraft/server/ItemFood.java b/src/main/java/net/minecraft/server/ItemFood.java index 9e4b60c..32779b6 100755 --- a/src/main/java/net/minecraft/server/ItemFood.java +++ b/src/main/java/net/minecraft/server/ItemFood.java @@ -1,111 +1,111 @@ package net.minecraft.server; import net.canarymod.Canary; import net.canarymod.api.potion.CanaryPotionEffect; import net.canarymod.hook.player.EatHook; public class ItemFood extends Item { public final int a; private final int b; private final float c; private final boolean d; private boolean cu; private int cv; private int cw; private int cx; private float cy; public ItemFood(int i0, int i1, float f0, boolean flag0) { super(i0); this.a = 32; this.b = i1; this.d = flag0; this.c = f0; this.a(CreativeTabs.h); } public ItemFood(int i0, int i1, boolean flag0) { this(i0, i1, 0.6F, flag0); } public ItemStack b(ItemStack itemstack, World world, EntityPlayer entityplayer) { // CanaryMod: Eat net.canarymod.api.potion.PotionEffect[] effects = null; - if (this instanceof ItemAppleGold && !world.I) { + if (this instanceof ItemAppleGold && !world.I && itemstack.k() > 0) { effects = new net.canarymod.api.potion.PotionEffect[] { new CanaryPotionEffect(new PotionEffect(Potion.l.H, 600, 3)), new CanaryPotionEffect(new PotionEffect(Potion.m.H, 6000, 0)), new CanaryPotionEffect(new PotionEffect(Potion.n.H, 6000, 0)) }; } else if (!world.I && this.cv > 0 && world.s.nextFloat() < this.cy) { effects = new net.canarymod.api.potion.PotionEffect[] { new CanaryPotionEffect(new PotionEffect(this.cv, this.cw * 20, this.cx)) }; } EatHook hook = new EatHook(((EntityPlayerMP) entityplayer).getPlayer(), itemstack.getCanaryItem(), this.g(), this.h(), effects); Canary.hooks().callHook(hook); if (!hook.isCanceled()) { --itemstack.a; entityplayer.cn().a(hook.getLevelGain(), hook.getSaturationGain()); world.a((Entity) entityplayer, "random.burp", 0.5F, world.s.nextFloat() * 0.1F + 0.9F); // this.c(itemstack, world, entityplayer); moved above and below if (hook.getPotionEffects() != null) { for (net.canarymod.api.potion.PotionEffect effect : hook.getPotionEffects()) { if (effect != null) { entityplayer.d(((CanaryPotionEffect) effect).getHandle()); } } } } // return itemstack; } protected void c(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (!world.I && this.cv > 0 && world.s.nextFloat() < this.cy) { entityplayer.d(new PotionEffect(this.cv, this.cw * 20, this.cx)); } } public int c_(ItemStack itemstack) { return 32; } public EnumAction b_(ItemStack itemstack) { return EnumAction.b; } public ItemStack a(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (entityplayer.i(this.cu)) { entityplayer.a(itemstack, this.c_(itemstack)); } return itemstack; } public int g() { return this.b; } public float h() { return this.c; } public boolean i() { return this.d; } public ItemFood a(int i0, int i1, int i2, float f0) { this.cv = i0; this.cw = i1; this.cx = i2; this.cy = f0; return this; } public ItemFood j() { this.cu = true; return this; } }
true
true
public ItemStack b(ItemStack itemstack, World world, EntityPlayer entityplayer) { // CanaryMod: Eat net.canarymod.api.potion.PotionEffect[] effects = null; if (this instanceof ItemAppleGold && !world.I) { effects = new net.canarymod.api.potion.PotionEffect[] { new CanaryPotionEffect(new PotionEffect(Potion.l.H, 600, 3)), new CanaryPotionEffect(new PotionEffect(Potion.m.H, 6000, 0)), new CanaryPotionEffect(new PotionEffect(Potion.n.H, 6000, 0)) }; } else if (!world.I && this.cv > 0 && world.s.nextFloat() < this.cy) { effects = new net.canarymod.api.potion.PotionEffect[] { new CanaryPotionEffect(new PotionEffect(this.cv, this.cw * 20, this.cx)) }; } EatHook hook = new EatHook(((EntityPlayerMP) entityplayer).getPlayer(), itemstack.getCanaryItem(), this.g(), this.h(), effects); Canary.hooks().callHook(hook); if (!hook.isCanceled()) { --itemstack.a; entityplayer.cn().a(hook.getLevelGain(), hook.getSaturationGain()); world.a((Entity) entityplayer, "random.burp", 0.5F, world.s.nextFloat() * 0.1F + 0.9F); // this.c(itemstack, world, entityplayer); moved above and below if (hook.getPotionEffects() != null) { for (net.canarymod.api.potion.PotionEffect effect : hook.getPotionEffects()) { if (effect != null) { entityplayer.d(((CanaryPotionEffect) effect).getHandle()); } } } } // return itemstack; }
public ItemStack b(ItemStack itemstack, World world, EntityPlayer entityplayer) { // CanaryMod: Eat net.canarymod.api.potion.PotionEffect[] effects = null; if (this instanceof ItemAppleGold && !world.I && itemstack.k() > 0) { effects = new net.canarymod.api.potion.PotionEffect[] { new CanaryPotionEffect(new PotionEffect(Potion.l.H, 600, 3)), new CanaryPotionEffect(new PotionEffect(Potion.m.H, 6000, 0)), new CanaryPotionEffect(new PotionEffect(Potion.n.H, 6000, 0)) }; } else if (!world.I && this.cv > 0 && world.s.nextFloat() < this.cy) { effects = new net.canarymod.api.potion.PotionEffect[] { new CanaryPotionEffect(new PotionEffect(this.cv, this.cw * 20, this.cx)) }; } EatHook hook = new EatHook(((EntityPlayerMP) entityplayer).getPlayer(), itemstack.getCanaryItem(), this.g(), this.h(), effects); Canary.hooks().callHook(hook); if (!hook.isCanceled()) { --itemstack.a; entityplayer.cn().a(hook.getLevelGain(), hook.getSaturationGain()); world.a((Entity) entityplayer, "random.burp", 0.5F, world.s.nextFloat() * 0.1F + 0.9F); // this.c(itemstack, world, entityplayer); moved above and below if (hook.getPotionEffects() != null) { for (net.canarymod.api.potion.PotionEffect effect : hook.getPotionEffects()) { if (effect != null) { entityplayer.d(((CanaryPotionEffect) effect).getHandle()); } } } } // return itemstack; }
diff --git a/astrid/src/com/todoroo/astrid/service/UpgradeService.java b/astrid/src/com/todoroo/astrid/service/UpgradeService.java index 13107af1b..b54a21859 100644 --- a/astrid/src/com/todoroo/astrid/service/UpgradeService.java +++ b/astrid/src/com/todoroo/astrid/service/UpgradeService.java @@ -1,689 +1,689 @@ /** * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.service; import java.util.Date; import org.weloveastrid.rmilk.data.MilkNoteHelper; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.timsu.astrid.R; import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.Property.StringProperty; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.actfm.sync.ActFmPreferenceService; import com.todoroo.astrid.activity.Eula; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.SortHelper; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.gtasks.GtasksPreferenceService; import com.todoroo.astrid.helper.DueDateTimeMigrator; import com.todoroo.astrid.notes.NoteMetadata; import com.todoroo.astrid.producteev.sync.ProducteevDataService; import com.todoroo.astrid.service.abtesting.ABChooser; import com.todoroo.astrid.tags.TagCaseMigrator; import com.todoroo.astrid.utility.AstridPreferences; public final class UpgradeService { public static final int V4_4_1 = 286; public static final int V4_4 = 285; public static final int V4_3_4_2 = 284; public static final int V4_3_4_1 = 283; public static final int V4_3_4 = 282; public static final int V4_3_3 = 281; public static final int V4_3_2 = 280; public static final int V4_3_1 = 279; public static final int V4_3_0 = 278; public static final int V4_2_6 = 277; public static final int V4_2_5 = 276; public static final int V4_2_4 = 275; public static final int V4_2_3 = 274; public static final int V4_2_2_1 = 273; public static final int V4_2_2 = 272; public static final int V4_2_1 = 271; public static final int V4_2_0 = 270; public static final int V4_1_3_1 = 269; public static final int V4_1_3 = 268; public static final int V4_1_2 = 267; public static final int V4_1_1 = 266; public static final int V4_1_0 = 265; public static final int V4_0_6_2 = 264; public static final int V4_0_6_1 = 263; public static final int V4_0_6 = 262; public static final int V4_0_5_1 = 261; public static final int V4_0_5 = 260; public static final int V4_0_4_3 = 259; public static final int V4_0_4_2 = 258; public static final int V4_0_4_1 = 257; public static final int V4_0_4 = 256; public static final int V4_0_3 = 255; public static final int V4_0_2_1 = 254; public static final int V4_0_2 = 253; public static final int V4_0_1 = 252; public static final int V4_0_0 = 251; public static final int V3_9_2_3 = 210; public static final int V3_9_2_2 = 209; public static final int V3_9_2_1 = 208; public static final int V3_9_2 = 207; public static final int V3_9_1_1 = 206; public static final int V3_9_1 = 205; public static final int V3_9_0_2 = 204; public static final int V3_9_0_1 = 203; public static final int V3_9_0 = 202; public static final int V3_8_5_1 = 201; public static final int V3_8_5 = 200; public static final int V3_8_4_4 = 199; public static final int V3_8_4_3 = 198; public static final int V3_8_4_2 = 197; public static final int V3_8_4_1 = 196; public static final int V3_8_4 = 195; public static final int V3_8_3_1 = 194; public static final int V3_8_3 = 192; public static final int V3_8_2 = 191; public static final int V3_8_0_2 = 188; public static final int V3_8_0 = 186; public static final int V3_7_7 = 184; public static final int V3_7_6 = 182; public static final int V3_7_5 = 179; public static final int V3_7_4 = 178; public static final int V3_7_3 = 175; public static final int V3_7_2 = 174; public static final int V3_7_1 = 173; public static final int V3_7_0 = 172; public static final int V3_6_4 = 170; public static final int V3_6_3 = 169; public static final int V3_6_2 = 168; public static final int V3_6_0 = 166; public static final int V3_5_0 = 165; public static final int V3_4_0 = 162; public static final int V3_3_0 = 155; public static final int V3_2_0 = 147; public static final int V3_1_0 = 146; public static final int V3_0_0 = 136; public static final int V2_14_4 = 135; @Autowired Database database; @Autowired TaskService taskService; @Autowired MetadataService metadataService; @Autowired GtasksPreferenceService gtasksPreferenceService; @Autowired ABChooser abChooser; @Autowired AddOnService addOnService; @Autowired ActFmPreferenceService actFmPreferenceService; public UpgradeService() { DependencyInjectionService.getInstance().inject(this); } /** * Perform upgrade from one version to the next. Needs to be called * on the UI thread so it can display a progress bar and then * show users a change log. * * @param from * @param to */ public void performUpgrade(final Context context, final int from) { if(from == 135) AddOnService.recordOem(); if(from > 0 && from < V3_8_2) { if(Preferences.getBoolean(R.string.p_transparent_deprecated, false)) Preferences.setString(R.string.p_theme, "transparent"); //$NON-NLS-1$ else Preferences.setString(R.string.p_theme, "black"); //$NON-NLS-1$ } if( from<= V3_9_1_1) { actFmPreferenceService.clearLastSyncDate(); } // long running tasks: pop up a progress dialog final ProgressDialog dialog; if(from < V4_0_6 && context instanceof Activity) dialog = DialogUtilities.progressDialog(context, context.getString(R.string.DLG_upgrading)); else dialog = null; final String lastSetVersionName = AstridPreferences.getCurrentVersionName(); Preferences.setInt(AstridPreferences.P_UPGRADE_FROM, from); new Thread(new Runnable() { @Override public void run() { try { // NOTE: This line should be uncommented whenever any new version requires a data migration // TasksXmlExporter.exportTasks(context, TasksXmlExporter.ExportType.EXPORT_TYPE_ON_UPGRADE, null, null, lastSetVersionName); if(from < V3_0_0) new Astrid2To3UpgradeHelper().upgrade2To3(context, from); if(from < V3_1_0) new Astrid2To3UpgradeHelper().upgrade3To3_1(context, from); if(from < V3_8_3_1) new TagCaseMigrator().performTagCaseMigration(context); if(from < V3_8_4 && Preferences.getBoolean(R.string.p_showNotes, false)) taskService.clearDetails(Task.NOTES.neq("")); //$NON-NLS-1$ if (from < V4_0_6) new DueDateTimeMigrator().migrateDueTimes(); } finally { DialogUtilities.dismissDialog((Activity)context, dialog); context.sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH)); } } }).start(); } /** * Return a change log string. Releases occur often enough that we don't * expect change sets to be localized. * * @param from * @param to * @return */ @SuppressWarnings("nls") public void showChangeLog(Context context, int from) { if(!(context instanceof Activity) || from == 0) return; Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT); Preferences.clear(AstridPreferences.P_UPGRADE_FROM); StringBuilder changeLog = new StringBuilder(); if (from >= V4_4 && from < V4_4_1) { - newVersionString(changeLog, "4.4.1 (10/31/12)", new String[] { + newVersionString(changeLog, "4.4.1 (10/30/12)", new String[] { "Fixed an issue where the calendar assistant could remind you about the wrong events", "Fixed a crash that could occur when swipe between lists is enabled" }); } if (from < V4_4) { newVersionString(changeLog, "4.4 (10/25/12)", new String[] { "Astrid calendar assistant will help you prepare for meetings! Enable or " + "disable in Settings -> Premium and misc. settings -> Calendar assistant", "Full Chinese translation", "Widgets will now reflect manual ordering", "Accept pending friend requests from the people view", "Several minor bug and crash fixes" }); } if (from >= V4_3_0 && from < V4_3_4) { newVersionString(changeLog, "4.3.4 (10/2/12)", new String[] { "Magic words in task title now correctly removed when placed in parentheses", "Bug fix for viewing Featured Lists with swipe enabled", "Bug fixes for rare crashes" }); } if (from >= V4_3_0 && from < V4_3_3) { newVersionString(changeLog, "4.3.3 (9/19/12)", new String[] { "Reverse sort works again!", "Swipe between lists is faster", "Option for a new style of task row (Try it: Settings -> Appearance -> Task row appearance and choose \"Simple\")", "A few other small bugs fixed" }); } if (from >= V4_3_0 && from < V4_3_2) { newVersionString(changeLog, "4.3.2 (9/07/12)", new String[] { "Fixed issues with Google Tasks shortcuts" }); } if (from >= V4_3_0 && from < V4_3_1) { newVersionString(changeLog, "4.3.1 (9/06/12)", new String[] { "Fixed crashes for Google Tasks users and certain filters", "Added ability to complete shared tasks from list view" }); } if (from < V4_3_0) { newVersionString(changeLog, "4.3.0 (9/05/12)", new String[] { "Significant performance improvements", "Voice-add now enabled for all users!", "New feature: Featured lists (Enable in Settings -> Appearance)", "New and improved premium widget design", "Redesigned settings page", "Improved translations", "Lots of bug fixes and UI polish" }); } if (from >= V4_2_0 && from < V4_2_6) { newVersionString(changeLog, "4.2.6 (8/14/12)", new String[] { "Tablet users can opt to use the single-pane phone layout (Settings -> Astrid Labs)", "Minor polish and bug fixes" }); } if (from >= V4_2_0 && from < V4_2_5) { newVersionString(changeLog, "4.2.5 (8/13/12)", new String[] { "Improved tablet UX", "More customizable task edit screen", "Add to calendar now starts at task due time (by default)", "Updated translations for several languages", "Numerous bug fixes" }); } if (from >= V4_2_0 && from < V4_2_4) { newVersionString(changeLog, "4.2.4 (7/11/12)", new String[] { "Ability to specify end date on repeating tasks", "Improved sync of comments made while offline", "Crash fixes" }); } if (from >= V4_2_0 && from < V4_2_3) { newVersionString(changeLog, "4.2.3 (6/25/12)", new String[] { "Fixes for Google Tasks and Astrid.com sync", "New layout for tablets in portrait mode", "Minor UI polish and bugfixes" }); } if (from >= V4_2_0 && from < V4_2_2_1) { newVersionString(changeLog, "4.2.2.1 (6/13/12)", new String[] { "Fixed a crash affecting the Nook" }); } if (from >= V4_2_0 && from < V4_2_2) { newVersionString(changeLog, "4.2.2 (6/12/12)", new String[] { "Fix for people views displaying the wrong list of tasks", "Fixed a bug with Astrid Smart Sort", "Fixed a bug when adding photo comments" }); } if (from >= V4_2_0 && from < V4_2_1) { newVersionString(changeLog, "4.2.1 (6/08/12)", new String[] { "Fix for MyTouch 4G Lists", "Fixed a crash when adding tasks with due times to Google Calendar", "Better syncing of the people list", "Minor UI polish and bugfixes" }); } if (from < V4_2_0) { newVersionString(changeLog, "4.2.0 (6/05/12)", new String[] { "Support for the Nook", "Fixed crash on large image attachments", "Minor bugfixes" }); } if (from >= V4_1_3 && from < V4_1_3_1) { newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] { "Fixed reminders for ICS" }); } if (from >= V4_1_2 && from < V4_1_3) { newVersionString(changeLog, "4.1.3 (5/17/12)", new String[] { "Added ability to see shared tasks sorted by friend! Enable or disable " + "in Settings > Astrid Labs", "Fixed desktop shortcuts", "Fixed adding tasks from the Power Pack widget", "Fixed selecting photos on the Kindle Fire", "Various other minor bug and crash fixes" }); } if (from >= V4_1_1 && from < V4_1_2) { newVersionString(changeLog, "4.1.2 (5/05/12)", new String[] { "Fixed some crashes and minor bugs" }); } if (from < V4_1_1) { newVersionString(changeLog, "4.1.1 (5/04/12)", new String[] { "Respond to or set reminders for missed calls. This feature requires a new permission to read " + "the phone state.", }); } if (from < V4_1_0) { newVersionString(changeLog, "4.1.0 (5/03/12)", new String[] { "Swipe between lists! Swipe left and right to move through your lists. Enable or adjust " + "in Settings > Astrid Labs", "Assign tasks to contacts without typing", "Links to tasks in comments", "Astrid.com sync improvements", "Other minor bugfixes", }); } if (from >= V4_0_6 && from < V4_0_6_2) { newVersionString(changeLog, "4.0.6.2 (4/03/12)", new String[] { "Minor fix to backup migration fix to handle deleted tasks as well as completed tasks." }); } if (from >= V4_0_6 && from < V4_0_6_1) { newVersionString(changeLog, "4.0.6.1 (4/03/12)", new String[] { "Fixed a bug where old tasks could become uncompleted. Sorry to those of you" + " who were affected by this! To recover, you can import your old tasks" + " from any backup file created before April 3 by clicking Menu -> Settings ->" + " Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start" + " with 'auto.120403'." }); } if (from < V4_0_6) { newVersionString(changeLog, "4.0.6 (4/02/12)", new String[] { "Fixes and performance improvements to Astrid.com and Google Tasks sync", "Google TV support! (Beta)", "Fixed a bug that could put duetimes on tasks when changing timezones", "Fixed a rare crash when starting a task timer" }); } if (from >= V4_0_0 && from < V4_0_5) { newVersionString(changeLog, "4.0.5 (3/22/12)", new String[] { "Better conflict resolution for Astrid.com sync", "Fixes and improvements to Gtasks sync", "Added option to report sync errors in sync preference screen" }); } if (from >= V4_0_0 && from < V4_0_4) { newVersionString(changeLog, "4.0.4 (3/7/12)", new String[] { "Fixed crashes related to error reporting", "Fixed a crash when creating a task from the widget", "Fixed a bug where a manual sync wouldn't always start" }); } if (from >= V4_0_0 && from < V4_0_3) { newVersionString(changeLog, "4.0.3 (3/6/12)", new String[] { "Fix some issues with Google Tasks sync. We're sorry to " + "everyone who's been having trouble with it!", "Updated translations for Portuguese, Chinese, German, Russian, and Dutch", "Centralize Android's menu key with in-app navigation", "Fixed crashes & improve crash logging", }); } if (from >= V4_0_0 && from < V4_0_2) { newVersionString(changeLog, "4.0.2 (2/29/12)", new String[] { "Removed GPS permission - no longer needed", "Fixes for some subtasks issues", "No longer need to run the Crittercism service in the background", "Fixed a crash that could occur when cloning tasks", "Fixed a bug that prevented certain comments from syncing correctly", "Fixed issues where voice add wouldn't work correctly", }); } if (from >= V4_0_0 && from < V4_0_1) { newVersionString(changeLog, "4.0.1 (2/23/12)", new String[] { "Fixed a database issue affecting Android 2.1 users", "Fixed a crash when using drag and drop in Google Tasks lists", "Other small bugfixes" }); } if (from < V4_0_0) { newVersionString(changeLog, "4.0.0 (2/23/12)", new String[] { "Welcome to Astrid 4.0! Here's what's new:", "<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access", "<b>New Look!</b><br>Customize how Astrid looks from the Settings menu", "<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people", "<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync", "<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet", "Many bug and usability fixes" }); } // --- old messages if (from >= V3_0_0 && from < V3_9_0) { newVersionString(changeLog, "3.9 (12/09/11)", new String[] { "Cleaner design (especially the task edit page)!", "Customize the edit page (\"Beast Mode\" in preferences)", "Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)", "Fixes for some ICS crashes (full support coming soon)", "Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.", "Other minor bug fixes", "Feedback welcomed!" }); } if(from >= V3_0_0 && from < V3_8_0) { newVersionString(changeLog, "3.8.0 (7/15/11)", new String[] { "Astrid.com: sync & share tasks / lists with others!", "GTasks Sync using Google's official task API! Gtasks users " + "will need to perform a manual sync to set everything up.", "Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)", "New style for \"Task Edit\" page!", "Purge completed or deleted tasks from settings menu!", }); gtasksPreferenceService.setToken(null); } if(from >= V3_0_0 && from < V3_7_0) { newVersionString(changeLog, "3.7.0 (2/7/11)", new String[] { "Improved UI for displaying task actions. Tap a task to " + "bring up actions, tap again to dismiss.", "Task notes can be viewed by tapping the note icon to " + "the right of the task.", "Added Astrid as 'Send-To' choice in Android Browser and " + "other apps.", "Add tags and importance in quick-add, e.g. " + "\"call mom #family @phone !4\"", "Fixed bug with custom filters & tasks being hidden.", }); upgrade3To3_7(); if(gtasksPreferenceService.isLoggedIn()) taskService.clearDetails(Criterion.all); Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true); } if(from >= V3_0_0 && from < V3_6_0) { newVersionString(changeLog, "3.6.0 (11/13/10)", new String[] { "Astrid Power Pack is now launched to the Android Market. " + "New Power Pack features include 4x2 and 4x4 widgets and voice " + "task reminders and creation. Go to the add-ons page to find out more!", "Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated", "Fix for task alarms not always firing if multiple set", "Fix for various force closes", }); upgrade3To3_6(context); } if(from >= V3_0_0 && from < V3_5_0) newVersionString(changeLog, "3.5.0 (10/25/10)", new String[] { "Google Tasks Sync (beta!)", "Bug fix with RMilk & new tasks not getting synced", "Fixed Force Closes and other bugs", }); if(from >= V3_0_0 && from < V3_4_0) { newVersionString(changeLog, "3.4.0 (10/08/10)", new String[] { "End User License Agreement", "Option to disable usage statistics", "Bug fixes with Producteev", }); } if(from >= V3_0_0 && from < V3_3_0) newVersionString(changeLog, "3.3.0 (9/17/10)", new String[] { "Fixed some RTM duplicated tasks issues", "UI updates based on your feedback", "Snooze now overrides other alarms", "Added preference option for selecting snooze style", "Hide until: now allows you to pick a specific time", }); if(from >= V3_0_0 && from < V3_2_0) newVersionString(changeLog, "3.2.0 (8/16/10)", new String[] { "Build your own custom filters from the Filter page", "Easy task sorting (in the task list menu)", "Create widgets from any of your filters", "Synchronize with Producteev! (producteev.com)", "Select tags by drop-down box", "Cosmetic improvements, calendar & sync bug fixes", }); if(from >= V3_0_0 && from < V3_1_0) newVersionString(changeLog, "3.1.0 (8/9/10)", new String[] { "Linkify phone numbers, e-mails, and web pages", "Swipe L => R to go from tasks to filters", "Moved task priority bar to left side", "Added ability to create fixed alerts for a task", "Restored tag hiding when tag begins with underscore (_)", "FROYO: disabled moving app to SD card, it would break alarms and widget", "Also gone: a couple force closes, bugs with repeating tasks", }); if(changeLog.length() == 0) return; changeLog.append("Enjoy!</body></html>"); String color = ThemeService.getDialogTextColorString(); String changeLogHtml = "<html><body style='color: " + color +"'>" + changeLog; DialogUtilities.htmlDialog(context, changeLogHtml, R.string.UpS_changelog_title); } /** * Helper for adding a single version to the changelog * @param changeLog * @param version * @param changes */ @SuppressWarnings("nls") private void newVersionString(StringBuilder changeLog, String version, String[] changes) { changeLog.append("<font style='text-align: center; color=#ffaa00'><b>Version ").append(version).append(":</b></font><br><ul>"); for(String change : changes) changeLog.append("<li>").append(change).append("</li>\n"); changeLog.append("</ul>"); } // --- upgrade functions /** * Fixes task filter missing tasks bug, migrate PDV/RTM notes */ @SuppressWarnings("nls") private void upgrade3To3_7() { TodorooCursor<Task> t = taskService.query(Query.select(Task.ID, Task.DUE_DATE).where(Task.DUE_DATE.gt(0))); Task task = new Task(); for(t.moveToFirst(); !t.isAfterLast(); t.moveToNext()) { task.readFromCursor(t); if(task.hasDueDate()) { task.setValue(Task.DUE_DATE, task.getValue(Task.DUE_DATE) / 1000L * 1000L); taskService.save(task); } } t.close(); TodorooCursor<Metadata> m = metadataService.query(Query.select(Metadata.PROPERTIES). where(Criterion.or(Metadata.KEY.eq("producteev-note"), Metadata.KEY.eq("rmilk-note")))); StringProperty PDV_NOTE_ID = Metadata.VALUE1; StringProperty PDV_NOTE_MESSAGE = Metadata.VALUE2; LongProperty PDV_NOTE_CREATED = new LongProperty(Metadata.TABLE, Metadata.VALUE3.name); StringProperty RTM_NOTE_ID = Metadata.VALUE1; StringProperty RTM_NOTE_TITLE = Metadata.VALUE2; StringProperty RTM_NOTE_TEXT = Metadata.VALUE3; LongProperty RTM_NOTE_CREATED = new LongProperty(Metadata.TABLE, Metadata.VALUE4.name); Metadata metadata = new Metadata(); for(m.moveToFirst(); !m.isAfterLast(); m.moveToNext()) { metadata.readFromCursor(m); String id, body, title, provider; long created; if("rmilk-note".equals(metadata.getValue(Metadata.KEY))) { id = metadata.getValue(RTM_NOTE_ID); body = metadata.getValue(RTM_NOTE_TEXT); title = metadata.getValue(RTM_NOTE_TITLE); created = metadata.getValue(RTM_NOTE_CREATED); provider = MilkNoteHelper.PROVIDER; } else { id = metadata.getValue(PDV_NOTE_ID); body = metadata.getValue(PDV_NOTE_MESSAGE); created = metadata.getValue(PDV_NOTE_CREATED); title = DateUtilities.getDateStringWithWeekday(ContextManager.getContext(), new Date(created)); provider = ProducteevDataService.NOTE_PROVIDER; } metadata.setValue(Metadata.KEY, NoteMetadata.METADATA_KEY); metadata.setValue(Metadata.CREATION_DATE, created); metadata.setValue(NoteMetadata.BODY, body); metadata.setValue(NoteMetadata.TITLE, title); metadata.setValue(NoteMetadata.THUMBNAIL, null); metadata.setValue(NoteMetadata.EXT_PROVIDER, provider); metadata.setValue(NoteMetadata.EXT_ID, id); metadata.clearValue(Metadata.ID); metadataService.save(metadata); } m.close(); } /** * Moves sorting prefs to public pref store * @param context */ private void upgrade3To3_6(final Context context) { SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context); Editor editor = publicPrefs.edit(); editor.putInt(SortHelper.PREF_SORT_FLAGS, Preferences.getInt(SortHelper.PREF_SORT_FLAGS, 0)); editor.putInt(SortHelper.PREF_SORT_SORT, Preferences.getInt(SortHelper.PREF_SORT_SORT, 0)); editor.commit(); } // --- secondary upgrade /** * If primary upgrade doesn't work for some reason (corrupt SharedPreferences, * for example), this will catch some cases */ public void performSecondaryUpgrade(Context context) { if(!context.getDatabasePath(database.getName()).exists() && context.getDatabasePath("tasks").exists()) { //$NON-NLS-1$ new Astrid2To3UpgradeHelper().upgrade2To3(context, 1); } } }
true
true
public void showChangeLog(Context context, int from) { if(!(context instanceof Activity) || from == 0) return; Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT); Preferences.clear(AstridPreferences.P_UPGRADE_FROM); StringBuilder changeLog = new StringBuilder(); if (from >= V4_4 && from < V4_4_1) { newVersionString(changeLog, "4.4.1 (10/31/12)", new String[] { "Fixed an issue where the calendar assistant could remind you about the wrong events", "Fixed a crash that could occur when swipe between lists is enabled" }); } if (from < V4_4) { newVersionString(changeLog, "4.4 (10/25/12)", new String[] { "Astrid calendar assistant will help you prepare for meetings! Enable or " + "disable in Settings -> Premium and misc. settings -> Calendar assistant", "Full Chinese translation", "Widgets will now reflect manual ordering", "Accept pending friend requests from the people view", "Several minor bug and crash fixes" }); } if (from >= V4_3_0 && from < V4_3_4) { newVersionString(changeLog, "4.3.4 (10/2/12)", new String[] { "Magic words in task title now correctly removed when placed in parentheses", "Bug fix for viewing Featured Lists with swipe enabled", "Bug fixes for rare crashes" }); } if (from >= V4_3_0 && from < V4_3_3) { newVersionString(changeLog, "4.3.3 (9/19/12)", new String[] { "Reverse sort works again!", "Swipe between lists is faster", "Option for a new style of task row (Try it: Settings -> Appearance -> Task row appearance and choose \"Simple\")", "A few other small bugs fixed" }); } if (from >= V4_3_0 && from < V4_3_2) { newVersionString(changeLog, "4.3.2 (9/07/12)", new String[] { "Fixed issues with Google Tasks shortcuts" }); } if (from >= V4_3_0 && from < V4_3_1) { newVersionString(changeLog, "4.3.1 (9/06/12)", new String[] { "Fixed crashes for Google Tasks users and certain filters", "Added ability to complete shared tasks from list view" }); } if (from < V4_3_0) { newVersionString(changeLog, "4.3.0 (9/05/12)", new String[] { "Significant performance improvements", "Voice-add now enabled for all users!", "New feature: Featured lists (Enable in Settings -> Appearance)", "New and improved premium widget design", "Redesigned settings page", "Improved translations", "Lots of bug fixes and UI polish" }); } if (from >= V4_2_0 && from < V4_2_6) { newVersionString(changeLog, "4.2.6 (8/14/12)", new String[] { "Tablet users can opt to use the single-pane phone layout (Settings -> Astrid Labs)", "Minor polish and bug fixes" }); } if (from >= V4_2_0 && from < V4_2_5) { newVersionString(changeLog, "4.2.5 (8/13/12)", new String[] { "Improved tablet UX", "More customizable task edit screen", "Add to calendar now starts at task due time (by default)", "Updated translations for several languages", "Numerous bug fixes" }); } if (from >= V4_2_0 && from < V4_2_4) { newVersionString(changeLog, "4.2.4 (7/11/12)", new String[] { "Ability to specify end date on repeating tasks", "Improved sync of comments made while offline", "Crash fixes" }); } if (from >= V4_2_0 && from < V4_2_3) { newVersionString(changeLog, "4.2.3 (6/25/12)", new String[] { "Fixes for Google Tasks and Astrid.com sync", "New layout for tablets in portrait mode", "Minor UI polish and bugfixes" }); } if (from >= V4_2_0 && from < V4_2_2_1) { newVersionString(changeLog, "4.2.2.1 (6/13/12)", new String[] { "Fixed a crash affecting the Nook" }); } if (from >= V4_2_0 && from < V4_2_2) { newVersionString(changeLog, "4.2.2 (6/12/12)", new String[] { "Fix for people views displaying the wrong list of tasks", "Fixed a bug with Astrid Smart Sort", "Fixed a bug when adding photo comments" }); } if (from >= V4_2_0 && from < V4_2_1) { newVersionString(changeLog, "4.2.1 (6/08/12)", new String[] { "Fix for MyTouch 4G Lists", "Fixed a crash when adding tasks with due times to Google Calendar", "Better syncing of the people list", "Minor UI polish and bugfixes" }); } if (from < V4_2_0) { newVersionString(changeLog, "4.2.0 (6/05/12)", new String[] { "Support for the Nook", "Fixed crash on large image attachments", "Minor bugfixes" }); } if (from >= V4_1_3 && from < V4_1_3_1) { newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] { "Fixed reminders for ICS" }); } if (from >= V4_1_2 && from < V4_1_3) { newVersionString(changeLog, "4.1.3 (5/17/12)", new String[] { "Added ability to see shared tasks sorted by friend! Enable or disable " + "in Settings > Astrid Labs", "Fixed desktop shortcuts", "Fixed adding tasks from the Power Pack widget", "Fixed selecting photos on the Kindle Fire", "Various other minor bug and crash fixes" }); } if (from >= V4_1_1 && from < V4_1_2) { newVersionString(changeLog, "4.1.2 (5/05/12)", new String[] { "Fixed some crashes and minor bugs" }); } if (from < V4_1_1) { newVersionString(changeLog, "4.1.1 (5/04/12)", new String[] { "Respond to or set reminders for missed calls. This feature requires a new permission to read " + "the phone state.", }); } if (from < V4_1_0) { newVersionString(changeLog, "4.1.0 (5/03/12)", new String[] { "Swipe between lists! Swipe left and right to move through your lists. Enable or adjust " + "in Settings > Astrid Labs", "Assign tasks to contacts without typing", "Links to tasks in comments", "Astrid.com sync improvements", "Other minor bugfixes", }); } if (from >= V4_0_6 && from < V4_0_6_2) { newVersionString(changeLog, "4.0.6.2 (4/03/12)", new String[] { "Minor fix to backup migration fix to handle deleted tasks as well as completed tasks." }); } if (from >= V4_0_6 && from < V4_0_6_1) { newVersionString(changeLog, "4.0.6.1 (4/03/12)", new String[] { "Fixed a bug where old tasks could become uncompleted. Sorry to those of you" + " who were affected by this! To recover, you can import your old tasks" + " from any backup file created before April 3 by clicking Menu -> Settings ->" + " Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start" + " with 'auto.120403'." }); } if (from < V4_0_6) { newVersionString(changeLog, "4.0.6 (4/02/12)", new String[] { "Fixes and performance improvements to Astrid.com and Google Tasks sync", "Google TV support! (Beta)", "Fixed a bug that could put duetimes on tasks when changing timezones", "Fixed a rare crash when starting a task timer" }); } if (from >= V4_0_0 && from < V4_0_5) { newVersionString(changeLog, "4.0.5 (3/22/12)", new String[] { "Better conflict resolution for Astrid.com sync", "Fixes and improvements to Gtasks sync", "Added option to report sync errors in sync preference screen" }); } if (from >= V4_0_0 && from < V4_0_4) { newVersionString(changeLog, "4.0.4 (3/7/12)", new String[] { "Fixed crashes related to error reporting", "Fixed a crash when creating a task from the widget", "Fixed a bug where a manual sync wouldn't always start" }); } if (from >= V4_0_0 && from < V4_0_3) { newVersionString(changeLog, "4.0.3 (3/6/12)", new String[] { "Fix some issues with Google Tasks sync. We're sorry to " + "everyone who's been having trouble with it!", "Updated translations for Portuguese, Chinese, German, Russian, and Dutch", "Centralize Android's menu key with in-app navigation", "Fixed crashes & improve crash logging", }); } if (from >= V4_0_0 && from < V4_0_2) { newVersionString(changeLog, "4.0.2 (2/29/12)", new String[] { "Removed GPS permission - no longer needed", "Fixes for some subtasks issues", "No longer need to run the Crittercism service in the background", "Fixed a crash that could occur when cloning tasks", "Fixed a bug that prevented certain comments from syncing correctly", "Fixed issues where voice add wouldn't work correctly", }); } if (from >= V4_0_0 && from < V4_0_1) { newVersionString(changeLog, "4.0.1 (2/23/12)", new String[] { "Fixed a database issue affecting Android 2.1 users", "Fixed a crash when using drag and drop in Google Tasks lists", "Other small bugfixes" }); } if (from < V4_0_0) { newVersionString(changeLog, "4.0.0 (2/23/12)", new String[] { "Welcome to Astrid 4.0! Here's what's new:", "<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access", "<b>New Look!</b><br>Customize how Astrid looks from the Settings menu", "<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people", "<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync", "<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet", "Many bug and usability fixes" }); } // --- old messages if (from >= V3_0_0 && from < V3_9_0) { newVersionString(changeLog, "3.9 (12/09/11)", new String[] { "Cleaner design (especially the task edit page)!", "Customize the edit page (\"Beast Mode\" in preferences)", "Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)", "Fixes for some ICS crashes (full support coming soon)", "Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.", "Other minor bug fixes", "Feedback welcomed!" }); } if(from >= V3_0_0 && from < V3_8_0) { newVersionString(changeLog, "3.8.0 (7/15/11)", new String[] { "Astrid.com: sync & share tasks / lists with others!", "GTasks Sync using Google's official task API! Gtasks users " + "will need to perform a manual sync to set everything up.", "Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)", "New style for \"Task Edit\" page!", "Purge completed or deleted tasks from settings menu!", }); gtasksPreferenceService.setToken(null); } if(from >= V3_0_0 && from < V3_7_0) { newVersionString(changeLog, "3.7.0 (2/7/11)", new String[] { "Improved UI for displaying task actions. Tap a task to " + "bring up actions, tap again to dismiss.", "Task notes can be viewed by tapping the note icon to " + "the right of the task.", "Added Astrid as 'Send-To' choice in Android Browser and " + "other apps.", "Add tags and importance in quick-add, e.g. " + "\"call mom #family @phone !4\"", "Fixed bug with custom filters & tasks being hidden.", }); upgrade3To3_7(); if(gtasksPreferenceService.isLoggedIn()) taskService.clearDetails(Criterion.all); Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true); } if(from >= V3_0_0 && from < V3_6_0) { newVersionString(changeLog, "3.6.0 (11/13/10)", new String[] { "Astrid Power Pack is now launched to the Android Market. " + "New Power Pack features include 4x2 and 4x4 widgets and voice " + "task reminders and creation. Go to the add-ons page to find out more!", "Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated", "Fix for task alarms not always firing if multiple set", "Fix for various force closes", }); upgrade3To3_6(context); } if(from >= V3_0_0 && from < V3_5_0) newVersionString(changeLog, "3.5.0 (10/25/10)", new String[] { "Google Tasks Sync (beta!)", "Bug fix with RMilk & new tasks not getting synced", "Fixed Force Closes and other bugs", }); if(from >= V3_0_0 && from < V3_4_0) { newVersionString(changeLog, "3.4.0 (10/08/10)", new String[] { "End User License Agreement", "Option to disable usage statistics", "Bug fixes with Producteev", }); } if(from >= V3_0_0 && from < V3_3_0) newVersionString(changeLog, "3.3.0 (9/17/10)", new String[] { "Fixed some RTM duplicated tasks issues", "UI updates based on your feedback", "Snooze now overrides other alarms", "Added preference option for selecting snooze style", "Hide until: now allows you to pick a specific time", }); if(from >= V3_0_0 && from < V3_2_0) newVersionString(changeLog, "3.2.0 (8/16/10)", new String[] { "Build your own custom filters from the Filter page", "Easy task sorting (in the task list menu)", "Create widgets from any of your filters", "Synchronize with Producteev! (producteev.com)", "Select tags by drop-down box", "Cosmetic improvements, calendar & sync bug fixes", }); if(from >= V3_0_0 && from < V3_1_0) newVersionString(changeLog, "3.1.0 (8/9/10)", new String[] { "Linkify phone numbers, e-mails, and web pages", "Swipe L => R to go from tasks to filters", "Moved task priority bar to left side", "Added ability to create fixed alerts for a task", "Restored tag hiding when tag begins with underscore (_)", "FROYO: disabled moving app to SD card, it would break alarms and widget", "Also gone: a couple force closes, bugs with repeating tasks", }); if(changeLog.length() == 0) return; changeLog.append("Enjoy!</body></html>"); String color = ThemeService.getDialogTextColorString(); String changeLogHtml = "<html><body style='color: " + color +"'>" + changeLog; DialogUtilities.htmlDialog(context, changeLogHtml, R.string.UpS_changelog_title); }
public void showChangeLog(Context context, int from) { if(!(context instanceof Activity) || from == 0) return; Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT); Preferences.clear(AstridPreferences.P_UPGRADE_FROM); StringBuilder changeLog = new StringBuilder(); if (from >= V4_4 && from < V4_4_1) { newVersionString(changeLog, "4.4.1 (10/30/12)", new String[] { "Fixed an issue where the calendar assistant could remind you about the wrong events", "Fixed a crash that could occur when swipe between lists is enabled" }); } if (from < V4_4) { newVersionString(changeLog, "4.4 (10/25/12)", new String[] { "Astrid calendar assistant will help you prepare for meetings! Enable or " + "disable in Settings -> Premium and misc. settings -> Calendar assistant", "Full Chinese translation", "Widgets will now reflect manual ordering", "Accept pending friend requests from the people view", "Several minor bug and crash fixes" }); } if (from >= V4_3_0 && from < V4_3_4) { newVersionString(changeLog, "4.3.4 (10/2/12)", new String[] { "Magic words in task title now correctly removed when placed in parentheses", "Bug fix for viewing Featured Lists with swipe enabled", "Bug fixes for rare crashes" }); } if (from >= V4_3_0 && from < V4_3_3) { newVersionString(changeLog, "4.3.3 (9/19/12)", new String[] { "Reverse sort works again!", "Swipe between lists is faster", "Option for a new style of task row (Try it: Settings -> Appearance -> Task row appearance and choose \"Simple\")", "A few other small bugs fixed" }); } if (from >= V4_3_0 && from < V4_3_2) { newVersionString(changeLog, "4.3.2 (9/07/12)", new String[] { "Fixed issues with Google Tasks shortcuts" }); } if (from >= V4_3_0 && from < V4_3_1) { newVersionString(changeLog, "4.3.1 (9/06/12)", new String[] { "Fixed crashes for Google Tasks users and certain filters", "Added ability to complete shared tasks from list view" }); } if (from < V4_3_0) { newVersionString(changeLog, "4.3.0 (9/05/12)", new String[] { "Significant performance improvements", "Voice-add now enabled for all users!", "New feature: Featured lists (Enable in Settings -> Appearance)", "New and improved premium widget design", "Redesigned settings page", "Improved translations", "Lots of bug fixes and UI polish" }); } if (from >= V4_2_0 && from < V4_2_6) { newVersionString(changeLog, "4.2.6 (8/14/12)", new String[] { "Tablet users can opt to use the single-pane phone layout (Settings -> Astrid Labs)", "Minor polish and bug fixes" }); } if (from >= V4_2_0 && from < V4_2_5) { newVersionString(changeLog, "4.2.5 (8/13/12)", new String[] { "Improved tablet UX", "More customizable task edit screen", "Add to calendar now starts at task due time (by default)", "Updated translations for several languages", "Numerous bug fixes" }); } if (from >= V4_2_0 && from < V4_2_4) { newVersionString(changeLog, "4.2.4 (7/11/12)", new String[] { "Ability to specify end date on repeating tasks", "Improved sync of comments made while offline", "Crash fixes" }); } if (from >= V4_2_0 && from < V4_2_3) { newVersionString(changeLog, "4.2.3 (6/25/12)", new String[] { "Fixes for Google Tasks and Astrid.com sync", "New layout for tablets in portrait mode", "Minor UI polish and bugfixes" }); } if (from >= V4_2_0 && from < V4_2_2_1) { newVersionString(changeLog, "4.2.2.1 (6/13/12)", new String[] { "Fixed a crash affecting the Nook" }); } if (from >= V4_2_0 && from < V4_2_2) { newVersionString(changeLog, "4.2.2 (6/12/12)", new String[] { "Fix for people views displaying the wrong list of tasks", "Fixed a bug with Astrid Smart Sort", "Fixed a bug when adding photo comments" }); } if (from >= V4_2_0 && from < V4_2_1) { newVersionString(changeLog, "4.2.1 (6/08/12)", new String[] { "Fix for MyTouch 4G Lists", "Fixed a crash when adding tasks with due times to Google Calendar", "Better syncing of the people list", "Minor UI polish and bugfixes" }); } if (from < V4_2_0) { newVersionString(changeLog, "4.2.0 (6/05/12)", new String[] { "Support for the Nook", "Fixed crash on large image attachments", "Minor bugfixes" }); } if (from >= V4_1_3 && from < V4_1_3_1) { newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] { "Fixed reminders for ICS" }); } if (from >= V4_1_2 && from < V4_1_3) { newVersionString(changeLog, "4.1.3 (5/17/12)", new String[] { "Added ability to see shared tasks sorted by friend! Enable or disable " + "in Settings > Astrid Labs", "Fixed desktop shortcuts", "Fixed adding tasks from the Power Pack widget", "Fixed selecting photos on the Kindle Fire", "Various other minor bug and crash fixes" }); } if (from >= V4_1_1 && from < V4_1_2) { newVersionString(changeLog, "4.1.2 (5/05/12)", new String[] { "Fixed some crashes and minor bugs" }); } if (from < V4_1_1) { newVersionString(changeLog, "4.1.1 (5/04/12)", new String[] { "Respond to or set reminders for missed calls. This feature requires a new permission to read " + "the phone state.", }); } if (from < V4_1_0) { newVersionString(changeLog, "4.1.0 (5/03/12)", new String[] { "Swipe between lists! Swipe left and right to move through your lists. Enable or adjust " + "in Settings > Astrid Labs", "Assign tasks to contacts without typing", "Links to tasks in comments", "Astrid.com sync improvements", "Other minor bugfixes", }); } if (from >= V4_0_6 && from < V4_0_6_2) { newVersionString(changeLog, "4.0.6.2 (4/03/12)", new String[] { "Minor fix to backup migration fix to handle deleted tasks as well as completed tasks." }); } if (from >= V4_0_6 && from < V4_0_6_1) { newVersionString(changeLog, "4.0.6.1 (4/03/12)", new String[] { "Fixed a bug where old tasks could become uncompleted. Sorry to those of you" + " who were affected by this! To recover, you can import your old tasks" + " from any backup file created before April 3 by clicking Menu -> Settings ->" + " Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start" + " with 'auto.120403'." }); } if (from < V4_0_6) { newVersionString(changeLog, "4.0.6 (4/02/12)", new String[] { "Fixes and performance improvements to Astrid.com and Google Tasks sync", "Google TV support! (Beta)", "Fixed a bug that could put duetimes on tasks when changing timezones", "Fixed a rare crash when starting a task timer" }); } if (from >= V4_0_0 && from < V4_0_5) { newVersionString(changeLog, "4.0.5 (3/22/12)", new String[] { "Better conflict resolution for Astrid.com sync", "Fixes and improvements to Gtasks sync", "Added option to report sync errors in sync preference screen" }); } if (from >= V4_0_0 && from < V4_0_4) { newVersionString(changeLog, "4.0.4 (3/7/12)", new String[] { "Fixed crashes related to error reporting", "Fixed a crash when creating a task from the widget", "Fixed a bug where a manual sync wouldn't always start" }); } if (from >= V4_0_0 && from < V4_0_3) { newVersionString(changeLog, "4.0.3 (3/6/12)", new String[] { "Fix some issues with Google Tasks sync. We're sorry to " + "everyone who's been having trouble with it!", "Updated translations for Portuguese, Chinese, German, Russian, and Dutch", "Centralize Android's menu key with in-app navigation", "Fixed crashes & improve crash logging", }); } if (from >= V4_0_0 && from < V4_0_2) { newVersionString(changeLog, "4.0.2 (2/29/12)", new String[] { "Removed GPS permission - no longer needed", "Fixes for some subtasks issues", "No longer need to run the Crittercism service in the background", "Fixed a crash that could occur when cloning tasks", "Fixed a bug that prevented certain comments from syncing correctly", "Fixed issues where voice add wouldn't work correctly", }); } if (from >= V4_0_0 && from < V4_0_1) { newVersionString(changeLog, "4.0.1 (2/23/12)", new String[] { "Fixed a database issue affecting Android 2.1 users", "Fixed a crash when using drag and drop in Google Tasks lists", "Other small bugfixes" }); } if (from < V4_0_0) { newVersionString(changeLog, "4.0.0 (2/23/12)", new String[] { "Welcome to Astrid 4.0! Here's what's new:", "<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access", "<b>New Look!</b><br>Customize how Astrid looks from the Settings menu", "<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people", "<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync", "<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet", "Many bug and usability fixes" }); } // --- old messages if (from >= V3_0_0 && from < V3_9_0) { newVersionString(changeLog, "3.9 (12/09/11)", new String[] { "Cleaner design (especially the task edit page)!", "Customize the edit page (\"Beast Mode\" in preferences)", "Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)", "Fixes for some ICS crashes (full support coming soon)", "Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.", "Other minor bug fixes", "Feedback welcomed!" }); } if(from >= V3_0_0 && from < V3_8_0) { newVersionString(changeLog, "3.8.0 (7/15/11)", new String[] { "Astrid.com: sync & share tasks / lists with others!", "GTasks Sync using Google's official task API! Gtasks users " + "will need to perform a manual sync to set everything up.", "Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)", "New style for \"Task Edit\" page!", "Purge completed or deleted tasks from settings menu!", }); gtasksPreferenceService.setToken(null); } if(from >= V3_0_0 && from < V3_7_0) { newVersionString(changeLog, "3.7.0 (2/7/11)", new String[] { "Improved UI for displaying task actions. Tap a task to " + "bring up actions, tap again to dismiss.", "Task notes can be viewed by tapping the note icon to " + "the right of the task.", "Added Astrid as 'Send-To' choice in Android Browser and " + "other apps.", "Add tags and importance in quick-add, e.g. " + "\"call mom #family @phone !4\"", "Fixed bug with custom filters & tasks being hidden.", }); upgrade3To3_7(); if(gtasksPreferenceService.isLoggedIn()) taskService.clearDetails(Criterion.all); Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true); } if(from >= V3_0_0 && from < V3_6_0) { newVersionString(changeLog, "3.6.0 (11/13/10)", new String[] { "Astrid Power Pack is now launched to the Android Market. " + "New Power Pack features include 4x2 and 4x4 widgets and voice " + "task reminders and creation. Go to the add-ons page to find out more!", "Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated", "Fix for task alarms not always firing if multiple set", "Fix for various force closes", }); upgrade3To3_6(context); } if(from >= V3_0_0 && from < V3_5_0) newVersionString(changeLog, "3.5.0 (10/25/10)", new String[] { "Google Tasks Sync (beta!)", "Bug fix with RMilk & new tasks not getting synced", "Fixed Force Closes and other bugs", }); if(from >= V3_0_0 && from < V3_4_0) { newVersionString(changeLog, "3.4.0 (10/08/10)", new String[] { "End User License Agreement", "Option to disable usage statistics", "Bug fixes with Producteev", }); } if(from >= V3_0_0 && from < V3_3_0) newVersionString(changeLog, "3.3.0 (9/17/10)", new String[] { "Fixed some RTM duplicated tasks issues", "UI updates based on your feedback", "Snooze now overrides other alarms", "Added preference option for selecting snooze style", "Hide until: now allows you to pick a specific time", }); if(from >= V3_0_0 && from < V3_2_0) newVersionString(changeLog, "3.2.0 (8/16/10)", new String[] { "Build your own custom filters from the Filter page", "Easy task sorting (in the task list menu)", "Create widgets from any of your filters", "Synchronize with Producteev! (producteev.com)", "Select tags by drop-down box", "Cosmetic improvements, calendar & sync bug fixes", }); if(from >= V3_0_0 && from < V3_1_0) newVersionString(changeLog, "3.1.0 (8/9/10)", new String[] { "Linkify phone numbers, e-mails, and web pages", "Swipe L => R to go from tasks to filters", "Moved task priority bar to left side", "Added ability to create fixed alerts for a task", "Restored tag hiding when tag begins with underscore (_)", "FROYO: disabled moving app to SD card, it would break alarms and widget", "Also gone: a couple force closes, bugs with repeating tasks", }); if(changeLog.length() == 0) return; changeLog.append("Enjoy!</body></html>"); String color = ThemeService.getDialogTextColorString(); String changeLogHtml = "<html><body style='color: " + color +"'>" + changeLog; DialogUtilities.htmlDialog(context, changeLogHtml, R.string.UpS_changelog_title); }
diff --git a/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/NodeType.java b/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/NodeType.java index 461f712..f1387e3 100644 --- a/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/NodeType.java +++ b/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/NodeType.java @@ -1,278 +1,280 @@ /******************************************************************************* * Copyright (c) 2005, 2009 Andrea Bittau, University College London, and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Andrea Bittau - initial API and implementation from the PsychoPath XPath 2.0 * Mukul Gandhi - bug 276134 - improvements to schema aware primitive type support * for attribute/element nodes * David Carver (STAR)- bug 277774 - XSDecimal returning wrong values. * Jesper Moller - bug 275610 - Avoid big time and memory overhead for externals * David Carver (STAR) - bug 281186 - implementation of fn:id and fn:idref * David Carver (STAR) - bug 289304 - fixed schema awareness on elements *******************************************************************************/ package org.eclipse.wst.xml.xpath2.processor.internal.types; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Time; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import org.apache.xerces.dom.PSVIAttrNSImpl; import org.apache.xerces.xs.ItemPSVI; import org.apache.xerces.xs.XSTypeDefinition; import org.eclipse.wst.xml.xpath2.processor.DynamicError; import org.eclipse.wst.xml.xpath2.processor.ResultSequence; import org.eclipse.wst.xml.xpath2.processor.ResultSequenceFactory; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.w3c.dom.TypeInfo; /** * A representation of a Node datatype */ public abstract class NodeType extends AnyType { protected static final String SCHEMA_TYPE_IDREF = "IDREF"; protected static final String SCHEMA_TYPE_ID = "ID"; private Node _node; /** * Initialises according to the supplied parameters * * @param node * The Node being represented * @param document_order * The document order */ public NodeType(Node node) { _node = node; } /** * Retrieves the actual node being represented * * @return Actual node being represented */ public Node node_value() { return _node; } // Accessors defined in XPath Data model // http://www.w3.org/TR/xpath-datamodel/ /** * Retrieves the actual node being represented * * @return Actual node being represented */ public abstract ResultSequence typed_value(); /** * Retrieves the name of the node * * @return QName representation of the name of the node */ public abstract QName node_name(); // may return null ["empty sequence"] // XXX element should override public ResultSequence nilled() { return ResultSequenceFactory.create_new(); } // a little factory for converting from DOM to our representation public static NodeType dom_to_xpath(Node node) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: return new ElementType((Element) node); case Node.COMMENT_NODE: return new CommentType((Comment) node); case Node.ATTRIBUTE_NODE: return new AttrType((Attr) node); case Node.TEXT_NODE: return new TextType((Text) node); case Node.DOCUMENT_NODE: return new DocType((Document) node); case Node.PROCESSING_INSTRUCTION_NODE: return new PIType((ProcessingInstruction) node); // XXX default: assert false; } // unreach... hopefully return null; } public static ResultSequence eliminate_dups(ResultSequence rs) { Hashtable added = new Hashtable(rs.size()); for (Iterator i = rs.iterator(); i.hasNext();) { NodeType node = (NodeType) i.next(); Node n = node.node_value(); if (added.containsKey(n)) i.remove(); else added.put(n, new Boolean(true)); } return rs; } public static ResultSequence sort_document_order(ResultSequence rs) { ArrayList res = new ArrayList(rs.size()); for (Iterator i = rs.iterator(); i.hasNext();) { NodeType node = (NodeType) i.next(); boolean added = false; for (int j = 0; j < res.size(); j++) { NodeType x = (NodeType) res.get(j); if (before(node, x)) { res.add(j, node); added = true; break; } } if (!added) res.add(node); } rs = ResultSequenceFactory.create_new(); for (Iterator i = res.iterator(); i.hasNext();) { NodeType node = (NodeType) i.next(); rs.add(node); } return rs; } public static boolean same(NodeType a, NodeType b) { return (a.node_value().isSameNode(b.node_value())); // While compare_node(a, b) == 0 is tempting, it is also expensive } public boolean before(NodeType two) { return before(this, two); } public static boolean before(NodeType a, NodeType b) { return compare_node(a, b) < 0; } public boolean after(NodeType two) { return after(this, two); } public static boolean after(NodeType a, NodeType b) { return compare_node(a, b) > 0; } private static int compare_node(NodeType a, NodeType b) { Node nodeA = a.node_value(); Node nodeB = b.node_value(); if (nodeA == nodeB || nodeA.isSameNode(nodeB)) return 0; Document docA = getDocument(nodeA); Document docB = getDocument(nodeB); if (docA != docB && ! docA.isSameNode(docB)) { return compareDocuments(docA, docB); } short relation = nodeA.compareDocumentPosition(nodeB); if ((relation & Node.DOCUMENT_POSITION_PRECEDING) != 0) return 1; if ((relation & Node.DOCUMENT_POSITION_FOLLOWING) != 0) return -1; throw new RuntimeException("Unexpected result from node comparison: " + relation); } private static int compareDocuments(Document docA, Document docB) { // Arbitrary but fulfills the spec (provided documenURI is always set) return docB.getDocumentURI().compareTo(docA.getDocumentURI()); } private static Document getDocument(Node nodeA) { return nodeA instanceof Document ? (Document)nodeA : nodeA.getOwnerDocument(); } protected Object getTypedValueForPrimitiveType(XSTypeDefinition typeDef) { Object schemaTypeValue = null; if (typeDef == null) { return new XSUntypedAtomic(string_value()); } String typeName = typeDef.getName(); if ("date".equals(typeName)) { schemaTypeValue = XSDate.parse_date(string_value()); } else if ("int".equals(typeName)) { schemaTypeValue = new XSInt(new BigInteger(string_value())); } else if ("long".equals(typeName)) { schemaTypeValue = new XSLong(new BigInteger(string_value())); } else if ("integer".equals(typeName)) { schemaTypeValue = new XSInteger(new BigInteger(string_value())); } else if ("double".equals(typeName)) { schemaTypeValue = new XSDouble(Double.parseDouble(string_value())); } else if ("float".equals(typeName)) { schemaTypeValue = new XSFloat(Float.parseFloat(string_value())); } else if ("decimal".equals(typeName)) { schemaTypeValue = new XSDecimal(new BigDecimal(string_value())); } else if ("dateTime".equals(typeName)) { schemaTypeValue = XSDateTime.parseDateTime(string_value()); } else if ("time".equals(typeName)) { schemaTypeValue = XSTime.parse_time(string_value()); } else if ("date".equals(typeName)) { schemaTypeValue = XSDate.parse_date(string_value()); } else if ("boolean".equals(typeName)) { schemaTypeValue = new XSBoolean(Boolean.valueOf(string_value())); + } else if ("NOTATION".equals(typeName)) { + schemaTypeValue = new XSString(string_value()); } return schemaTypeValue; } public abstract boolean isID(); public abstract boolean isIDREF(); /** * Utility method to check to see if a particular TypeInfo matches. * @param typeInfo * @param typeName * @return */ protected boolean isType(TypeInfo typeInfo, String typeName) { if (typeInfo != null) { String typeInfoName = typeInfo.getTypeName(); if (typeInfoName != null) { if (typeInfo.getTypeName().equalsIgnoreCase(typeName)) { return true; } } } return false; } }
true
true
protected Object getTypedValueForPrimitiveType(XSTypeDefinition typeDef) { Object schemaTypeValue = null; if (typeDef == null) { return new XSUntypedAtomic(string_value()); } String typeName = typeDef.getName(); if ("date".equals(typeName)) { schemaTypeValue = XSDate.parse_date(string_value()); } else if ("int".equals(typeName)) { schemaTypeValue = new XSInt(new BigInteger(string_value())); } else if ("long".equals(typeName)) { schemaTypeValue = new XSLong(new BigInteger(string_value())); } else if ("integer".equals(typeName)) { schemaTypeValue = new XSInteger(new BigInteger(string_value())); } else if ("double".equals(typeName)) { schemaTypeValue = new XSDouble(Double.parseDouble(string_value())); } else if ("float".equals(typeName)) { schemaTypeValue = new XSFloat(Float.parseFloat(string_value())); } else if ("decimal".equals(typeName)) { schemaTypeValue = new XSDecimal(new BigDecimal(string_value())); } else if ("dateTime".equals(typeName)) { schemaTypeValue = XSDateTime.parseDateTime(string_value()); } else if ("time".equals(typeName)) { schemaTypeValue = XSTime.parse_time(string_value()); } else if ("date".equals(typeName)) { schemaTypeValue = XSDate.parse_date(string_value()); } else if ("boolean".equals(typeName)) { schemaTypeValue = new XSBoolean(Boolean.valueOf(string_value())); } return schemaTypeValue; }
protected Object getTypedValueForPrimitiveType(XSTypeDefinition typeDef) { Object schemaTypeValue = null; if (typeDef == null) { return new XSUntypedAtomic(string_value()); } String typeName = typeDef.getName(); if ("date".equals(typeName)) { schemaTypeValue = XSDate.parse_date(string_value()); } else if ("int".equals(typeName)) { schemaTypeValue = new XSInt(new BigInteger(string_value())); } else if ("long".equals(typeName)) { schemaTypeValue = new XSLong(new BigInteger(string_value())); } else if ("integer".equals(typeName)) { schemaTypeValue = new XSInteger(new BigInteger(string_value())); } else if ("double".equals(typeName)) { schemaTypeValue = new XSDouble(Double.parseDouble(string_value())); } else if ("float".equals(typeName)) { schemaTypeValue = new XSFloat(Float.parseFloat(string_value())); } else if ("decimal".equals(typeName)) { schemaTypeValue = new XSDecimal(new BigDecimal(string_value())); } else if ("dateTime".equals(typeName)) { schemaTypeValue = XSDateTime.parseDateTime(string_value()); } else if ("time".equals(typeName)) { schemaTypeValue = XSTime.parse_time(string_value()); } else if ("date".equals(typeName)) { schemaTypeValue = XSDate.parse_date(string_value()); } else if ("boolean".equals(typeName)) { schemaTypeValue = new XSBoolean(Boolean.valueOf(string_value())); } else if ("NOTATION".equals(typeName)) { schemaTypeValue = new XSString(string_value()); } return schemaTypeValue; }
diff --git a/OsmAnd/src/net/osmand/OsmandSettings.java b/OsmAnd/src/net/osmand/OsmandSettings.java index 44f20229..62494196 100644 --- a/OsmAnd/src/net/osmand/OsmandSettings.java +++ b/OsmAnd/src/net/osmand/OsmandSettings.java @@ -1,808 +1,808 @@ package net.osmand; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.regex.Pattern; import net.osmand.activities.OsmandApplication; import net.osmand.activities.RouteProvider.RouteService; import net.osmand.activities.search.SearchHistoryHelper; import net.osmand.map.ITileSource; import net.osmand.map.TileSourceManager; import net.osmand.map.TileSourceManager.TileSourceTemplate; import net.osmand.osm.LatLon; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.hardware.Sensor; import android.hardware.SensorManager; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Environment; import android.util.Log; public class OsmandSettings { public enum ApplicationMode { /* * DEFAULT("Default"), CAR("Car"), BICYCLE("Bicycle"), PEDESTRIAN("Pedestrian"); */ DEFAULT(R.string.app_mode_default), CAR(R.string.app_mode_car), BICYCLE(R.string.app_mode_bicycle), PEDESTRIAN(R.string.app_mode_pedestrian); private final int key; ApplicationMode(int key) { this.key = key; } public static String toHumanString(ApplicationMode m, Context ctx){ return ctx.getResources().getString(m.key); } } public enum DayNightMode { AUTO(R.string.daynight_mode_auto), DAY(R.string.daynight_mode_day), NIGHT(R.string.daynight_mode_night), SENSOR(R.string.daynight_mode_sensor); private final int key; DayNightMode(int key) { this.key = key; } public String toHumanString(Context ctx){ return ctx.getResources().getString(key); } public boolean isSensor() { return this == SENSOR; } public boolean isAuto() { return this == AUTO; } public boolean isDay() { return this == DAY; } public boolean isNight() { return this == NIGHT; } public static DayNightMode[] possibleValues(Context context) { SensorManager mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); Sensor mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); if (mLight != null) { return DayNightMode.values(); } else { return new DayNightMode[] { AUTO, DAY, NIGHT }; } } } // These settings are stored in SharedPreferences public static final String SHARED_PREFERENCES_NAME = "net.osmand.settings"; //$NON-NLS-1$ public static final int CENTER_CONSTANT = 0; public static final int BOTTOM_CONSTANT = 1; public static final Editor getWriteableEditor(Context ctx){ SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit(); } public static final SharedPreferences getSharedPreferences(Context ctx){ return ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); } public static final SharedPreferences getPrefs(Context ctx){ return ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); } // this value string is synchronized with settings_pref.xml preference name public static final String USE_INTERNET_TO_DOWNLOAD_TILES = "use_internet_to_download_tiles"; //$NON-NLS-1$ public static final boolean USE_INTERNET_TO_DOWNLOAD_TILES_DEF = true; private static Boolean CACHE_USE_INTERNET_TO_DOWNLOAD_TILES = null; private static long lastTimeInternetConnectionChecked = 0; private static boolean internetConnectionAvailable = true; public static boolean isUsingInternetToDownloadTiles(SharedPreferences prefs) { if(CACHE_USE_INTERNET_TO_DOWNLOAD_TILES == null){ CACHE_USE_INTERNET_TO_DOWNLOAD_TILES = prefs.getBoolean(USE_INTERNET_TO_DOWNLOAD_TILES, USE_INTERNET_TO_DOWNLOAD_TILES_DEF); } return CACHE_USE_INTERNET_TO_DOWNLOAD_TILES; } public static void setUseInternetToDownloadTiles(boolean use, Editor edit) { edit.putBoolean(USE_INTERNET_TO_DOWNLOAD_TILES, use); CACHE_USE_INTERNET_TO_DOWNLOAD_TILES = use; } public static boolean isInternetConnectionAvailable(Context ctx){ long delta = System.currentTimeMillis() - lastTimeInternetConnectionChecked; if(delta < 0 || delta > 15000){ ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo active = mgr.getActiveNetworkInfo(); if(active == null){ internetConnectionAvailable = false; } else { NetworkInfo.State state = active.getState(); internetConnectionAvailable = state != NetworkInfo.State.DISCONNECTED && state != NetworkInfo.State.DISCONNECTING; } } return internetConnectionAvailable; } // this value string is synchronized with settings_pref.xml preference name public static final String USE_TRACKBALL_FOR_MOVEMENTS = "use_trackball_for_movements"; //$NON-NLS-1$ public static final boolean USE_TRACKBALL_FOR_MOVEMENTS_DEF = true; public static boolean isUsingTrackBall(SharedPreferences prefs) { return prefs.getBoolean(USE_TRACKBALL_FOR_MOVEMENTS, USE_TRACKBALL_FOR_MOVEMENTS_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String USE_HIGH_RES_MAPS = "use_high_res_maps"; //$NON-NLS-1$ public static final boolean USE_HIGH_RES_MAPS_DEF = false; public static boolean isUsingHighResMaps(SharedPreferences prefs) { return prefs.getBoolean(USE_HIGH_RES_MAPS, USE_HIGH_RES_MAPS_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String SHOW_POI_OVER_MAP = "show_poi_over_map"; //$NON-NLS-1$ public static final Boolean SHOW_POI_OVER_MAP_DEF = false; public static boolean isShowingPoiOverMap(SharedPreferences prefs) { return prefs.getBoolean(SHOW_POI_OVER_MAP, SHOW_POI_OVER_MAP_DEF); } public static boolean setShowPoiOverMap(Context ctx, boolean val) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SHOW_POI_OVER_MAP, val).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String SHOW_TRANSPORT_OVER_MAP = "show_transport_over_map"; //$NON-NLS-1$ public static final boolean SHOW_TRANSPORT_OVER_MAP_DEF = false; public static boolean isShowingTransportOverMap(SharedPreferences prefs) { return prefs.getBoolean(SHOW_TRANSPORT_OVER_MAP, SHOW_TRANSPORT_OVER_MAP_DEF); } public static boolean setShowTransortOverMap(Context ctx, boolean val) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SHOW_TRANSPORT_OVER_MAP, val).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String USER_NAME = "user_name"; //$NON-NLS-1$ public static String getUserName(SharedPreferences prefs) { return prefs.getString(USER_NAME, "NoName"); //$NON-NLS-1$ } public static boolean setUserName(Context ctx, String name) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(USER_NAME, name).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String USER_OSM_BUG_NAME = "user_osm_bug_name"; //$NON-NLS-1$ public static String getUserNameForOsmBug(SharedPreferences prefs) { return prefs.getString(USER_OSM_BUG_NAME, "NoName/Osmand"); //$NON-NLS-1$ } public static boolean setUserNameForOsmBug(Context ctx, String name) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(USER_OSM_BUG_NAME, name).commit(); } public static final String USER_PASSWORD = "user_password"; //$NON-NLS-1$ public static String getUserPassword(SharedPreferences prefs){ return prefs.getString(USER_PASSWORD, ""); //$NON-NLS-1$ } public static boolean setUserPassword(Context ctx, String name){ SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(USER_PASSWORD, name).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String APPLICATION_MODE = "application_mode"; //$NON-NLS-1$ public static ApplicationMode getApplicationMode(SharedPreferences prefs) { String s = prefs.getString(APPLICATION_MODE, ApplicationMode.DEFAULT.name()); try { return ApplicationMode.valueOf(s); } catch (IllegalArgumentException e) { return ApplicationMode.DEFAULT; } } public static boolean setApplicationMode(Context ctx, ApplicationMode p) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(APPLICATION_MODE, p.name()).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String DAYNIGHT_MODE = "daynight_mode"; //$NON-NLS-1$ public static DayNightMode getDayNightMode(SharedPreferences prefs) { String s = prefs.getString(DAYNIGHT_MODE, DayNightMode.AUTO.name()); try { return DayNightMode.valueOf(s); } catch (IllegalArgumentException e) { return DayNightMode.AUTO; } } public static boolean setDayNightMode(Context ctx, DayNightMode p) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(APPLICATION_MODE, p.name()).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String ROUTER_SERVICE = "router_service"; //$NON-NLS-1$ public static RouteService getRouterService(SharedPreferences prefs) { int ord = prefs.getInt(ROUTER_SERVICE, RouteService.OSMAND.ordinal()); if(ord < RouteService.values().length){ return RouteService.values()[ord]; } else { return RouteService.OSMAND; } } public static boolean setRouterService(Context ctx, RouteService p) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putInt(ROUTER_SERVICE, p.ordinal()).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String SAVE_CURRENT_TRACK = "save_current_track"; //$NON-NLS-1$ public static final String RELOAD_INDEXES = "reload_indexes"; //$NON-NLS-1$ public static final String DOWNLOAD_INDEXES = "download_indexes"; //$NON-NLS-1$ // this value string is synchronized with settings_pref.xml preference name public static final String SAVE_TRACK_TO_GPX = "save_track_to_gpx"; //$NON-NLS-1$ public static final boolean SAVE_TRACK_TO_GPX_DEF = false; public static boolean isSavingTrackToGpx(Context ctx) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.getBoolean(SAVE_TRACK_TO_GPX, SAVE_TRACK_TO_GPX_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String FAST_ROUTE_MODE = "fast_route_mode"; //$NON-NLS-1$ public static final boolean FAST_ROUTE_MODE_DEF = true; public static boolean isFastRouteMode(Context ctx) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.getBoolean(FAST_ROUTE_MODE, FAST_ROUTE_MODE_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String SAVE_TRACK_INTERVAL = "save_track_interval"; //$NON-NLS-1$ public static int getSavingTrackInterval(SharedPreferences prefs) { return prefs.getInt(SAVE_TRACK_INTERVAL, 5); } // this value string is synchronized with settings_pref.xml preference name public static final String SHOW_OSM_BUGS = "show_osm_bugs"; //$NON-NLS-1$ public static final boolean SHOW_OSM_BUGS_DEF = false; public static boolean isShowingOsmBugs(SharedPreferences prefs) { return prefs.getBoolean(SHOW_OSM_BUGS, SHOW_OSM_BUGS_DEF); } public static boolean setShowingOsmBugs(Context ctx, boolean val) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SHOW_OSM_BUGS, val).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String DEBUG_RENDERING_INFO = "debug_rendering"; //$NON-NLS-1$ public static final boolean DEBUG_RENDERING_INFO_DEF = false; public static boolean isDebugRendering(Context ctx) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.getBoolean(DEBUG_RENDERING_INFO, DEBUG_RENDERING_INFO_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String SHOW_YANDEX_TRAFFIC = "show_yandex_traffic"; //$NON-NLS-1$ public static final boolean SHOW_YANDEX_TRAFFIC_DEF = false; public static boolean isShowingYandexTraffic(SharedPreferences prefs) { return prefs.getBoolean(SHOW_YANDEX_TRAFFIC, SHOW_YANDEX_TRAFFIC_DEF); } public static boolean setShowingYandexTraffic(Context ctx, boolean val) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SHOW_YANDEX_TRAFFIC, val).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String SHOW_FAVORITES = "show_favorites"; //$NON-NLS-1$ public static final boolean SHOW_FAVORITES_DEF = false; public static boolean isShowingFavorites(SharedPreferences prefs) { return prefs.getBoolean(SHOW_FAVORITES, SHOW_FAVORITES_DEF); } public static boolean setShowingFavorites(Context ctx, boolean val) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SHOW_FAVORITES, val).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String MAP_SCREEN_ORIENTATION = "map_screen_orientation"; //$NON-NLS-1$ public static int getMapOrientation(SharedPreferences prefs){ return prefs.getInt(MAP_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } // this value string is synchronized with settings_pref.xml preference name public static final String SHOW_VIEW_ANGLE = "show_view_angle"; //$NON-NLS-1$ public static final boolean SHOW_VIEW_ANGLE_DEF = false; public static boolean isShowingViewAngle(SharedPreferences prefs) { return prefs.getBoolean(SHOW_VIEW_ANGLE, SHOW_VIEW_ANGLE_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String AUTO_ZOOM_MAP = "auto_zoom_map"; //$NON-NLS-1$ public static final boolean AUTO_ZOOM_MAP_DEF = false; public static boolean isAutoZoomEnabled(SharedPreferences prefs) { return prefs.getBoolean(AUTO_ZOOM_MAP, AUTO_ZOOM_MAP_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String ROTATE_MAP = "rotate_map"; //$NON-NLS-1$ public static final int ROTATE_MAP_TO_BEARING_DEF = 0; public static final int ROTATE_MAP_NONE = 0; public static final int ROTATE_MAP_BEARING = 1; public static final int ROTATE_MAP_COMPASS = 2; // return 0 - no rotate, 1 - to bearing, 2 - to compass public static int getRotateMap(SharedPreferences prefs) { return prefs.getInt(ROTATE_MAP, ROTATE_MAP_TO_BEARING_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String POSITION_ON_MAP = "position_on_map"; //$NON-NLS-1$ public static int getPositionOnMap(SharedPreferences prefs) { return prefs.getInt(POSITION_ON_MAP, CENTER_CONSTANT); } // this value string is synchronized with settings_pref.xml preference name public static final String MAX_LEVEL_TO_DOWNLOAD_TILE = "max_level_download_tile"; //$NON-NLS-1$ public static int getMaximumLevelToDownloadTile(SharedPreferences prefs) { return prefs.getInt(MAX_LEVEL_TO_DOWNLOAD_TILE, 18); } // this value string is synchronized with settings_pref.xml preference name public static final String MAP_VIEW_3D = "map_view_3d"; //$NON-NLS-1$ public static final boolean MAP_VIEW_3D_DEF = false; public static boolean isMapView3D(SharedPreferences prefs) { return prefs.getBoolean(MAP_VIEW_3D, MAP_VIEW_3D_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String USE_ENGLISH_NAMES = "use_english_names"; //$NON-NLS-1$ public static final boolean USE_ENGLISH_NAMES_DEF = false; public static boolean usingEnglishNames(SharedPreferences prefs) { return prefs.getBoolean(USE_ENGLISH_NAMES, USE_ENGLISH_NAMES_DEF); } public static boolean setUseEnglishNames(Context ctx, boolean useEnglishNames) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(USE_ENGLISH_NAMES, useEnglishNames).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String USE_STEP_BY_STEP_RENDERING = "use_step_by_step_rendering"; //$NON-NLS-1$ public static final boolean USE_STEP_BY_STEP_RENDERING_DEF = true; public static boolean isUsingStepByStepRendering(SharedPreferences prefs) { return prefs.getBoolean(USE_STEP_BY_STEP_RENDERING, USE_STEP_BY_STEP_RENDERING_DEF); } public static boolean setUsingStepByStepRendering(Context ctx, boolean rendering) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(USE_STEP_BY_STEP_RENDERING, rendering).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String MAP_VECTOR_DATA = "map_vector_data"; //$NON-NLS-1$ public static final String MAP_TILE_SOURCES = "map_tile_sources"; //$NON-NLS-1$ public static boolean isUsingMapVectorData(SharedPreferences prefs){ return prefs.getBoolean(MAP_VECTOR_DATA, false); } public static ITileSource getMapTileSource(SharedPreferences prefs) { String tileName = prefs.getString(MAP_TILE_SOURCES, null); if (tileName != null) { List<TileSourceTemplate> list = TileSourceManager.getKnownSourceTemplates(); for (TileSourceTemplate l : list) { if (l.getName().equals(tileName)) { return l; } } File tPath = new File(Environment.getExternalStorageDirectory(), ResourceManager.TILES_PATH); File dir = new File(tPath, tileName); if(dir.exists()){ if(tileName.endsWith(SQLiteTileSource.EXT)){ return new SQLiteTileSource(dir); } else if (dir.isDirectory()) { String url = null; File readUrl = new File(dir, "url"); //$NON-NLS-1$ try { if (readUrl.exists()) { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(readUrl), "UTF-8")); //$NON-NLS-1$ url = reader.readLine(); url = url.replaceAll(Pattern.quote("{$z}"), "{0}"); //$NON-NLS-1$ //$NON-NLS-2$ url = url.replaceAll(Pattern.quote("{$x}"), "{1}"); //$NON-NLS-1$//$NON-NLS-2$ url = url.replaceAll(Pattern.quote("{$y}"), "{2}"); //$NON-NLS-1$ //$NON-NLS-2$ reader.close(); } } catch (IOException e) { Log.d(LogUtil.TAG, "Error reading url " + dir.getName(), e); //$NON-NLS-1$ } - return new TileSourceManager.TileSourceTemplate(dir.getName(), url); + return new TileSourceManager.TileSourceTemplate(dir, dir.getName(), url); } } } return TileSourceManager.getMapnikSource(); } public static String getMapTileSourceName(SharedPreferences prefs) { String tileName = prefs.getString(MAP_TILE_SOURCES, null); if (tileName != null) { return tileName; } return TileSourceManager.getMapnikSource().getName(); } // This value is a key for saving last known location shown on the map public static final String LAST_KNOWN_MAP_LAT = "last_known_map_lat"; //$NON-NLS-1$ public static final String LAST_KNOWN_MAP_LON = "last_known_map_lon"; //$NON-NLS-1$ public static final String IS_MAP_SYNC_TO_GPS_LOCATION = "is_map_sync_to_gps_location"; //$NON-NLS-1$ public static final String LAST_KNOWN_MAP_ZOOM = "last_known_map_zoom"; //$NON-NLS-1$ public static final String MAP_LAT_TO_SHOW = "map_lat_to_show"; //$NON-NLS-1$ public static final String MAP_LON_TO_SHOW = "map_lon_to_show"; //$NON-NLS-1$ public static final String MAP_ZOOM_TO_SHOW = "map_zoom_to_show"; //$NON-NLS-1$ public static LatLon getLastKnownMapLocation(SharedPreferences prefs) { float lat = prefs.getFloat(LAST_KNOWN_MAP_LAT, 0); float lon = prefs.getFloat(LAST_KNOWN_MAP_LON, 0); return new LatLon(lat, lon); } public static void setMapLocationToShow(Context ctx, double latitude, double longitude) { setMapLocationToShow(ctx, latitude, longitude, getLastKnownMapZoom(getSharedPreferences(ctx)), null); } public static void setMapLocationToShow(Context ctx, double latitude, double longitude, int zoom) { setMapLocationToShow(ctx, latitude, longitude, null); } public static LatLon getAndClearMapLocationToShow(SharedPreferences prefs){ if(!prefs.contains(MAP_LAT_TO_SHOW)){ return null; } float lat = prefs.getFloat(MAP_LAT_TO_SHOW, 0); float lon = prefs.getFloat(MAP_LON_TO_SHOW, 0); prefs.edit().remove(MAP_LAT_TO_SHOW).commit(); return new LatLon(lat, lon); } public static int getMapZoomToShow(SharedPreferences prefs) { return prefs.getInt(MAP_ZOOM_TO_SHOW, 5); } public static void setMapLocationToShow(Context ctx, double latitude, double longitude, int zoom, String historyDescription) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit(); edit.putFloat(MAP_LAT_TO_SHOW, (float) latitude); edit.putFloat(MAP_LON_TO_SHOW, (float) longitude); edit.putInt(MAP_ZOOM_TO_SHOW, zoom); edit.putBoolean(IS_MAP_SYNC_TO_GPS_LOCATION, false); edit.commit(); if(historyDescription != null){ SearchHistoryHelper.getInstance().addNewItemToHistory(latitude, longitude, historyDescription, ctx); } } public static void setMapLocationToShow(Context ctx, double latitude, double longitude, String historyDescription) { setMapLocationToShow(ctx, latitude, longitude, getLastKnownMapZoom(getSharedPreferences(ctx)), historyDescription); } // Do not use that method if you want to show point on map. Use setMapLocationToShow public static void setLastKnownMapLocation(Context ctx, double latitude, double longitude) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit(); edit.putFloat(LAST_KNOWN_MAP_LAT, (float) latitude); edit.putFloat(LAST_KNOWN_MAP_LON, (float) longitude); edit.commit(); } public static boolean setSyncMapToGpsLocation(Context ctx, boolean value) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(IS_MAP_SYNC_TO_GPS_LOCATION, value).commit(); } public static boolean isMapSyncToGpsLocation(SharedPreferences prefs) { return prefs.getBoolean(IS_MAP_SYNC_TO_GPS_LOCATION, true); } public static int getLastKnownMapZoom(SharedPreferences prefs) { return prefs.getInt(LAST_KNOWN_MAP_ZOOM, 5); } public static void setLastKnownMapZoom(Context ctx, int zoom) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit(); edit.putInt(LAST_KNOWN_MAP_ZOOM, zoom); edit.commit(); } public final static String POINT_NAVIGATE_LAT = "point_navigate_lat"; //$NON-NLS-1$ public final static String POINT_NAVIGATE_LON = "point_navigate_lon"; //$NON-NLS-1$ public static LatLon getPointToNavigate(SharedPreferences prefs) { float lat = prefs.getFloat(POINT_NAVIGATE_LAT, 0); float lon = prefs.getFloat(POINT_NAVIGATE_LON, 0); if (lat == 0 && lon == 0) { return null; } return new LatLon(lat, lon); } public static boolean clearPointToNavigate(SharedPreferences prefs) { return prefs.edit().remove(POINT_NAVIGATE_LAT).remove(POINT_NAVIGATE_LON).commit(); } public static boolean setPointToNavigate(Context ctx, double latitude, double longitude) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putFloat(POINT_NAVIGATE_LAT, (float) latitude).putFloat(POINT_NAVIGATE_LON, (float) longitude).commit(); } public static final String LAST_SEARCHED_REGION = "last_searched_region"; //$NON-NLS-1$ public static final String LAST_SEARCHED_CITY = "last_searched_city"; //$NON-NLS-1$ public static final String lAST_SEARCHED_POSTCODE= "last_searched_postcode"; //$NON-NLS-1$ public static final String LAST_SEARCHED_STREET = "last_searched_street"; //$NON-NLS-1$ public static final String LAST_SEARCHED_BUILDING = "last_searched_building"; //$NON-NLS-1$ public static final String LAST_SEARCHED_INTERSECTED_STREET = "last_searched_intersected_street"; //$NON-NLS-1$ public static String getLastSearchedRegion(SharedPreferences prefs) { return prefs.getString(LAST_SEARCHED_REGION, ""); //$NON-NLS-1$ } public static boolean setLastSearchedRegion(Context ctx, String region) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit().putString(LAST_SEARCHED_REGION, region).putLong(LAST_SEARCHED_CITY, -1).putString(LAST_SEARCHED_STREET, "").putString(LAST_SEARCHED_BUILDING, ""); //$NON-NLS-1$ //$NON-NLS-2$ if (prefs.contains(LAST_SEARCHED_INTERSECTED_STREET)) { edit.putString(LAST_SEARCHED_INTERSECTED_STREET, ""); //$NON-NLS-1$ } return edit.commit(); } public static String getLastSearchedPostcode(SharedPreferences prefs){ return prefs.getString(lAST_SEARCHED_POSTCODE, null); } public static boolean setLastSearchedPostcode(Context ctx, String postcode){ SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit().putLong(LAST_SEARCHED_CITY, -1).putString(LAST_SEARCHED_STREET, "").putString( //$NON-NLS-1$ LAST_SEARCHED_BUILDING, "").putString(lAST_SEARCHED_POSTCODE, postcode); //$NON-NLS-1$ if(prefs.contains(LAST_SEARCHED_INTERSECTED_STREET)){ edit.putString(LAST_SEARCHED_INTERSECTED_STREET, ""); //$NON-NLS-1$ } return edit.commit(); } public static Long getLastSearchedCity(SharedPreferences prefs) { return prefs.getLong(LAST_SEARCHED_CITY, -1); } public static boolean setLastSearchedCity(Context ctx, Long cityId) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit().putLong(LAST_SEARCHED_CITY, cityId).putString(LAST_SEARCHED_STREET, "").putString( //$NON-NLS-1$ LAST_SEARCHED_BUILDING, ""); //$NON-NLS-1$ edit.remove(lAST_SEARCHED_POSTCODE); if(prefs.contains(LAST_SEARCHED_INTERSECTED_STREET)){ edit.putString(LAST_SEARCHED_INTERSECTED_STREET, ""); //$NON-NLS-1$ } return edit.commit(); } public static String getLastSearchedStreet(SharedPreferences prefs) { return prefs.getString(LAST_SEARCHED_STREET, ""); //$NON-NLS-1$ } public static boolean setLastSearchedStreet(Context ctx, String street) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); Editor edit = prefs.edit().putString(LAST_SEARCHED_STREET, street).putString(LAST_SEARCHED_BUILDING, ""); //$NON-NLS-1$ if (prefs.contains(LAST_SEARCHED_INTERSECTED_STREET)) { edit.putString(LAST_SEARCHED_INTERSECTED_STREET, ""); //$NON-NLS-1$ } return edit.commit(); } public static String getLastSearchedBuilding(SharedPreferences prefs) { return prefs.getString(LAST_SEARCHED_BUILDING, ""); //$NON-NLS-1$ } public static boolean setLastSearchedBuilding(Context ctx, String building) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(LAST_SEARCHED_BUILDING, building).remove(LAST_SEARCHED_INTERSECTED_STREET).commit(); } public static String getLastSearchedIntersectedStreet(SharedPreferences prefs) { if (!prefs.contains(LAST_SEARCHED_INTERSECTED_STREET)) { return null; } return prefs.getString(LAST_SEARCHED_INTERSECTED_STREET, ""); //$NON-NLS-1$ } public static boolean setLastSearchedIntersectedStreet(Context ctx, String street) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(LAST_SEARCHED_INTERSECTED_STREET, street).commit(); } public static boolean removeLastSearchedIntersectedStreet(Context ctx) { SharedPreferences prefs = getPrefs(ctx); return prefs.edit().remove(LAST_SEARCHED_INTERSECTED_STREET).commit(); } public static final String SELECTED_POI_FILTER_FOR_MAP = "selected_poi_filter_for_map"; //$NON-NLS-1$ public static boolean setPoiFilterForMap(Context ctx, String filterId) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putString(SELECTED_POI_FILTER_FOR_MAP, filterId).commit(); } public static PoiFilter getPoiFilterForMap(Context ctx, OsmandApplication application) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); String filterId = prefs.getString(SELECTED_POI_FILTER_FOR_MAP, null); PoiFilter filter = application.getPoiFilters().getFilterById(filterId); if (filter != null) { return filter; } return new PoiFilter(null, application); } // this value string is synchronized with settings_pref.xml preference name public static final String VOICE_PROVIDER = "voice_provider"; //$NON-NLS-1$ public static String getVoiceProvider(SharedPreferences prefs){ return prefs.getString(VOICE_PROVIDER, null); } // this value string is synchronized with settings_pref.xml preference name public static final String RENDERER = "renderer"; //$NON-NLS-1$ public static String getVectorRenderer(SharedPreferences prefs){ return prefs.getString(RENDERER, null); } public static final String VOICE_MUTE = "voice_mute"; //$NON-NLS-1$ public static final boolean VOICE_MUTE_DEF = false; public static boolean isVoiceMute(SharedPreferences prefs){ return prefs.getBoolean(VOICE_MUTE, VOICE_MUTE_DEF); } public static boolean setVoiceMute(Context ctx, boolean mute){ SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(VOICE_MUTE, mute).commit(); } // for background service public static final String MAP_ACTIVITY_ENABLED = "map_activity_enabled"; //$NON-NLS-1$ public static final boolean MAP_ACTIVITY_ENABLED_DEF = false; public static boolean getMapActivityEnabled(SharedPreferences prefs) { return prefs.getBoolean(MAP_ACTIVITY_ENABLED, MAP_ACTIVITY_ENABLED_DEF); } public static boolean setMapActivityEnabled(Context ctx, boolean en) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(MAP_ACTIVITY_ENABLED, en).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String SERVICE_OFF_ENABLED = "service_off_enabled"; //$NON-NLS-1$ public static final boolean SERVICE_OFF_ENABLED_DEF = false; public static boolean getServiceOffEnabled(SharedPreferences prefs) { return prefs.getBoolean(SERVICE_OFF_ENABLED, SERVICE_OFF_ENABLED_DEF); } public static boolean setServiceOffEnabled(Context ctx, boolean en) { SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SERVICE_OFF_ENABLED, en).commit(); } // this value string is synchronized with settings_pref.xml preference name public static final String SERVICE_OFF_PROVIDER = "service_off_provider"; //$NON-NLS-1$ public static String getServiceOffProvider(SharedPreferences prefs) { return prefs.getString(SERVICE_OFF_PROVIDER, LocationManager.GPS_PROVIDER); } // this value string is synchronized with settings_pref.xml preference name public static final String SERVICE_OFF_INTERVAL = "service_off_interval"; //$NON-NLS-1$ public static final int SERVICE_OFF_INTERVAL_DEF = 5 * 60 * 1000; public static int getServiceOffInterval(SharedPreferences prefs) { return prefs.getInt(SERVICE_OFF_INTERVAL, SERVICE_OFF_INTERVAL_DEF); } // this value string is synchronized with settings_pref.xml preference name public static final String SERVICE_OFF_WAIT_INTERVAL = "service_off_wait_interval"; //$NON-NLS-1$ public static final int SERVICE_OFF_WAIT_INTERVAL_DEF = 90 * 1000; public static int getServiceOffWaitInterval(SharedPreferences prefs) { return prefs.getInt(SERVICE_OFF_WAIT_INTERVAL, SERVICE_OFF_WAIT_INTERVAL_DEF); } public static final String FOLLOW_TO_THE_ROUTE = "follow_to_route"; //$NON-NLS-1$ public static boolean isFollowingByRoute(SharedPreferences prefs){ return prefs.getBoolean(FOLLOW_TO_THE_ROUTE, false); } public static boolean setFollowingByRoute(Context ctx, boolean val){ SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(FOLLOW_TO_THE_ROUTE, val).commit(); } public static final String SHOW_ARRIVAL_TIME_OTHERWISE_EXPECTED_TIME = "show_arrival_time"; //$NON-NLS-1$ public static boolean isShowingArrivalTime(SharedPreferences prefs){ return prefs.getBoolean(SHOW_ARRIVAL_TIME_OTHERWISE_EXPECTED_TIME, true); } public static boolean setShowingArrivalTime(Context ctx, boolean val){ SharedPreferences prefs = ctx.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE); return prefs.edit().putBoolean(SHOW_ARRIVAL_TIME_OTHERWISE_EXPECTED_TIME, val).commit(); } }
true
true
public static ITileSource getMapTileSource(SharedPreferences prefs) { String tileName = prefs.getString(MAP_TILE_SOURCES, null); if (tileName != null) { List<TileSourceTemplate> list = TileSourceManager.getKnownSourceTemplates(); for (TileSourceTemplate l : list) { if (l.getName().equals(tileName)) { return l; } } File tPath = new File(Environment.getExternalStorageDirectory(), ResourceManager.TILES_PATH); File dir = new File(tPath, tileName); if(dir.exists()){ if(tileName.endsWith(SQLiteTileSource.EXT)){ return new SQLiteTileSource(dir); } else if (dir.isDirectory()) { String url = null; File readUrl = new File(dir, "url"); //$NON-NLS-1$ try { if (readUrl.exists()) { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(readUrl), "UTF-8")); //$NON-NLS-1$ url = reader.readLine(); url = url.replaceAll(Pattern.quote("{$z}"), "{0}"); //$NON-NLS-1$ //$NON-NLS-2$ url = url.replaceAll(Pattern.quote("{$x}"), "{1}"); //$NON-NLS-1$//$NON-NLS-2$ url = url.replaceAll(Pattern.quote("{$y}"), "{2}"); //$NON-NLS-1$ //$NON-NLS-2$ reader.close(); } } catch (IOException e) { Log.d(LogUtil.TAG, "Error reading url " + dir.getName(), e); //$NON-NLS-1$ } return new TileSourceManager.TileSourceTemplate(dir.getName(), url); } } } return TileSourceManager.getMapnikSource(); }
public static ITileSource getMapTileSource(SharedPreferences prefs) { String tileName = prefs.getString(MAP_TILE_SOURCES, null); if (tileName != null) { List<TileSourceTemplate> list = TileSourceManager.getKnownSourceTemplates(); for (TileSourceTemplate l : list) { if (l.getName().equals(tileName)) { return l; } } File tPath = new File(Environment.getExternalStorageDirectory(), ResourceManager.TILES_PATH); File dir = new File(tPath, tileName); if(dir.exists()){ if(tileName.endsWith(SQLiteTileSource.EXT)){ return new SQLiteTileSource(dir); } else if (dir.isDirectory()) { String url = null; File readUrl = new File(dir, "url"); //$NON-NLS-1$ try { if (readUrl.exists()) { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(readUrl), "UTF-8")); //$NON-NLS-1$ url = reader.readLine(); url = url.replaceAll(Pattern.quote("{$z}"), "{0}"); //$NON-NLS-1$ //$NON-NLS-2$ url = url.replaceAll(Pattern.quote("{$x}"), "{1}"); //$NON-NLS-1$//$NON-NLS-2$ url = url.replaceAll(Pattern.quote("{$y}"), "{2}"); //$NON-NLS-1$ //$NON-NLS-2$ reader.close(); } } catch (IOException e) { Log.d(LogUtil.TAG, "Error reading url " + dir.getName(), e); //$NON-NLS-1$ } return new TileSourceManager.TileSourceTemplate(dir, dir.getName(), url); } } } return TileSourceManager.getMapnikSource(); }
diff --git a/src/org/red5/server/service/ServiceInvoker.java b/src/org/red5/server/service/ServiceInvoker.java index d435c3e3..39b80b8f 100644 --- a/src/org/red5/server/service/ServiceInvoker.java +++ b/src/org/red5/server/service/ServiceInvoker.java @@ -1,208 +1,210 @@ package org.red5.server.service; /* * RED5 Open Source Flash Server - http://www.osflash.org/red5 * * Copyright � 2006 by respective authors. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @author The Red5 Project ([email protected]) * @author Luke Hubbard, Codegent Ltd ([email protected]) */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; public class ServiceInvoker { private static final Log log = LogFactory.getLog(ServiceInvoker.class); public static final String SERVICE_NAME = "serviceInvoker"; protected ApplicationContext serviceContext = null; //protected ScriptBeanFactory scriptBeanFactory = null; /* public void setScriptBeanFactory(ScriptBeanFactory scriptBeanFactory) { this.scriptBeanFactory = scriptBeanFactory; } */ public void setServiceContext(ApplicationContext serviceContext){ this.serviceContext = serviceContext; } public void invoke(Call call) { invoke(call, serviceContext); } /* * Returns (method, params) for the given service or (null, null) if not method was found. */ private Object[] findMethodWithExactParameters(Object service, String methodName, Object[] args) { int numParams = (args==null) ? 0 : args.length; List methods = ConversionUtils.findMethodsByNameAndNumParams(service, methodName, numParams); log.debug("Found " + methods.size() + " methods"); if (methods.isEmpty()) return new Object[]{null, null}; else if (methods.size() > 1) { log.debug("Multiple methods found with same name and parameter count."); log.debug("Parameter conversion will be attempted in order."); } Method method = null; Object[] params = null; for(int i=0; i<methods.size(); i++){ try { method = (Method) methods.get(i); params = ConversionUtils.convertParams(args, method.getParameterTypes()); return new Object[]{method, params}; } catch (Exception ex){ log.debug("Parameter conversion failed", ex); } } return new Object[]{null, null}; } /* * Returns (method, params) for the given service or (null, null) if not method was found. */ private Object[] findMethodWithListParameters(Object service, String methodName, Object[] args) { List methods = ConversionUtils.findMethodsByNameAndNumParams(service, methodName, 1); log.debug("Found " + methods.size() + " methods"); if (methods.isEmpty()) return new Object[]{null, null}; else if (methods.size() > 1) { log.debug("Multiple methods found with same name and parameter count."); log.debug("Parameter conversion will be attempted in order."); } ArrayList argsList = new ArrayList(); if(args!=null){ for(int i=0; i<args.length; i++){ argsList.add(args[0]); } } args = new Object[]{argsList}; Method method = null; Object[] params = null; for(int i=0; i<methods.size(); i++){ try { method = (Method) methods.get(i); params = ConversionUtils.convertParams(args, method.getParameterTypes()); return new Object[]{method, params}; } catch (Exception ex){ log.debug("Parameter conversion failed", ex); } } return new Object[]{null, null}; } public void invoke(Call call, ApplicationContext serviceContext) { String serviceName = call.getServiceName(); String methodName = call.getServiceMethodName(); log.debug("Service name " + serviceName); log.debug("Service method " + methodName); Object service = null; if(serviceContext.containsBean(serviceName)){ service = serviceContext.getBean(serviceName); } /* if(service == null && serviceContext.containsBean("scriptBeanFactory")){ scriptBeanFactory = (ScriptBeanFactory) serviceContext.getBean("scriptBeanFactory"); } if(service == null && scriptBeanFactory !=null) { // lets see if its a script. service = scriptBeanFactory.getBean(serviceName); } */ if(service == null) { call.setException(new ServiceNotFoundException(serviceName)); call.setStatus(Call.STATUS_SERVICE_NOT_FOUND); log.warn("Service not found: "+serviceName); return; // EXIT } else { log.debug("Service found: "+serviceName); } Object[] args = call.getArguments(); - for (int i=0; i<args.length; i++) { - log.debug(" "+i+" => "+args[i]); + if (args != null) { + for (int i=0; i<args.length; i++) { + log.debug(" "+i+" => "+args[i]); + } } Object[] methodResult = null; methodResult = findMethodWithExactParameters(service, methodName, args); if (methodResult.length == 0 || methodResult[0] == null) methodResult = findMethodWithListParameters(service, methodName, args); if (methodResult.length == 0 || methodResult[0] == null) { call.setStatus(Call.STATUS_METHOD_NOT_FOUND); call.setException(new MethodNotFoundException(methodName)); return; } Object result = null; Method method = (Method) methodResult[0]; Object[] params = (Object[]) methodResult[1]; try { log.debug("Invoking method: "+method.toString()); if (method.getReturnType() == Void.class) { method.invoke(service, params); call.setStatus(Call.STATUS_SUCCESS_VOID); } else { result = method.invoke(service, params); call.setResult(result); call.setStatus( result==null ? Call.STATUS_SUCCESS_NULL : Call.STATUS_SUCCESS_RESULT ); } } catch (IllegalAccessException accessEx){ call.setException(accessEx); call.setStatus(Call.STATUS_ACCESS_DENIED); log.error("Service invocation error",accessEx); } catch (InvocationTargetException invocationEx){ call.setException(invocationEx); call.setStatus(Call.STATUS_INVOCATION_EXCEPTION); log.error("Service invocation error",invocationEx); } catch (Exception ex){ call.setException(ex); call.setStatus(Call.STATUS_GENERAL_EXCEPTION); log.error("Service invocation error",ex); } } }
true
true
public void invoke(Call call, ApplicationContext serviceContext) { String serviceName = call.getServiceName(); String methodName = call.getServiceMethodName(); log.debug("Service name " + serviceName); log.debug("Service method " + methodName); Object service = null; if(serviceContext.containsBean(serviceName)){ service = serviceContext.getBean(serviceName); } /* if(service == null && serviceContext.containsBean("scriptBeanFactory")){ scriptBeanFactory = (ScriptBeanFactory) serviceContext.getBean("scriptBeanFactory"); } if(service == null && scriptBeanFactory !=null) { // lets see if its a script. service = scriptBeanFactory.getBean(serviceName); } */ if(service == null) { call.setException(new ServiceNotFoundException(serviceName)); call.setStatus(Call.STATUS_SERVICE_NOT_FOUND); log.warn("Service not found: "+serviceName); return; // EXIT } else { log.debug("Service found: "+serviceName); } Object[] args = call.getArguments(); for (int i=0; i<args.length; i++) { log.debug(" "+i+" => "+args[i]); } Object[] methodResult = null; methodResult = findMethodWithExactParameters(service, methodName, args); if (methodResult.length == 0 || methodResult[0] == null) methodResult = findMethodWithListParameters(service, methodName, args); if (methodResult.length == 0 || methodResult[0] == null) { call.setStatus(Call.STATUS_METHOD_NOT_FOUND); call.setException(new MethodNotFoundException(methodName)); return; } Object result = null; Method method = (Method) methodResult[0]; Object[] params = (Object[]) methodResult[1]; try { log.debug("Invoking method: "+method.toString()); if (method.getReturnType() == Void.class) { method.invoke(service, params); call.setStatus(Call.STATUS_SUCCESS_VOID); } else { result = method.invoke(service, params); call.setResult(result); call.setStatus( result==null ? Call.STATUS_SUCCESS_NULL : Call.STATUS_SUCCESS_RESULT ); } } catch (IllegalAccessException accessEx){ call.setException(accessEx); call.setStatus(Call.STATUS_ACCESS_DENIED); log.error("Service invocation error",accessEx); } catch (InvocationTargetException invocationEx){ call.setException(invocationEx); call.setStatus(Call.STATUS_INVOCATION_EXCEPTION); log.error("Service invocation error",invocationEx); } catch (Exception ex){ call.setException(ex); call.setStatus(Call.STATUS_GENERAL_EXCEPTION); log.error("Service invocation error",ex); } }
public void invoke(Call call, ApplicationContext serviceContext) { String serviceName = call.getServiceName(); String methodName = call.getServiceMethodName(); log.debug("Service name " + serviceName); log.debug("Service method " + methodName); Object service = null; if(serviceContext.containsBean(serviceName)){ service = serviceContext.getBean(serviceName); } /* if(service == null && serviceContext.containsBean("scriptBeanFactory")){ scriptBeanFactory = (ScriptBeanFactory) serviceContext.getBean("scriptBeanFactory"); } if(service == null && scriptBeanFactory !=null) { // lets see if its a script. service = scriptBeanFactory.getBean(serviceName); } */ if(service == null) { call.setException(new ServiceNotFoundException(serviceName)); call.setStatus(Call.STATUS_SERVICE_NOT_FOUND); log.warn("Service not found: "+serviceName); return; // EXIT } else { log.debug("Service found: "+serviceName); } Object[] args = call.getArguments(); if (args != null) { for (int i=0; i<args.length; i++) { log.debug(" "+i+" => "+args[i]); } } Object[] methodResult = null; methodResult = findMethodWithExactParameters(service, methodName, args); if (methodResult.length == 0 || methodResult[0] == null) methodResult = findMethodWithListParameters(service, methodName, args); if (methodResult.length == 0 || methodResult[0] == null) { call.setStatus(Call.STATUS_METHOD_NOT_FOUND); call.setException(new MethodNotFoundException(methodName)); return; } Object result = null; Method method = (Method) methodResult[0]; Object[] params = (Object[]) methodResult[1]; try { log.debug("Invoking method: "+method.toString()); if (method.getReturnType() == Void.class) { method.invoke(service, params); call.setStatus(Call.STATUS_SUCCESS_VOID); } else { result = method.invoke(service, params); call.setResult(result); call.setStatus( result==null ? Call.STATUS_SUCCESS_NULL : Call.STATUS_SUCCESS_RESULT ); } } catch (IllegalAccessException accessEx){ call.setException(accessEx); call.setStatus(Call.STATUS_ACCESS_DENIED); log.error("Service invocation error",accessEx); } catch (InvocationTargetException invocationEx){ call.setException(invocationEx); call.setStatus(Call.STATUS_INVOCATION_EXCEPTION); log.error("Service invocation error",invocationEx); } catch (Exception ex){ call.setException(ex); call.setStatus(Call.STATUS_GENERAL_EXCEPTION); log.error("Service invocation error",ex); } }
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java b/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java index b7ab9ea7a..a165cdcd6 100644 --- a/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java +++ b/src/com/redhat/ceylon/compiler/java/codegen/CodegenUtil.java @@ -1,459 +1,462 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.java.codegen; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.java.codegen.AbstractTransformer.BoxingStrategy; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Specification; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilerAnnotation; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Term; /** * Utility functions that are specific to the codegen package * @see Util */ class CodegenUtil { private CodegenUtil(){} static boolean isErasedAttribute(String name){ // ERASURE return "hash".equals(name) || "string".equals(name); } public static boolean isHashAttribute(Declaration model) { return model instanceof Value && Decl.withinClassOrInterface(model) && model.isShared() && "hash".equals(model.getName()); } static boolean isUnBoxed(Term node){ return node.getUnboxed(); } static boolean isUnBoxed(TypedDeclaration decl){ // null is considered boxed return decl.getUnboxed() == Boolean.TRUE; } static void markUnBoxed(Term node) { node.setUnboxed(true); } static BoxingStrategy getBoxingStrategy(Term node) { return isUnBoxed(node) ? BoxingStrategy.UNBOXED : BoxingStrategy.BOXED; } static BoxingStrategy getBoxingStrategy(TypedDeclaration decl) { return isUnBoxed(decl) ? BoxingStrategy.UNBOXED : BoxingStrategy.BOXED; } static boolean isRaw(TypedDeclaration decl){ ProducedType type = decl.getType(); return type != null && type.isRaw(); } static boolean isRaw(Term node){ ProducedType type = node.getTypeModel(); return type != null && type.isRaw(); } static void markRaw(Term node) { ProducedType type = node.getTypeModel(); if(type != null) type.setRaw(true); } static boolean hasTypeErased(Term node){ return node.getTypeErased(); } static boolean hasTypeErased(TypedDeclaration decl){ return decl.getTypeErased(); } static void markTypeErased(Term node) { markTypeErased(node, true); } static void markTypeErased(Term node, boolean erased) { node.setTypeErased(erased); } static void markUntrustedType(Term node) { node.setUntrustedType(true); } static boolean hasUntrustedType(Term node) { return node.getUntrustedType(); } static boolean hasUntrustedType(TypedDeclaration decl){ Boolean ret = decl.getUntrustedType(); return ret != null && ret.booleanValue(); } /** * Determines if the given statement or argument has a compiler annotation * with the given name. * * @param decl The statement or argument * @param name The compiler annotation name * @return true if the statement or argument has an annotation with the * given name * * @see #hasCompilerAnnotationWithArgument(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration, String, String) */ static boolean hasCompilerAnnotation(Tree.StatementOrArgument decl, String name){ for(CompilerAnnotation annotation : decl.getCompilerAnnotations()){ if(annotation.getIdentifier().getText().equals(name)) return true; } return false; } static boolean hasCompilerAnnotationNoArgument(Tree.StatementOrArgument decl, String name){ for (CompilerAnnotation annotation : decl.getCompilerAnnotations()) { if (annotation.getIdentifier().getText().equals(name)) { if (annotation.getStringLiteral() == null) { return true; } } } return false; } /** * Determines if the given statement or argument has a compiler annotation * with the given name and with the given argument. * * @param decl The statement or argument * @param name The compiler annotation name * @param argument The compiler annotation's argument * @return true if the statement or argument has an annotation with the * given name and argument value * * @see #hasCompilerAnnotation(com.redhat.ceylon.compiler.typechecker.tree.Tree.Declaration, String) */ static boolean hasCompilerAnnotationWithArgument(Tree.StatementOrArgument decl, String name, String argument){ for (CompilerAnnotation annotation : decl.getCompilerAnnotations()) { if (annotation.getIdentifier().getText().equals(name)) { if (annotation.getStringLiteral() == null) { continue; } String text = annotation.getStringLiteral().getText(); if (text == null) { continue; } if (text.equals(argument)) { return true; } } } return false; } private static String getCompilerAnnotationArgument(Iterable<Tree.CompilerAnnotation> compilerAnnotations, String name) { for (CompilerAnnotation annotation : compilerAnnotations) { if (annotation.getIdentifier().getText().equals(name)) { if (annotation.getStringLiteral() == null) { continue; } String text = annotation.getStringLiteral().getText(); return text; } } return null; } static String getCompilerAnnotationArgument(Tree.StatementOrArgument def, String name) { return getCompilerAnnotationArgument(def.getCompilerAnnotations(), name); } /** * Returns the compiler annotation with the given name on the * given compilation unit, or null iff the unit lacks that annotation. */ static String getCompilerAnnotationArgument(Tree.CompilationUnit def, String name) { return getCompilerAnnotationArgument(def.getCompilerAnnotations(), name); } static boolean isDirectAccessVariable(Term term) { if(!(term instanceof BaseMemberExpression)) return false; Declaration decl = ((BaseMemberExpression)term).getDeclaration(); if(decl == null) // typechecker error return false; // make sure we don't try to optimise things which can't be optimised return Decl.isValue(decl) && !decl.isToplevel() && !decl.isClassOrInterfaceMember() && !decl.isCaptured() && !decl.isShared(); } static Declaration getTopmostRefinedDeclaration(Declaration decl){ return getTopmostRefinedDeclaration(decl, null); } static Declaration getTopmostRefinedDeclaration(Declaration decl, Map<Method, Method> methodOverrides){ if (decl instanceof MethodOrValue && ((MethodOrValue)decl).isParameter() && decl.getContainer() instanceof Class) { // Parameters in a refined class are not considered refinements themselves // We have in find the refined attribute Class c = (Class)decl.getContainer(); boolean isAlias = c.isAlias(); boolean isActual = c.isActual(); // aliases and actual classes actually do refine their extended type parameters so the same rules apply wrt // boxing and stuff if (isAlias || isActual) { int index = c.getParameterList().getParameters().indexOf(findParamForDecl(((TypedDeclaration)decl))); // ATM we only consider aliases if we're looking at aliases, and same for actual, not mixing the two. // Note(Stef): not entirely sure about that one, what about aliases of actual classes? while ((isAlias && c.isAlias()) || (isActual && c.isActual())) { c = c.getExtendedTypeDeclaration(); } // be safe if(c.getParameterList() == null || c.getParameterList().getParameters() == null || c.getParameterList().getParameters().size() <= index) return null; decl = c.getParameterList().getParameters().get(index).getModel(); } if (decl.isShared()) { Declaration refinedDecl = c.getRefinedMember(decl.getName(), null, false);//?? elipses=false?? if(refinedDecl != null && refinedDecl != decl) { return getTopmostRefinedDeclaration(refinedDecl, methodOverrides); } } return decl; } else if(decl instanceof MethodOrValue && ((MethodOrValue)decl).isParameter() // a parameter && ((decl.getContainer() instanceof Method && !(((Method)decl.getContainer()).isParameter())) // that's not parameter of a functional parameter || decl.getContainer() instanceof Specification // or is a parameter in a specification || (decl.getContainer() instanceof Method && ((Method)decl.getContainer()).isParameter() && Strategy.createMethod((Method)decl.getContainer())))) {// or is a class functional parameter // Parameters in a refined method are not considered refinements themselves // so we have to look up the corresponding parameter in the container's refined declaration Functional func = (Functional)getParameterized((MethodOrValue)decl); if(func == null) return decl; Declaration kk = getTopmostRefinedDeclaration((Declaration)func, methodOverrides); + // error recovery + if(kk instanceof Functional == false) + return decl; Functional refinedFunc = (Functional) kk; // shortcut if the functional doesn't override anything if(refinedFunc == func) return decl; if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) { // invalid input return decl; } for (int ii = 0; ii < func.getParameterLists().size(); ii++) { if (func.getParameterLists().get(ii).getParameters().size() != refinedFunc.getParameterLists().get(ii).getParameters().size()) { // invalid input return decl; } // find the index of the parameter in the declaration int index = 0; for (Parameter px : func.getParameterLists().get(ii).getParameters()) { if (px.getModel().equals(decl)) { // And return the corresponding parameter from the refined declaration return refinedFunc.getParameterLists().get(ii).getParameters().get(index).getModel(); } index++; } continue; } }else if(methodOverrides != null && decl instanceof Method && decl.getRefinedDeclaration() == decl && decl.getContainer() instanceof Specification && ((Specification)decl.getContainer()).getDeclaration() instanceof Method && ((Method) ((Specification)decl.getContainer()).getDeclaration()).isShortcutRefinement() // we do all the previous ones first because they are likely to filter out false positives cheaper than the // hash lookup we do next to make sure it is really one of those cases && methodOverrides.containsKey(decl)){ // special case for class X() extends T(){ m = function() => e; } which we inline decl = methodOverrides.get(decl); } Declaration refinedDecl = decl.getRefinedDeclaration(); if(refinedDecl != null && refinedDecl != decl) return getTopmostRefinedDeclaration(refinedDecl); return decl; } static Parameter findParamForDecl(Tree.TypedDeclaration decl) { String attrName = decl.getIdentifier().getText(); return findParamForDecl(attrName, decl.getDeclarationModel()); } static Parameter findParamForDecl(TypedDeclaration decl) { String attrName = decl.getName(); return findParamForDecl(attrName, decl); } static Parameter findParamForDecl(String attrName, TypedDeclaration decl) { Parameter result = null; if (decl.getContainer() instanceof Functional) { Functional f = (Functional)decl.getContainer(); result = f.getParameter(attrName); } return result; } static MethodOrValue findMethodOrValueForParam(Parameter param) { return param.getModel(); } static boolean isVoid(ProducedType type) { return type != null && type.getDeclaration() != null && type.getDeclaration().getUnit().getAnythingDeclaration().getType().isExactly(type); } public static boolean canOptimiseMethodSpecifier(Term expression, Method m) { if(expression instanceof Tree.FunctionArgument) return true; if(expression instanceof Tree.BaseMemberOrTypeExpression == false) return false; Declaration declaration = ((Tree.BaseMemberOrTypeExpression)expression).getDeclaration(); // methods are fine because they are constant if(declaration instanceof Method) return true; // toplevel constructors are fine if(declaration instanceof Class) return true; // parameters are constant too if(declaration instanceof MethodOrValue && ((MethodOrValue)declaration).isParameter()) return true; // the rest we can't know: we can't trust attributes that could be getters or overridden // we can't trust even toplevel attributes that could be made variable in the future because of // binary compat. return false; } public static Declaration getParameterized(Parameter parameter) { return parameter.getDeclaration(); } public static Declaration getParameterized(MethodOrValue methodOrValue) { Assert.that(methodOrValue.isParameter()); Scope scope = methodOrValue.getContainer(); if (scope instanceof Specification) { return ((Specification)scope).getDeclaration(); } else if (scope instanceof Declaration) { return (Declaration)scope; } throw Assert.fail(); } public static boolean isContainerFunctionalParameter(Declaration declaration) { Scope containerScope = declaration.getContainer(); Declaration containerDeclaration; if (containerScope instanceof Specification) { containerDeclaration = ((Specification)containerScope).getDeclaration(); } else if (containerScope instanceof Declaration) { containerDeclaration = (Declaration)containerScope; } else { throw Assert.fail(); } return containerDeclaration instanceof Method && ((Method)containerDeclaration).isParameter(); } public static boolean isMemberReferenceInvocation(Tree.InvocationExpression expr) { Tree.Term p = com.redhat.ceylon.compiler.typechecker.analyzer.Util.unwrapExpressionUntilTerm(expr.getPrimary()); if (com.redhat.ceylon.compiler.typechecker.analyzer.Util.isIndirectInvocation(expr) && p instanceof Tree.QualifiedMemberOrTypeExpression) { Tree.QualifiedMemberOrTypeExpression primary = (Tree.QualifiedMemberOrTypeExpression)p; Tree.Term q = com.redhat.ceylon.compiler.typechecker.analyzer.Util.unwrapExpressionUntilTerm(primary.getPrimary()); if (q instanceof Tree.BaseTypeExpression || q instanceof Tree.QualifiedTypeExpression) { return true; } } return false; } /** * Returns true if the given produced type is a type parameter or has type arguments which * are type parameters. */ public static boolean containsTypeParameter(ProducedType type) { TypeDeclaration declaration = type.getDeclaration(); if(declaration == null) return false; if(declaration instanceof TypeParameter) return true; for(ProducedType pt : type.getTypeArgumentList()){ if(containsTypeParameter(pt)){ return true; } } if(declaration instanceof IntersectionType){ List<ProducedType> types = declaration.getSatisfiedTypes(); for(int i=0,l=types.size();i<l;i++){ if(containsTypeParameter(types.get(i))) return true; } return false; } if(declaration instanceof UnionType){ List<ProducedType> types = declaration.getCaseTypes(); for(int i=0,l=types.size();i<l;i++){ if(containsTypeParameter(types.get(i))) return true; } return false; } return false; } }
true
true
static Declaration getTopmostRefinedDeclaration(Declaration decl, Map<Method, Method> methodOverrides){ if (decl instanceof MethodOrValue && ((MethodOrValue)decl).isParameter() && decl.getContainer() instanceof Class) { // Parameters in a refined class are not considered refinements themselves // We have in find the refined attribute Class c = (Class)decl.getContainer(); boolean isAlias = c.isAlias(); boolean isActual = c.isActual(); // aliases and actual classes actually do refine their extended type parameters so the same rules apply wrt // boxing and stuff if (isAlias || isActual) { int index = c.getParameterList().getParameters().indexOf(findParamForDecl(((TypedDeclaration)decl))); // ATM we only consider aliases if we're looking at aliases, and same for actual, not mixing the two. // Note(Stef): not entirely sure about that one, what about aliases of actual classes? while ((isAlias && c.isAlias()) || (isActual && c.isActual())) { c = c.getExtendedTypeDeclaration(); } // be safe if(c.getParameterList() == null || c.getParameterList().getParameters() == null || c.getParameterList().getParameters().size() <= index) return null; decl = c.getParameterList().getParameters().get(index).getModel(); } if (decl.isShared()) { Declaration refinedDecl = c.getRefinedMember(decl.getName(), null, false);//?? elipses=false?? if(refinedDecl != null && refinedDecl != decl) { return getTopmostRefinedDeclaration(refinedDecl, methodOverrides); } } return decl; } else if(decl instanceof MethodOrValue && ((MethodOrValue)decl).isParameter() // a parameter && ((decl.getContainer() instanceof Method && !(((Method)decl.getContainer()).isParameter())) // that's not parameter of a functional parameter || decl.getContainer() instanceof Specification // or is a parameter in a specification || (decl.getContainer() instanceof Method && ((Method)decl.getContainer()).isParameter() && Strategy.createMethod((Method)decl.getContainer())))) {// or is a class functional parameter // Parameters in a refined method are not considered refinements themselves // so we have to look up the corresponding parameter in the container's refined declaration Functional func = (Functional)getParameterized((MethodOrValue)decl); if(func == null) return decl; Declaration kk = getTopmostRefinedDeclaration((Declaration)func, methodOverrides); Functional refinedFunc = (Functional) kk; // shortcut if the functional doesn't override anything if(refinedFunc == func) return decl; if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) { // invalid input return decl; } for (int ii = 0; ii < func.getParameterLists().size(); ii++) { if (func.getParameterLists().get(ii).getParameters().size() != refinedFunc.getParameterLists().get(ii).getParameters().size()) { // invalid input return decl; } // find the index of the parameter in the declaration int index = 0; for (Parameter px : func.getParameterLists().get(ii).getParameters()) { if (px.getModel().equals(decl)) { // And return the corresponding parameter from the refined declaration return refinedFunc.getParameterLists().get(ii).getParameters().get(index).getModel(); } index++; } continue; } }else if(methodOverrides != null && decl instanceof Method && decl.getRefinedDeclaration() == decl && decl.getContainer() instanceof Specification && ((Specification)decl.getContainer()).getDeclaration() instanceof Method && ((Method) ((Specification)decl.getContainer()).getDeclaration()).isShortcutRefinement() // we do all the previous ones first because they are likely to filter out false positives cheaper than the // hash lookup we do next to make sure it is really one of those cases && methodOverrides.containsKey(decl)){ // special case for class X() extends T(){ m = function() => e; } which we inline decl = methodOverrides.get(decl); } Declaration refinedDecl = decl.getRefinedDeclaration(); if(refinedDecl != null && refinedDecl != decl) return getTopmostRefinedDeclaration(refinedDecl); return decl; }
static Declaration getTopmostRefinedDeclaration(Declaration decl, Map<Method, Method> methodOverrides){ if (decl instanceof MethodOrValue && ((MethodOrValue)decl).isParameter() && decl.getContainer() instanceof Class) { // Parameters in a refined class are not considered refinements themselves // We have in find the refined attribute Class c = (Class)decl.getContainer(); boolean isAlias = c.isAlias(); boolean isActual = c.isActual(); // aliases and actual classes actually do refine their extended type parameters so the same rules apply wrt // boxing and stuff if (isAlias || isActual) { int index = c.getParameterList().getParameters().indexOf(findParamForDecl(((TypedDeclaration)decl))); // ATM we only consider aliases if we're looking at aliases, and same for actual, not mixing the two. // Note(Stef): not entirely sure about that one, what about aliases of actual classes? while ((isAlias && c.isAlias()) || (isActual && c.isActual())) { c = c.getExtendedTypeDeclaration(); } // be safe if(c.getParameterList() == null || c.getParameterList().getParameters() == null || c.getParameterList().getParameters().size() <= index) return null; decl = c.getParameterList().getParameters().get(index).getModel(); } if (decl.isShared()) { Declaration refinedDecl = c.getRefinedMember(decl.getName(), null, false);//?? elipses=false?? if(refinedDecl != null && refinedDecl != decl) { return getTopmostRefinedDeclaration(refinedDecl, methodOverrides); } } return decl; } else if(decl instanceof MethodOrValue && ((MethodOrValue)decl).isParameter() // a parameter && ((decl.getContainer() instanceof Method && !(((Method)decl.getContainer()).isParameter())) // that's not parameter of a functional parameter || decl.getContainer() instanceof Specification // or is a parameter in a specification || (decl.getContainer() instanceof Method && ((Method)decl.getContainer()).isParameter() && Strategy.createMethod((Method)decl.getContainer())))) {// or is a class functional parameter // Parameters in a refined method are not considered refinements themselves // so we have to look up the corresponding parameter in the container's refined declaration Functional func = (Functional)getParameterized((MethodOrValue)decl); if(func == null) return decl; Declaration kk = getTopmostRefinedDeclaration((Declaration)func, methodOverrides); // error recovery if(kk instanceof Functional == false) return decl; Functional refinedFunc = (Functional) kk; // shortcut if the functional doesn't override anything if(refinedFunc == func) return decl; if (func.getParameterLists().size() != refinedFunc.getParameterLists().size()) { // invalid input return decl; } for (int ii = 0; ii < func.getParameterLists().size(); ii++) { if (func.getParameterLists().get(ii).getParameters().size() != refinedFunc.getParameterLists().get(ii).getParameters().size()) { // invalid input return decl; } // find the index of the parameter in the declaration int index = 0; for (Parameter px : func.getParameterLists().get(ii).getParameters()) { if (px.getModel().equals(decl)) { // And return the corresponding parameter from the refined declaration return refinedFunc.getParameterLists().get(ii).getParameters().get(index).getModel(); } index++; } continue; } }else if(methodOverrides != null && decl instanceof Method && decl.getRefinedDeclaration() == decl && decl.getContainer() instanceof Specification && ((Specification)decl.getContainer()).getDeclaration() instanceof Method && ((Method) ((Specification)decl.getContainer()).getDeclaration()).isShortcutRefinement() // we do all the previous ones first because they are likely to filter out false positives cheaper than the // hash lookup we do next to make sure it is really one of those cases && methodOverrides.containsKey(decl)){ // special case for class X() extends T(){ m = function() => e; } which we inline decl = methodOverrides.get(decl); } Declaration refinedDecl = decl.getRefinedDeclaration(); if(refinedDecl != null && refinedDecl != decl) return getTopmostRefinedDeclaration(refinedDecl); return decl; }
diff --git a/genetica-libraries/src/main/java/umcg/genetica/io/trityper/TriTyperExpressionData.java b/genetica-libraries/src/main/java/umcg/genetica/io/trityper/TriTyperExpressionData.java index 6450895c..bd33e949 100644 --- a/genetica-libraries/src/main/java/umcg/genetica/io/trityper/TriTyperExpressionData.java +++ b/genetica-libraries/src/main/java/umcg/genetica/io/trityper/TriTyperExpressionData.java @@ -1,747 +1,747 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package umcg.genetica.io.trityper; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import umcg.genetica.containers.Pair; import umcg.genetica.io.Gpio; import umcg.genetica.io.text.TextFile; import umcg.genetica.io.trityper.util.ChrAnnotation; import umcg.genetica.math.stats.Descriptives; import umcg.genetica.util.RankArray; /** * * @author harmjan // rows: individuals cols: probes */ public class TriTyperExpressionData { private int[] chrStart; private int[] chrStop; private byte[] chr; private String[] annotation; private double[][] matrix; private String[] individuals; private HashMap<String, Integer> individualNameToId; private String[] probes; private HashMap<String, Integer> probeNameToId; private HashMap<String, ArrayList<Integer>> annotationToProbeId; private HashSet<String> includeIndividuals; private boolean confineToProbesThatMapToAnyChromosome; private Integer confineToProbesMappingOnChromosome; private HashSet<String> probesConfine; private double[] probeOriginalMean; private double[] probeOriginalVariance; private double[] probeMean; private double[] probeVariance; private String m_platform; private Pair<List<String>, List<List<String>>> pathwayDefinitions; public TriTyperExpressionData() { } public TriTyperExpressionData(String loc, String probeAnnotationLoc, String platform, boolean cistrans) throws IOException { this.load(loc, probeAnnotationLoc, platform, cistrans); } /** * @return the rowNames */ public String[] getRowNames() { return individuals; } /** * @param rowNames the rowNames to set */ public void setRowNames(String[] rowNames) { this.individuals = rowNames; } /** * @return the rowNameToId */ public HashMap<String, Integer> getRowNameToId() { return individualNameToId; } /** * @param rowNameToId the rowNameToId to set */ public void setRowNameToId(HashMap<String, Integer> rowNameToId) { this.individualNameToId = rowNameToId; } /** * @return the colNames */ public String[] getColNames() { return probes; } /** * @param colNames the colNames to set */ public void setColNames(String[] colNames) { this.probes = colNames; } /** * @return the colNameToId */ public HashMap<String, Integer> getColNameToId() { return probeNameToId; } /** * @param colNameToId the colNameToId to set */ public void setColNameToId(HashMap<String, Integer> colNameToId) { this.probeNameToId = colNameToId; } /** * @return the matrix */ public double[][] getMatrix() { return matrix; } /** * @param matrix the matrix to set */ public void setMatrix(double[][] matrix) { this.matrix = matrix; } public void setIncludeIndividuals(HashSet<String> includedIndividuals) { this.includeIndividuals = includedIndividuals; } public void setConfineToProbesThatMapToChromosome(boolean chr) { this.confineToProbesThatMapToAnyChromosome = chr; } public void setConfineToProbesThatMapToChromosome(Integer chr) { this.confineToProbesMappingOnChromosome = chr; } public void confineToProbes(HashSet<String> probes) { this.probesConfine = probes; } public final boolean load(String loc, String probeAnnotationLoc, String platform, boolean cistrans) throws IOException { if (!Gpio.exists(loc)) { throw new IOException("! Error loading expression data: " + loc + " does not exist"); } System.out.println("Loading expression data from: " + loc); TextFile in = new TextFile(loc, TextFile.R); // detect whether TriTyper dataset // load probeAnnotation otherwise int numProbes = 0; boolean trityperformat = false; int offset = 1; String[] elems = null; numProbes = in.countLines(); elems = in.readLineElemsReturnReference(TextFile.tab); // header line... // MultipleHits SequenceIdentity Chr ChrStart ChrEnd if (elems[0].trim().toLowerCase().equals("probe") && elems[3].trim().toLowerCase().equals("chr") && elems[4].trim().toLowerCase().equals("chrstart")) { System.out.println("! Expression data is still in the old, deprecated TriTyper format."); trityperformat = true; offset = 9; } else if (probeAnnotationLoc == null && !cistrans) { throw new IOException("ERROR: Probe annotation is not specified. Please specify probe annotation or provide expression data in TriTyper format!"); } // load the probe annotation, if any present HashMap<String, Byte> hashProbeChr = null; HashMap<String, Integer> hashProbeChrStart = null; HashMap<String, Integer> hashProbeChrStop = null; HashMap<String, String> hashAnnot = null; if (probeAnnotationLoc != null) { if (trityperformat) { System.out.println("! WARNING: overriding probe annotation from TriTyper file with probe annotation!"); trityperformat = false; offset = 9; } System.out.println("Loading probe annotation from: " + probeAnnotationLoc); hashProbeChr = new HashMap<String, Byte>(); hashProbeChrStart = new HashMap<String, Integer>(); hashProbeChrStop = new HashMap<String, Integer>(); hashAnnot = new HashMap<String, String>(); TextFile an = new TextFile(probeAnnotationLoc, TextFile.R); an.readLineElemsReturnReference(TextFile.tab); String[] anelems = an.readLineElemsReturnReference(TextFile.tab); boolean filterplatform = true; if (m_platform == null) { filterplatform = false; } int numAnnotLoaded = 0; while (anelems != null) { if (anelems.length >= 6 && (!filterplatform || (filterplatform && anelems[0].equals(m_platform)))) { String probe = new String(anelems[1].getBytes("UTF-8")); Byte bchr = ChrAnnotation.parseChr(anelems[3]); Integer ichrStart = -1; Integer ichrStop = -1; try { ichrStart = Integer.parseInt(anelems[4]); ichrStop = Integer.parseInt(anelems[5]); } catch (NumberFormatException e) { } String annot = new String(anelems[2].getBytes("UTF-8")); hashProbeChr.put(probe, bchr); hashProbeChrStart.put(probe, ichrStart); hashProbeChrStop.put(probe, ichrStop); hashAnnot.put(probe, annot); numAnnotLoaded++; } anelems = an.readLineElemsReturnReference(TextFile.tab); } an.close(); if (numAnnotLoaded == 0) { throw new IOException("Error: no probe annotation available for expression platform: " + platform); } else { System.out.println("Loaded annotation for " + numAnnotLoaded + " probes."); } } int numIndsIncluded = 0; HashMap<String, Integer> indToId = new HashMap<String, Integer>(); boolean[] includeCol = new boolean[elems.length]; for (int pos = offset; pos < elems.length; pos++) { if (includeIndividuals == null || includeIndividuals.contains(elems[pos])) { numIndsIncluded++; includeCol[pos] = true; } else { includeCol[pos] = false; } } individuals = new String[numIndsIncluded]; int indNo = 0; for (int pos = offset; pos < elems.length; pos++) { if (includeCol[pos]) { individuals[indNo] = new String(elems[pos].getBytes("UTF-8")); indToId.put(elems[pos], indNo); indNo++; } } individualNameToId = indToId; System.out.println("Found gene expression data for " + numIndsIncluded + " individuals"); ArrayList<Integer> tmpChrStart = new ArrayList<Integer>(); ArrayList<Integer> tmpChrEnd = new ArrayList<Integer>(); ArrayList<Byte> tmpChr = new ArrayList<Byte>(); ArrayList<String> tmpProbe = new ArrayList<String>(); ArrayList<float[]> tmpRaw = new ArrayList<float[]>(); ArrayList<String> tmpAnnotation = new ArrayList<String>(); annotationToProbeId = new HashMap<String, ArrayList<Integer>>(); int probeNr = 0; elems = in.readLineElemsReturnReference(TextFile.tab); if (!trityperformat) { if (hashProbeChr == null && !cistrans) { System.out.println("WARNING: no probe annotation available."); } } int probesIncluded = 0; int probesExcluded = 0; HashSet<Integer> probesWithMissingValues = new HashSet<Integer>(); while (elems != null) { boolean printreason = true; if (elems.length > 1) { String probe = new String(elems[0].getBytes("UTF-8")); String annotstr = null; Byte probeChr = null; Integer probeChrStart = null; Integer probeChrEnd = null; - boolean includeprobe = false; + boolean includeprobe = true; String reason = ""; if (trityperformat && elems.length > 9) { // Probe MultipleHits SequenceIdentity Chr ChrStart ChrEnd Ensembl HUGO DIP Byte bchr = ChrAnnotation.parseChr(elems[3]); if (probesConfine == null || probesConfine.contains(probe)) { if (!confineToProbesThatMapToAnyChromosome || bchr >= 1) { if (confineToProbesMappingOnChromosome == null || confineToProbesMappingOnChromosome.equals((int) bchr)) { probeChr = bchr; probeChrStart = Integer.parseInt(elems[4]); probeChrEnd = Integer.parseInt(elems[5]); annotstr = new String(elems[7].getBytes("UTF-8")); includeprobe = true; } else { probesExcluded++; reason += "\tprobe does not map to chromosome:" + confineToProbesMappingOnChromosome + "\t" + bchr; includeprobe = false; } } else { probesExcluded++; reason += "\tprobe does not map to any chromosome:\t" + bchr; includeprobe = false; } } else { probesExcluded++; // reason += "\tprobe is not selected during confinement."; printreason = false; includeprobe = false; } } else if (!trityperformat) { if (hashProbeChr != null && !cistrans) { probeChr = hashProbeChr.get(probe); probeChrStart = hashProbeChrStart.get(probe); probeChrEnd = hashProbeChrStop.get(probe); annotstr = hashAnnot.get(probe); if (probeChr == null) { + includeprobe = false; reason += "Probe annotation not loaded for probe:\t" + probe; } else if ((probesConfine == null || probesConfine.contains(probe)) && (!confineToProbesThatMapToAnyChromosome || probeChr >= 1) - && (confineToProbesMappingOnChromosome == null || confineToProbesMappingOnChromosome.equals((int) probeChr))) { + && (confineToProbesMappingOnChromosome != null && confineToProbesMappingOnChromosome.equals((int) probeChr))) { includeprobe = true; - } else { - reason += "Probe not in confine list or not mapping to a chr of interest"; } } else if (!cistrans) { throw new IOException("ERROR: probe annotation not loaded?"); } else if (hashProbeChr != null && cistrans) { probeChr = hashProbeChr.get(probe); probeChrStart = hashProbeChrStart.get(probe); probeChrEnd = hashProbeChrStop.get(probe); annotstr = hashAnnot.get(probe); - includeprobe = true; } else { if ((probesConfine == null || probesConfine.contains(probe))) { includeprobe = true; probeChr = -1; probeChrStart = -1; probeChrEnd = -1; annotstr = "-"; } else { + includeprobe = false; printreason = false; } } } else { System.err.println("Error: data is in TriTyper format, but is probably wrongly formated (because the number of columns <10!)"); System.exit(-1); } if (!cistrans && includeprobe && probeChr == null && probeChrStart == null && probeChrEnd == null && !(probesConfine != null && !probesConfine.contains(probe))) { reason += "WARNING: probe\t" + probe + "\thas no annotation at all! Will exclude this probe from further use."; + includeprobe = false; } if (includeprobe) { probesIncluded++; tmpProbe.add(probe); if (probeChr == null) { probeChr = -1; } tmpChr.add(probeChr); if (probeChrStart == null) { probeChrStart = -1; } tmpChrStart.add(probeChrStart); if (probeChrEnd == null) { probeChrEnd = -1; } tmpChrEnd.add(probeChrEnd); if (annotstr != null && annotstr.length() > 0) { ArrayList<Integer> annotationToProbe = annotationToProbeId.get(new String(elems[7].getBytes("UTF-8"))); if (annotationToProbe == null) { annotationToProbe = new ArrayList<Integer>(); } annotationToProbe.add(probeNr); annotationToProbeId.put(probe, annotationToProbe); } if (annotstr == null) { annotstr = "-"; } tmpAnnotation.add(annotstr); int samplePos = 0; float[] tmpDt = new float[numIndsIncluded]; for (int pos = offset; pos < elems.length; pos++) { if (includeCol[pos]) { try { tmpDt[samplePos] = Float.parseFloat(elems[pos]); } catch (NumberFormatException e) { System.err.println("WARNING: missing value for column:\t" + pos + "\tprobe:\t" + probe); tmpDt[samplePos] = Float.NaN; probesWithMissingValues.add(probeNr); } samplePos++; } } tmpRaw.add(tmpDt); probeNr++; if (probeNr % 10000 == 0) { System.out.println(probeNr + " probes parsed."); } } else if (printreason) { System.out.println("Probe\t" + probe + "\texcluded. Reason:\t" + reason); } } elems = in.readLineElemsReturnReference(TextFile.tab); } in.close(); if (probesWithMissingValues.size() > 0) { System.err.println("WARNING: " + probesWithMissingValues.size() + " probes with missing values detected. Will replace missing values with average probe value."); ArrayList<float[]> newRaw = new ArrayList<float[]>(); for (int i = 0; i < tmpRaw.size(); i++) { if (probesWithMissingValues.contains(i)) { float[] data = tmpRaw.get(i); double sum = 0; int nrNotMissing = 0; for (int j = 0; j < data.length; j++) { if (!Float.isNaN(data[j])) { sum += data[j]; nrNotMissing++; } } sum /= nrNotMissing; for (int j = 0; j < data.length; j++) { if (Float.isNaN(data[j])) { data[j] = (float) sum; } } } else { newRaw.add(tmpRaw.get(i)); } } } System.out.println("Probes selected:\t" + probesIncluded); System.out.println("Probes not selected:\t" + probesExcluded); if (probeNr == 0) { System.err.println("ERROR: No gene expression data loaded for (no probes matching criteria): " + loc); return false; } this.chr = new byte[probeNr]; this.annotation = new String[probeNr]; this.chrStart = new int[probeNr]; this.chrStop = new int[probeNr]; this.probes = new String[probeNr]; this.matrix = new double[probeNr][numIndsIncluded]; probeNameToId = new HashMap<String, Integer>(); for (int i = 0; i < probeNr; i++) { probes[i] = tmpProbe.get(i); probeNameToId.put(probes[i], i); annotation[i] = tmpAnnotation.get(i); if (annotation[i] == null) { annotation[i] = "-"; } if (tmpChr.get(i) == null) { System.err.println("No chromosome annotation loaded for probe " + tmpProbe.get(i)); chr[i] = -1; chrStart[i] = -1; chrStop[i] = -1; } else { chr[i] = tmpChr.get(i); chrStart[i] = tmpChrStart.get(i); chrStop[i] = tmpChrEnd.get(i); } } for (int i = 0; i < numIndsIncluded; i++) { for (int p = 0; p < probeNr; p++) { matrix[p][i] = tmpRaw.get(p)[i]; } } tmpChrStart = null; tmpChrEnd = null; tmpChr = null; tmpProbe = null; tmpRaw = null; tmpAnnotation = null; if (pathwayDefinitions != null) { // do stuff. System.out.println("Now performing Pathway merger magic. *stars and unicorns*"); List<String> pathwayNames = pathwayDefinitions.getLeft(); List<List<String>> genesInPathways = pathwayDefinitions.getRight(); double[][] pathwayData = new double[pathwayNames.size()][this.individuals.length]; boolean[] usePathway = new boolean[pathwayNames.size()]; int nrPathwaysToUse = 0; for (int p = 0, len = pathwayNames.size(); p < len; p++) { List<String> ensGenesForPathway = genesInPathways.get(p); HashSet<String> hashGenesForPathway = new HashSet<String>(ensGenesForPathway); int nrProbesFound = 0; for (int probe = 0; probe < matrix.length; probe++) { String annotationForProbe = annotation[probe]; String[] annStrings = annotationForProbe.split(";"); boolean hasRightAnnotation = false; for (String s : annStrings) { if (hashGenesForPathway.contains(s)) { hasRightAnnotation = true; } } if (hasRightAnnotation) { // do stuff :-) :P for (int i = 0; i < individuals.length; i++) { pathwayData[p][i] += matrix[probe][i]; } nrProbesFound++; } } if (nrProbesFound > 1) { for (int i = 0; i < individuals.length; i++) { pathwayData[p][i] /= nrProbesFound; } } if (nrProbesFound >= 10) { usePathway[p] = true; nrPathwaysToUse++; } } System.out.println("Final number of pathways used in this dataset: " + nrPathwaysToUse); matrix = new double[nrPathwaysToUse][0]; probes = new String[nrPathwaysToUse]; probeNameToId = new HashMap<String, Integer>(); probeMean = new double[nrPathwaysToUse]; probeVariance = new double[nrPathwaysToUse]; probeOriginalMean = new double[nrPathwaysToUse]; probeOriginalVariance = new double[nrPathwaysToUse]; chr = new byte[nrPathwaysToUse]; chrStart = new int[nrPathwaysToUse]; chrStop = new int[nrPathwaysToUse]; int nrPathwaysUsed = 0; for (int p = 0, len = pathwayNames.size(); p < len; p++) { if (usePathway[p]) { matrix[nrPathwaysUsed] = pathwayData[p]; probes[nrPathwaysUsed] = pathwayNames.get(p); probeNameToId.put(probes[nrPathwaysUsed], nrPathwaysUsed); nrPathwaysUsed++; } } } calcMeanAndVariance(); for (int p = 0; p < matrix.length; p++) { for (int s = 0; s < matrix[p].length; s++) { matrix[p][s] -= probeMean[p]; } } calcMeanAndVariance(); System.out.println("Loaded " + matrix.length + " probes for " + individuals.length + " individuals"); return true; } /** * @return the chrStart */ public int[] getChrStart() { return chrStart; } /** * @param chrStart the chrStart to set */ public void setChrStart(int[] chrStart) { this.chrStart = chrStart; } /** * @return the chrStop */ public int[] getChrStop() { return chrStop; } /** * @param chrStop the chrStop to set */ public void setChrStop(int[] chrStop) { this.chrStop = chrStop; } /** * @return the annotation */ public String[] getAnnotation() { return annotation; } /** * @param annotation the annotation to set */ public void setAnnotation(String[] annotation) { this.annotation = annotation; } /** * @return the chr */ public byte[] getChr() { return chr; } /** * @param chr the chr to set */ public void setChr(byte[] chr) { this.chr = chr; } public String[] getIndividuals() { return individuals; } public String[] getProbes() { return probes; } public HashMap<String, Integer> getIndividualToId() { return individualNameToId; } public HashMap<String, Integer> getProbeToId() { return probeNameToId; } public Integer getIndividualId(String key) { return individualNameToId.get(key); } private void calcMeanAndVariance() { //Precalculate means and variances. This will improve calculations substantially: int probeCount = probes.length; probeOriginalMean = new double[probeCount]; probeOriginalVariance = new double[probeCount]; probeMean = new double[probeCount]; probeVariance = new double[probeCount]; for (int f = 0; f < probeCount; ++f) { double[] probeData = getProbeData(f); probeOriginalMean[f] = Descriptives.mean(probeData); probeOriginalVariance[f] = Descriptives.variance(probeData, probeMean[f]); probeMean[f] = Descriptives.mean(probeData); probeVariance[f] = Descriptives.variance(probeData, probeMean[f]); } } private double[] getProbeData(int f) { double[] probeData = new double[individuals.length]; System.arraycopy(matrix[f], 0, probeData, 0, individuals.length); return probeData; } public double[] getProbeVariance() { return probeVariance; } public double[] getProbeMean() { return probeMean; } public double[] getOriginalProbeVariance() { return probeOriginalVariance; } public double[] getOriginalProbeMean() { return probeOriginalMean; } /** * Ranks all the expressiondata available in rawData */ public void rankAllExpressionData(boolean rankWithTies) { RankArray r = new RankArray(); for (int p = 0; p < probes.length; ++p) { double[] probeData = getProbeData(p); if (probeVariance[p] == 0) { System.out.println("Excluding probe that has no variance in expression:\t" + probes[p] + "\t" + annotation[p]); } else { if (Double.isNaN(probeMean[p]) || Double.isNaN(probeVariance[p])) { System.out.println("Error ranking expression data: probe mean or variance is NaN!:\t" + p + "\t" + probes[p] + "\t" + probeMean[p] + "\t" + probeVariance[p]); System.exit(-1); } else { probeData = r.rank(probeData, rankWithTies); setProbeData(p, probeData); probeMean[p] = Descriptives.mean(probeData); probeVariance[p] = Descriptives.variance(probeData, probeMean[p]); } } } } private void setProbeData(int f, double[] probeData) { for (int i = 0; i < individuals.length; i++) { matrix[f][i] = (float) probeData[i]; } } public void pruneAndReorderSamples(List<String> colObjects) { double[][] newMatrix = new double[matrix.length][colObjects.size()]; HashMap<String, Integer> indToInd = new HashMap<String, Integer>(); for (int i = 0; i < colObjects.size(); i++) { String ind = colObjects.get(i); indToInd.put(ind, i); } for (int i = 0; i < individuals.length; i++) { Integer newId = indToInd.get(individuals[i]); if (newId != null) { for (int row = 0; row < matrix.length; row++) { newMatrix[row][newId] = matrix[row][i]; } } } matrix = newMatrix; individualNameToId = indToInd; individuals = colObjects.toArray(new String[0]); } public void setPathwayDefinitions(Pair<List<String>, List<List<String>>> pathwayDefinitions) { this.pathwayDefinitions = pathwayDefinitions; } }
false
true
public final boolean load(String loc, String probeAnnotationLoc, String platform, boolean cistrans) throws IOException { if (!Gpio.exists(loc)) { throw new IOException("! Error loading expression data: " + loc + " does not exist"); } System.out.println("Loading expression data from: " + loc); TextFile in = new TextFile(loc, TextFile.R); // detect whether TriTyper dataset // load probeAnnotation otherwise int numProbes = 0; boolean trityperformat = false; int offset = 1; String[] elems = null; numProbes = in.countLines(); elems = in.readLineElemsReturnReference(TextFile.tab); // header line... // MultipleHits SequenceIdentity Chr ChrStart ChrEnd if (elems[0].trim().toLowerCase().equals("probe") && elems[3].trim().toLowerCase().equals("chr") && elems[4].trim().toLowerCase().equals("chrstart")) { System.out.println("! Expression data is still in the old, deprecated TriTyper format."); trityperformat = true; offset = 9; } else if (probeAnnotationLoc == null && !cistrans) { throw new IOException("ERROR: Probe annotation is not specified. Please specify probe annotation or provide expression data in TriTyper format!"); } // load the probe annotation, if any present HashMap<String, Byte> hashProbeChr = null; HashMap<String, Integer> hashProbeChrStart = null; HashMap<String, Integer> hashProbeChrStop = null; HashMap<String, String> hashAnnot = null; if (probeAnnotationLoc != null) { if (trityperformat) { System.out.println("! WARNING: overriding probe annotation from TriTyper file with probe annotation!"); trityperformat = false; offset = 9; } System.out.println("Loading probe annotation from: " + probeAnnotationLoc); hashProbeChr = new HashMap<String, Byte>(); hashProbeChrStart = new HashMap<String, Integer>(); hashProbeChrStop = new HashMap<String, Integer>(); hashAnnot = new HashMap<String, String>(); TextFile an = new TextFile(probeAnnotationLoc, TextFile.R); an.readLineElemsReturnReference(TextFile.tab); String[] anelems = an.readLineElemsReturnReference(TextFile.tab); boolean filterplatform = true; if (m_platform == null) { filterplatform = false; } int numAnnotLoaded = 0; while (anelems != null) { if (anelems.length >= 6 && (!filterplatform || (filterplatform && anelems[0].equals(m_platform)))) { String probe = new String(anelems[1].getBytes("UTF-8")); Byte bchr = ChrAnnotation.parseChr(anelems[3]); Integer ichrStart = -1; Integer ichrStop = -1; try { ichrStart = Integer.parseInt(anelems[4]); ichrStop = Integer.parseInt(anelems[5]); } catch (NumberFormatException e) { } String annot = new String(anelems[2].getBytes("UTF-8")); hashProbeChr.put(probe, bchr); hashProbeChrStart.put(probe, ichrStart); hashProbeChrStop.put(probe, ichrStop); hashAnnot.put(probe, annot); numAnnotLoaded++; } anelems = an.readLineElemsReturnReference(TextFile.tab); } an.close(); if (numAnnotLoaded == 0) { throw new IOException("Error: no probe annotation available for expression platform: " + platform); } else { System.out.println("Loaded annotation for " + numAnnotLoaded + " probes."); } } int numIndsIncluded = 0; HashMap<String, Integer> indToId = new HashMap<String, Integer>(); boolean[] includeCol = new boolean[elems.length]; for (int pos = offset; pos < elems.length; pos++) { if (includeIndividuals == null || includeIndividuals.contains(elems[pos])) { numIndsIncluded++; includeCol[pos] = true; } else { includeCol[pos] = false; } } individuals = new String[numIndsIncluded]; int indNo = 0; for (int pos = offset; pos < elems.length; pos++) { if (includeCol[pos]) { individuals[indNo] = new String(elems[pos].getBytes("UTF-8")); indToId.put(elems[pos], indNo); indNo++; } } individualNameToId = indToId; System.out.println("Found gene expression data for " + numIndsIncluded + " individuals"); ArrayList<Integer> tmpChrStart = new ArrayList<Integer>(); ArrayList<Integer> tmpChrEnd = new ArrayList<Integer>(); ArrayList<Byte> tmpChr = new ArrayList<Byte>(); ArrayList<String> tmpProbe = new ArrayList<String>(); ArrayList<float[]> tmpRaw = new ArrayList<float[]>(); ArrayList<String> tmpAnnotation = new ArrayList<String>(); annotationToProbeId = new HashMap<String, ArrayList<Integer>>(); int probeNr = 0; elems = in.readLineElemsReturnReference(TextFile.tab); if (!trityperformat) { if (hashProbeChr == null && !cistrans) { System.out.println("WARNING: no probe annotation available."); } } int probesIncluded = 0; int probesExcluded = 0; HashSet<Integer> probesWithMissingValues = new HashSet<Integer>(); while (elems != null) { boolean printreason = true; if (elems.length > 1) { String probe = new String(elems[0].getBytes("UTF-8")); String annotstr = null; Byte probeChr = null; Integer probeChrStart = null; Integer probeChrEnd = null; boolean includeprobe = false; String reason = ""; if (trityperformat && elems.length > 9) { // Probe MultipleHits SequenceIdentity Chr ChrStart ChrEnd Ensembl HUGO DIP Byte bchr = ChrAnnotation.parseChr(elems[3]); if (probesConfine == null || probesConfine.contains(probe)) { if (!confineToProbesThatMapToAnyChromosome || bchr >= 1) { if (confineToProbesMappingOnChromosome == null || confineToProbesMappingOnChromosome.equals((int) bchr)) { probeChr = bchr; probeChrStart = Integer.parseInt(elems[4]); probeChrEnd = Integer.parseInt(elems[5]); annotstr = new String(elems[7].getBytes("UTF-8")); includeprobe = true; } else { probesExcluded++; reason += "\tprobe does not map to chromosome:" + confineToProbesMappingOnChromosome + "\t" + bchr; includeprobe = false; } } else { probesExcluded++; reason += "\tprobe does not map to any chromosome:\t" + bchr; includeprobe = false; } } else { probesExcluded++; // reason += "\tprobe is not selected during confinement."; printreason = false; includeprobe = false; } } else if (!trityperformat) { if (hashProbeChr != null && !cistrans) { probeChr = hashProbeChr.get(probe); probeChrStart = hashProbeChrStart.get(probe); probeChrEnd = hashProbeChrStop.get(probe); annotstr = hashAnnot.get(probe); if (probeChr == null) { reason += "Probe annotation not loaded for probe:\t" + probe; } else if ((probesConfine == null || probesConfine.contains(probe)) && (!confineToProbesThatMapToAnyChromosome || probeChr >= 1) && (confineToProbesMappingOnChromosome == null || confineToProbesMappingOnChromosome.equals((int) probeChr))) { includeprobe = true; } else { reason += "Probe not in confine list or not mapping to a chr of interest"; } } else if (!cistrans) { throw new IOException("ERROR: probe annotation not loaded?"); } else if (hashProbeChr != null && cistrans) { probeChr = hashProbeChr.get(probe); probeChrStart = hashProbeChrStart.get(probe); probeChrEnd = hashProbeChrStop.get(probe); annotstr = hashAnnot.get(probe); includeprobe = true; } else { if ((probesConfine == null || probesConfine.contains(probe))) { includeprobe = true; probeChr = -1; probeChrStart = -1; probeChrEnd = -1; annotstr = "-"; } else { printreason = false; } } } else { System.err.println("Error: data is in TriTyper format, but is probably wrongly formated (because the number of columns <10!)"); System.exit(-1); } if (!cistrans && includeprobe && probeChr == null && probeChrStart == null && probeChrEnd == null && !(probesConfine != null && !probesConfine.contains(probe))) { reason += "WARNING: probe\t" + probe + "\thas no annotation at all! Will exclude this probe from further use."; } if (includeprobe) { probesIncluded++; tmpProbe.add(probe); if (probeChr == null) { probeChr = -1; } tmpChr.add(probeChr); if (probeChrStart == null) { probeChrStart = -1; } tmpChrStart.add(probeChrStart); if (probeChrEnd == null) { probeChrEnd = -1; } tmpChrEnd.add(probeChrEnd); if (annotstr != null && annotstr.length() > 0) { ArrayList<Integer> annotationToProbe = annotationToProbeId.get(new String(elems[7].getBytes("UTF-8"))); if (annotationToProbe == null) { annotationToProbe = new ArrayList<Integer>(); } annotationToProbe.add(probeNr); annotationToProbeId.put(probe, annotationToProbe); } if (annotstr == null) { annotstr = "-"; } tmpAnnotation.add(annotstr); int samplePos = 0; float[] tmpDt = new float[numIndsIncluded]; for (int pos = offset; pos < elems.length; pos++) { if (includeCol[pos]) { try { tmpDt[samplePos] = Float.parseFloat(elems[pos]); } catch (NumberFormatException e) { System.err.println("WARNING: missing value for column:\t" + pos + "\tprobe:\t" + probe); tmpDt[samplePos] = Float.NaN; probesWithMissingValues.add(probeNr); } samplePos++; } } tmpRaw.add(tmpDt); probeNr++; if (probeNr % 10000 == 0) { System.out.println(probeNr + " probes parsed."); } } else if (printreason) { System.out.println("Probe\t" + probe + "\texcluded. Reason:\t" + reason); } } elems = in.readLineElemsReturnReference(TextFile.tab); } in.close(); if (probesWithMissingValues.size() > 0) { System.err.println("WARNING: " + probesWithMissingValues.size() + " probes with missing values detected. Will replace missing values with average probe value."); ArrayList<float[]> newRaw = new ArrayList<float[]>(); for (int i = 0; i < tmpRaw.size(); i++) { if (probesWithMissingValues.contains(i)) { float[] data = tmpRaw.get(i); double sum = 0; int nrNotMissing = 0; for (int j = 0; j < data.length; j++) { if (!Float.isNaN(data[j])) { sum += data[j]; nrNotMissing++; } } sum /= nrNotMissing; for (int j = 0; j < data.length; j++) { if (Float.isNaN(data[j])) { data[j] = (float) sum; } } } else { newRaw.add(tmpRaw.get(i)); } } } System.out.println("Probes selected:\t" + probesIncluded); System.out.println("Probes not selected:\t" + probesExcluded); if (probeNr == 0) { System.err.println("ERROR: No gene expression data loaded for (no probes matching criteria): " + loc); return false; } this.chr = new byte[probeNr]; this.annotation = new String[probeNr]; this.chrStart = new int[probeNr]; this.chrStop = new int[probeNr]; this.probes = new String[probeNr]; this.matrix = new double[probeNr][numIndsIncluded]; probeNameToId = new HashMap<String, Integer>(); for (int i = 0; i < probeNr; i++) { probes[i] = tmpProbe.get(i); probeNameToId.put(probes[i], i); annotation[i] = tmpAnnotation.get(i); if (annotation[i] == null) { annotation[i] = "-"; } if (tmpChr.get(i) == null) { System.err.println("No chromosome annotation loaded for probe " + tmpProbe.get(i)); chr[i] = -1; chrStart[i] = -1; chrStop[i] = -1; } else { chr[i] = tmpChr.get(i); chrStart[i] = tmpChrStart.get(i); chrStop[i] = tmpChrEnd.get(i); } } for (int i = 0; i < numIndsIncluded; i++) { for (int p = 0; p < probeNr; p++) { matrix[p][i] = tmpRaw.get(p)[i]; } } tmpChrStart = null; tmpChrEnd = null; tmpChr = null; tmpProbe = null; tmpRaw = null; tmpAnnotation = null; if (pathwayDefinitions != null) { // do stuff. System.out.println("Now performing Pathway merger magic. *stars and unicorns*"); List<String> pathwayNames = pathwayDefinitions.getLeft(); List<List<String>> genesInPathways = pathwayDefinitions.getRight(); double[][] pathwayData = new double[pathwayNames.size()][this.individuals.length]; boolean[] usePathway = new boolean[pathwayNames.size()]; int nrPathwaysToUse = 0; for (int p = 0, len = pathwayNames.size(); p < len; p++) { List<String> ensGenesForPathway = genesInPathways.get(p); HashSet<String> hashGenesForPathway = new HashSet<String>(ensGenesForPathway); int nrProbesFound = 0; for (int probe = 0; probe < matrix.length; probe++) { String annotationForProbe = annotation[probe]; String[] annStrings = annotationForProbe.split(";"); boolean hasRightAnnotation = false; for (String s : annStrings) { if (hashGenesForPathway.contains(s)) { hasRightAnnotation = true; } } if (hasRightAnnotation) { // do stuff :-) :P for (int i = 0; i < individuals.length; i++) { pathwayData[p][i] += matrix[probe][i]; } nrProbesFound++; } } if (nrProbesFound > 1) { for (int i = 0; i < individuals.length; i++) { pathwayData[p][i] /= nrProbesFound; } } if (nrProbesFound >= 10) { usePathway[p] = true; nrPathwaysToUse++; } } System.out.println("Final number of pathways used in this dataset: " + nrPathwaysToUse); matrix = new double[nrPathwaysToUse][0]; probes = new String[nrPathwaysToUse]; probeNameToId = new HashMap<String, Integer>(); probeMean = new double[nrPathwaysToUse]; probeVariance = new double[nrPathwaysToUse]; probeOriginalMean = new double[nrPathwaysToUse]; probeOriginalVariance = new double[nrPathwaysToUse]; chr = new byte[nrPathwaysToUse]; chrStart = new int[nrPathwaysToUse]; chrStop = new int[nrPathwaysToUse]; int nrPathwaysUsed = 0; for (int p = 0, len = pathwayNames.size(); p < len; p++) { if (usePathway[p]) { matrix[nrPathwaysUsed] = pathwayData[p]; probes[nrPathwaysUsed] = pathwayNames.get(p); probeNameToId.put(probes[nrPathwaysUsed], nrPathwaysUsed); nrPathwaysUsed++; } } } calcMeanAndVariance(); for (int p = 0; p < matrix.length; p++) { for (int s = 0; s < matrix[p].length; s++) { matrix[p][s] -= probeMean[p]; } } calcMeanAndVariance(); System.out.println("Loaded " + matrix.length + " probes for " + individuals.length + " individuals"); return true; }
public final boolean load(String loc, String probeAnnotationLoc, String platform, boolean cistrans) throws IOException { if (!Gpio.exists(loc)) { throw new IOException("! Error loading expression data: " + loc + " does not exist"); } System.out.println("Loading expression data from: " + loc); TextFile in = new TextFile(loc, TextFile.R); // detect whether TriTyper dataset // load probeAnnotation otherwise int numProbes = 0; boolean trityperformat = false; int offset = 1; String[] elems = null; numProbes = in.countLines(); elems = in.readLineElemsReturnReference(TextFile.tab); // header line... // MultipleHits SequenceIdentity Chr ChrStart ChrEnd if (elems[0].trim().toLowerCase().equals("probe") && elems[3].trim().toLowerCase().equals("chr") && elems[4].trim().toLowerCase().equals("chrstart")) { System.out.println("! Expression data is still in the old, deprecated TriTyper format."); trityperformat = true; offset = 9; } else if (probeAnnotationLoc == null && !cistrans) { throw new IOException("ERROR: Probe annotation is not specified. Please specify probe annotation or provide expression data in TriTyper format!"); } // load the probe annotation, if any present HashMap<String, Byte> hashProbeChr = null; HashMap<String, Integer> hashProbeChrStart = null; HashMap<String, Integer> hashProbeChrStop = null; HashMap<String, String> hashAnnot = null; if (probeAnnotationLoc != null) { if (trityperformat) { System.out.println("! WARNING: overriding probe annotation from TriTyper file with probe annotation!"); trityperformat = false; offset = 9; } System.out.println("Loading probe annotation from: " + probeAnnotationLoc); hashProbeChr = new HashMap<String, Byte>(); hashProbeChrStart = new HashMap<String, Integer>(); hashProbeChrStop = new HashMap<String, Integer>(); hashAnnot = new HashMap<String, String>(); TextFile an = new TextFile(probeAnnotationLoc, TextFile.R); an.readLineElemsReturnReference(TextFile.tab); String[] anelems = an.readLineElemsReturnReference(TextFile.tab); boolean filterplatform = true; if (m_platform == null) { filterplatform = false; } int numAnnotLoaded = 0; while (anelems != null) { if (anelems.length >= 6 && (!filterplatform || (filterplatform && anelems[0].equals(m_platform)))) { String probe = new String(anelems[1].getBytes("UTF-8")); Byte bchr = ChrAnnotation.parseChr(anelems[3]); Integer ichrStart = -1; Integer ichrStop = -1; try { ichrStart = Integer.parseInt(anelems[4]); ichrStop = Integer.parseInt(anelems[5]); } catch (NumberFormatException e) { } String annot = new String(anelems[2].getBytes("UTF-8")); hashProbeChr.put(probe, bchr); hashProbeChrStart.put(probe, ichrStart); hashProbeChrStop.put(probe, ichrStop); hashAnnot.put(probe, annot); numAnnotLoaded++; } anelems = an.readLineElemsReturnReference(TextFile.tab); } an.close(); if (numAnnotLoaded == 0) { throw new IOException("Error: no probe annotation available for expression platform: " + platform); } else { System.out.println("Loaded annotation for " + numAnnotLoaded + " probes."); } } int numIndsIncluded = 0; HashMap<String, Integer> indToId = new HashMap<String, Integer>(); boolean[] includeCol = new boolean[elems.length]; for (int pos = offset; pos < elems.length; pos++) { if (includeIndividuals == null || includeIndividuals.contains(elems[pos])) { numIndsIncluded++; includeCol[pos] = true; } else { includeCol[pos] = false; } } individuals = new String[numIndsIncluded]; int indNo = 0; for (int pos = offset; pos < elems.length; pos++) { if (includeCol[pos]) { individuals[indNo] = new String(elems[pos].getBytes("UTF-8")); indToId.put(elems[pos], indNo); indNo++; } } individualNameToId = indToId; System.out.println("Found gene expression data for " + numIndsIncluded + " individuals"); ArrayList<Integer> tmpChrStart = new ArrayList<Integer>(); ArrayList<Integer> tmpChrEnd = new ArrayList<Integer>(); ArrayList<Byte> tmpChr = new ArrayList<Byte>(); ArrayList<String> tmpProbe = new ArrayList<String>(); ArrayList<float[]> tmpRaw = new ArrayList<float[]>(); ArrayList<String> tmpAnnotation = new ArrayList<String>(); annotationToProbeId = new HashMap<String, ArrayList<Integer>>(); int probeNr = 0; elems = in.readLineElemsReturnReference(TextFile.tab); if (!trityperformat) { if (hashProbeChr == null && !cistrans) { System.out.println("WARNING: no probe annotation available."); } } int probesIncluded = 0; int probesExcluded = 0; HashSet<Integer> probesWithMissingValues = new HashSet<Integer>(); while (elems != null) { boolean printreason = true; if (elems.length > 1) { String probe = new String(elems[0].getBytes("UTF-8")); String annotstr = null; Byte probeChr = null; Integer probeChrStart = null; Integer probeChrEnd = null; boolean includeprobe = true; String reason = ""; if (trityperformat && elems.length > 9) { // Probe MultipleHits SequenceIdentity Chr ChrStart ChrEnd Ensembl HUGO DIP Byte bchr = ChrAnnotation.parseChr(elems[3]); if (probesConfine == null || probesConfine.contains(probe)) { if (!confineToProbesThatMapToAnyChromosome || bchr >= 1) { if (confineToProbesMappingOnChromosome == null || confineToProbesMappingOnChromosome.equals((int) bchr)) { probeChr = bchr; probeChrStart = Integer.parseInt(elems[4]); probeChrEnd = Integer.parseInt(elems[5]); annotstr = new String(elems[7].getBytes("UTF-8")); includeprobe = true; } else { probesExcluded++; reason += "\tprobe does not map to chromosome:" + confineToProbesMappingOnChromosome + "\t" + bchr; includeprobe = false; } } else { probesExcluded++; reason += "\tprobe does not map to any chromosome:\t" + bchr; includeprobe = false; } } else { probesExcluded++; // reason += "\tprobe is not selected during confinement."; printreason = false; includeprobe = false; } } else if (!trityperformat) { if (hashProbeChr != null && !cistrans) { probeChr = hashProbeChr.get(probe); probeChrStart = hashProbeChrStart.get(probe); probeChrEnd = hashProbeChrStop.get(probe); annotstr = hashAnnot.get(probe); if (probeChr == null) { includeprobe = false; reason += "Probe annotation not loaded for probe:\t" + probe; } else if ((probesConfine == null || probesConfine.contains(probe)) && (!confineToProbesThatMapToAnyChromosome || probeChr >= 1) && (confineToProbesMappingOnChromosome != null && confineToProbesMappingOnChromosome.equals((int) probeChr))) { includeprobe = true; } } else if (!cistrans) { throw new IOException("ERROR: probe annotation not loaded?"); } else if (hashProbeChr != null && cistrans) { probeChr = hashProbeChr.get(probe); probeChrStart = hashProbeChrStart.get(probe); probeChrEnd = hashProbeChrStop.get(probe); annotstr = hashAnnot.get(probe); } else { if ((probesConfine == null || probesConfine.contains(probe))) { includeprobe = true; probeChr = -1; probeChrStart = -1; probeChrEnd = -1; annotstr = "-"; } else { includeprobe = false; printreason = false; } } } else { System.err.println("Error: data is in TriTyper format, but is probably wrongly formated (because the number of columns <10!)"); System.exit(-1); } if (!cistrans && includeprobe && probeChr == null && probeChrStart == null && probeChrEnd == null && !(probesConfine != null && !probesConfine.contains(probe))) { reason += "WARNING: probe\t" + probe + "\thas no annotation at all! Will exclude this probe from further use."; includeprobe = false; } if (includeprobe) { probesIncluded++; tmpProbe.add(probe); if (probeChr == null) { probeChr = -1; } tmpChr.add(probeChr); if (probeChrStart == null) { probeChrStart = -1; } tmpChrStart.add(probeChrStart); if (probeChrEnd == null) { probeChrEnd = -1; } tmpChrEnd.add(probeChrEnd); if (annotstr != null && annotstr.length() > 0) { ArrayList<Integer> annotationToProbe = annotationToProbeId.get(new String(elems[7].getBytes("UTF-8"))); if (annotationToProbe == null) { annotationToProbe = new ArrayList<Integer>(); } annotationToProbe.add(probeNr); annotationToProbeId.put(probe, annotationToProbe); } if (annotstr == null) { annotstr = "-"; } tmpAnnotation.add(annotstr); int samplePos = 0; float[] tmpDt = new float[numIndsIncluded]; for (int pos = offset; pos < elems.length; pos++) { if (includeCol[pos]) { try { tmpDt[samplePos] = Float.parseFloat(elems[pos]); } catch (NumberFormatException e) { System.err.println("WARNING: missing value for column:\t" + pos + "\tprobe:\t" + probe); tmpDt[samplePos] = Float.NaN; probesWithMissingValues.add(probeNr); } samplePos++; } } tmpRaw.add(tmpDt); probeNr++; if (probeNr % 10000 == 0) { System.out.println(probeNr + " probes parsed."); } } else if (printreason) { System.out.println("Probe\t" + probe + "\texcluded. Reason:\t" + reason); } } elems = in.readLineElemsReturnReference(TextFile.tab); } in.close(); if (probesWithMissingValues.size() > 0) { System.err.println("WARNING: " + probesWithMissingValues.size() + " probes with missing values detected. Will replace missing values with average probe value."); ArrayList<float[]> newRaw = new ArrayList<float[]>(); for (int i = 0; i < tmpRaw.size(); i++) { if (probesWithMissingValues.contains(i)) { float[] data = tmpRaw.get(i); double sum = 0; int nrNotMissing = 0; for (int j = 0; j < data.length; j++) { if (!Float.isNaN(data[j])) { sum += data[j]; nrNotMissing++; } } sum /= nrNotMissing; for (int j = 0; j < data.length; j++) { if (Float.isNaN(data[j])) { data[j] = (float) sum; } } } else { newRaw.add(tmpRaw.get(i)); } } } System.out.println("Probes selected:\t" + probesIncluded); System.out.println("Probes not selected:\t" + probesExcluded); if (probeNr == 0) { System.err.println("ERROR: No gene expression data loaded for (no probes matching criteria): " + loc); return false; } this.chr = new byte[probeNr]; this.annotation = new String[probeNr]; this.chrStart = new int[probeNr]; this.chrStop = new int[probeNr]; this.probes = new String[probeNr]; this.matrix = new double[probeNr][numIndsIncluded]; probeNameToId = new HashMap<String, Integer>(); for (int i = 0; i < probeNr; i++) { probes[i] = tmpProbe.get(i); probeNameToId.put(probes[i], i); annotation[i] = tmpAnnotation.get(i); if (annotation[i] == null) { annotation[i] = "-"; } if (tmpChr.get(i) == null) { System.err.println("No chromosome annotation loaded for probe " + tmpProbe.get(i)); chr[i] = -1; chrStart[i] = -1; chrStop[i] = -1; } else { chr[i] = tmpChr.get(i); chrStart[i] = tmpChrStart.get(i); chrStop[i] = tmpChrEnd.get(i); } } for (int i = 0; i < numIndsIncluded; i++) { for (int p = 0; p < probeNr; p++) { matrix[p][i] = tmpRaw.get(p)[i]; } } tmpChrStart = null; tmpChrEnd = null; tmpChr = null; tmpProbe = null; tmpRaw = null; tmpAnnotation = null; if (pathwayDefinitions != null) { // do stuff. System.out.println("Now performing Pathway merger magic. *stars and unicorns*"); List<String> pathwayNames = pathwayDefinitions.getLeft(); List<List<String>> genesInPathways = pathwayDefinitions.getRight(); double[][] pathwayData = new double[pathwayNames.size()][this.individuals.length]; boolean[] usePathway = new boolean[pathwayNames.size()]; int nrPathwaysToUse = 0; for (int p = 0, len = pathwayNames.size(); p < len; p++) { List<String> ensGenesForPathway = genesInPathways.get(p); HashSet<String> hashGenesForPathway = new HashSet<String>(ensGenesForPathway); int nrProbesFound = 0; for (int probe = 0; probe < matrix.length; probe++) { String annotationForProbe = annotation[probe]; String[] annStrings = annotationForProbe.split(";"); boolean hasRightAnnotation = false; for (String s : annStrings) { if (hashGenesForPathway.contains(s)) { hasRightAnnotation = true; } } if (hasRightAnnotation) { // do stuff :-) :P for (int i = 0; i < individuals.length; i++) { pathwayData[p][i] += matrix[probe][i]; } nrProbesFound++; } } if (nrProbesFound > 1) { for (int i = 0; i < individuals.length; i++) { pathwayData[p][i] /= nrProbesFound; } } if (nrProbesFound >= 10) { usePathway[p] = true; nrPathwaysToUse++; } } System.out.println("Final number of pathways used in this dataset: " + nrPathwaysToUse); matrix = new double[nrPathwaysToUse][0]; probes = new String[nrPathwaysToUse]; probeNameToId = new HashMap<String, Integer>(); probeMean = new double[nrPathwaysToUse]; probeVariance = new double[nrPathwaysToUse]; probeOriginalMean = new double[nrPathwaysToUse]; probeOriginalVariance = new double[nrPathwaysToUse]; chr = new byte[nrPathwaysToUse]; chrStart = new int[nrPathwaysToUse]; chrStop = new int[nrPathwaysToUse]; int nrPathwaysUsed = 0; for (int p = 0, len = pathwayNames.size(); p < len; p++) { if (usePathway[p]) { matrix[nrPathwaysUsed] = pathwayData[p]; probes[nrPathwaysUsed] = pathwayNames.get(p); probeNameToId.put(probes[nrPathwaysUsed], nrPathwaysUsed); nrPathwaysUsed++; } } } calcMeanAndVariance(); for (int p = 0; p < matrix.length; p++) { for (int s = 0; s < matrix[p].length; s++) { matrix[p][s] -= probeMean[p]; } } calcMeanAndVariance(); System.out.println("Loaded " + matrix.length + " probes for " + individuals.length + " individuals"); return true; }
diff --git a/src/calliope/handler/post/AeseImportHandler.java b/src/calliope/handler/post/AeseImportHandler.java index 21aa3ab..4d931eb 100755 --- a/src/calliope/handler/post/AeseImportHandler.java +++ b/src/calliope/handler/post/AeseImportHandler.java @@ -1,278 +1,278 @@ /* This file is part of calliope. * * calliope is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * calliope is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with calliope. If not, see <http://www.gnu.org/licenses/>. */ package calliope.handler.post; import calliope.Connector; import calliope.constants.*; import calliope.ByteHolder; import calliope.exception.AeseException; import calliope.handler.post.importer.*; import calliope.importer.Archive; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Superclass of the various concrete import classes * @author desmond */ public abstract class AeseImportHandler extends AesePostHandler { StringBuilder log; DocID docID; String style; String filterName; String database; String splitterName; String stripperName; /** uploaded xslt file contents */ String xslt; boolean demo; /** text filter config */ String textName; HashMap<String,String> nameMap; HashMap<String,String> jsonKeys; ArrayList<File> files; ArrayList<ImageFile> images; public AeseImportHandler() { nameMap = new HashMap<String,String>(); jsonKeys = new HashMap<String,String>(); filterName = Filters.EMPTY; stripperName = "default"; splitterName = "default"; textName = "default"; files = new ArrayList<File>(); images = new ArrayList<ImageFile>(); log = new StringBuilder(); } /** * Add the archive to the database * @param archive the archive * @param db cortex or corcode * @param suffix the suffix to append * @throws AeseException */ protected void addToDBase( Archive archive, String db, String suffix ) throws AeseException { // now get the json docs and add them at the right docid if ( !archive.isEmpty() ) { String path; if ( suffix.length()>0 ) path = docID.get()+"/"+suffix; else path = docID.get(); if ( db.equals("corcode") ) path += "/default"; Connector.getConnection().putToDb( db, path, archive.toMVD(db) ); log.append( archive.getLog() ); } else log.append("No "+db+" created (empty)\n"); } /** * Parse the import params from the request * @param request the http request */ void parseImportParams( HttpServletRequest request ) throws AeseException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest( request ); for ( int i=0;i<items.size();i++ ) { FileItem item = (FileItem) items.get( i ); if ( item.isFormField() ) { String fieldName = item.getFieldName(); if ( fieldName != null ) { String contents = item.getString(); if ( fieldName.equals(Params.DOC_ID) ) { if ( contents.startsWith("/") ) { contents = contents.substring(1); int pos = contents.indexOf("/"); if ( pos != -1 ) { database = contents.substring(0,pos); contents = contents.substring(pos+1); } } docID = new DocID( contents ); } else if ( fieldName.startsWith(Params.SHORT_VERSION) ) nameMap.put( fieldName.substring( Params.SHORT_VERSION.length()), item.getString()); else if ( fieldName.equals(Params.STYLE) ) style = contents; else if ( fieldName.equals(Params.DEMO) ) { if ( contents!=null&&contents.equals("brillig") ) demo = false; else demo = true; } else if ( fieldName.equals(Params.FILTER) ) filterName = contents.toLowerCase(); else if ( fieldName.equals(Params.SPLITTER) ) splitterName = contents; else if ( fieldName.equals(Params.STRIPPER) ) stripperName = contents; else if ( fieldName.equals(Params.TEXT) ) textName = contents.toLowerCase(); else if ( fieldName.equals(Params.XSLT) ) xslt = getConfig(Config.xslt,contents); else jsonKeys.put( fieldName, contents ); } } else if ( item.getName().length()>0 ) { try { // assuming that the contents are text //item.getName retrieves the ORIGINAL file name String type = item.getContentType(); - if ( type.startsWith("image/") ) + if ( type != null && type.startsWith("image/") ) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while ( is.available()>0 ) { byte[] b = new byte[is.available()]; is.read( b ); bh.append( b ); } ImageFile iFile = new ImageFile( item.getName(), item.getContentType(), bh.getData() ); images.add( iFile ); } else { File f = new File( item.getName(), item.getString("UTF-8") ); files.add( f ); } } catch ( Exception e ) { throw new AeseException( e ); } } } } catch ( Exception e ) { throw new AeseException( e ); } } /** * Wrap the log in some HTML * @return the wrapped log */ String wrapLog() { StringBuilder sb = new StringBuilder(); sb.append("<html><body>"); sb.append("<h3>LOG</h3>"); sb.append("<p class=\"docid\"> DocID: "); sb.append( docID.get() ); sb.append( "</p><p class=\"log\">" ); sb.append( log.toString().replace("\n","<br>") ); sb.append("</p>"); sb.append("</body></html>"); return sb.toString(); } /** * Fetch the specified config from the database. If not there, check * for default configs progressively higher up. * @param kind the config kind: text, xslt or xml * @param path the path to the config * @return the loaded config document * @throws AeseException */ String getConfig( Config kind, String path ) //throws AeseException { try { String doc = null; String configDocId = kind.toString()+"/"+path; while ( doc == null ) { doc = Connector.getConnection().getFromDb( Database.CONFIG, configDocId.toLowerCase() ); if ( doc == null ) { String[] parts = configDocId.split("/"); if ( parts.length == 1 ) throw new AeseException("config not found: " +configDocId); else { String oldDocId = configDocId; StringBuilder sb = new StringBuilder(); int N=(parts[parts.length-1].equals(Formats.DEFAULT))?2:1; // recurse up the path for ( int i=0;i<parts.length-N;i++ ) { sb.append( parts[i] ); sb.append("/"); } if ( sb.length()==0 ) { sb.append(kind); sb.append("/"); } configDocId = sb.toString()+Formats.DEFAULT; if ( oldDocId.equals(configDocId) ) throw new AeseException("config "+oldDocId +" not found"); } } } return doc; } catch ( Exception e ) { // AeseException he; // if ( e instanceof AeseException ) // he = (AeseException) e ; // else // he = new AeseException( e ); // throw he; // just return empty config return "{}"; } } }
true
true
void parseImportParams( HttpServletRequest request ) throws AeseException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest( request ); for ( int i=0;i<items.size();i++ ) { FileItem item = (FileItem) items.get( i ); if ( item.isFormField() ) { String fieldName = item.getFieldName(); if ( fieldName != null ) { String contents = item.getString(); if ( fieldName.equals(Params.DOC_ID) ) { if ( contents.startsWith("/") ) { contents = contents.substring(1); int pos = contents.indexOf("/"); if ( pos != -1 ) { database = contents.substring(0,pos); contents = contents.substring(pos+1); } } docID = new DocID( contents ); } else if ( fieldName.startsWith(Params.SHORT_VERSION) ) nameMap.put( fieldName.substring( Params.SHORT_VERSION.length()), item.getString()); else if ( fieldName.equals(Params.STYLE) ) style = contents; else if ( fieldName.equals(Params.DEMO) ) { if ( contents!=null&&contents.equals("brillig") ) demo = false; else demo = true; } else if ( fieldName.equals(Params.FILTER) ) filterName = contents.toLowerCase(); else if ( fieldName.equals(Params.SPLITTER) ) splitterName = contents; else if ( fieldName.equals(Params.STRIPPER) ) stripperName = contents; else if ( fieldName.equals(Params.TEXT) ) textName = contents.toLowerCase(); else if ( fieldName.equals(Params.XSLT) ) xslt = getConfig(Config.xslt,contents); else jsonKeys.put( fieldName, contents ); } } else if ( item.getName().length()>0 ) { try { // assuming that the contents are text //item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if ( type.startsWith("image/") ) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while ( is.available()>0 ) { byte[] b = new byte[is.available()]; is.read( b ); bh.append( b ); } ImageFile iFile = new ImageFile( item.getName(), item.getContentType(), bh.getData() ); images.add( iFile ); } else { File f = new File( item.getName(), item.getString("UTF-8") ); files.add( f ); } } catch ( Exception e ) { throw new AeseException( e ); } } } } catch ( Exception e ) { throw new AeseException( e ); } }
void parseImportParams( HttpServletRequest request ) throws AeseException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest( request ); for ( int i=0;i<items.size();i++ ) { FileItem item = (FileItem) items.get( i ); if ( item.isFormField() ) { String fieldName = item.getFieldName(); if ( fieldName != null ) { String contents = item.getString(); if ( fieldName.equals(Params.DOC_ID) ) { if ( contents.startsWith("/") ) { contents = contents.substring(1); int pos = contents.indexOf("/"); if ( pos != -1 ) { database = contents.substring(0,pos); contents = contents.substring(pos+1); } } docID = new DocID( contents ); } else if ( fieldName.startsWith(Params.SHORT_VERSION) ) nameMap.put( fieldName.substring( Params.SHORT_VERSION.length()), item.getString()); else if ( fieldName.equals(Params.STYLE) ) style = contents; else if ( fieldName.equals(Params.DEMO) ) { if ( contents!=null&&contents.equals("brillig") ) demo = false; else demo = true; } else if ( fieldName.equals(Params.FILTER) ) filterName = contents.toLowerCase(); else if ( fieldName.equals(Params.SPLITTER) ) splitterName = contents; else if ( fieldName.equals(Params.STRIPPER) ) stripperName = contents; else if ( fieldName.equals(Params.TEXT) ) textName = contents.toLowerCase(); else if ( fieldName.equals(Params.XSLT) ) xslt = getConfig(Config.xslt,contents); else jsonKeys.put( fieldName, contents ); } } else if ( item.getName().length()>0 ) { try { // assuming that the contents are text //item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if ( type != null && type.startsWith("image/") ) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while ( is.available()>0 ) { byte[] b = new byte[is.available()]; is.read( b ); bh.append( b ); } ImageFile iFile = new ImageFile( item.getName(), item.getContentType(), bh.getData() ); images.add( iFile ); } else { File f = new File( item.getName(), item.getString("UTF-8") ); files.add( f ); } } catch ( Exception e ) { throw new AeseException( e ); } } } } catch ( Exception e ) { throw new AeseException( e ); } }
diff --git a/src/net/vexelon/myglob/actions/BaseAction.java b/src/net/vexelon/myglob/actions/BaseAction.java index dd27b4a..db1e207 100644 --- a/src/net/vexelon/myglob/actions/BaseAction.java +++ b/src/net/vexelon/myglob/actions/BaseAction.java @@ -1,62 +1,59 @@ package net.vexelon.myglob.actions; import net.vexelon.mobileops.GLBClient; import net.vexelon.mobileops.HttpClientException; import net.vexelon.mobileops.IClient; import net.vexelon.mobileops.InvalidCredentialsException; import net.vexelon.mobileops.SecureCodeRequiredException; import net.vexelon.myglob.R; import net.vexelon.myglob.users.User; import net.vexelon.myglob.users.UsersManager; import android.content.Context; public abstract class BaseAction implements Action { protected Context _context; protected User _user; public BaseAction(Context context, User user) { this._context = context; this._user = user; } protected IClient newClient() throws ActionExecuteException { IClient client; try { client = new GLBClient(_user.getPhoneNumber(), UsersManager.getInstance().getUserPassword(_user)); } catch (Exception e) { throw new ActionExecuteException(R.string.dlg_error_msg_decrypt_failed, e); } return client; } protected void clientLogin(IClient client) throws ActionExecuteException { try { client.login(); } catch (InvalidCredentialsException e) { throw new ActionExecuteException(R.string.dlg_error_msg_invalid_credentials, R.string.dlg_error_msg_title); } catch (SecureCodeRequiredException e) { throw new ActionExecuteException(R.string.dlg_error_msg_securecode, R.string.dlg_error_msg_title); } catch(HttpClientException e) { throw new ActionExecuteException(e); - } finally { - if (client != null) - client.close(); } } protected void clientLogout(IClient client) throws ActionExecuteException { try { client.logout(); } catch(HttpClientException e) { throw new ActionExecuteException(e); } finally { if (client != null) client.close(); } } }
true
true
protected void clientLogin(IClient client) throws ActionExecuteException { try { client.login(); } catch (InvalidCredentialsException e) { throw new ActionExecuteException(R.string.dlg_error_msg_invalid_credentials, R.string.dlg_error_msg_title); } catch (SecureCodeRequiredException e) { throw new ActionExecuteException(R.string.dlg_error_msg_securecode, R.string.dlg_error_msg_title); } catch(HttpClientException e) { throw new ActionExecuteException(e); } finally { if (client != null) client.close(); } }
protected void clientLogin(IClient client) throws ActionExecuteException { try { client.login(); } catch (InvalidCredentialsException e) { throw new ActionExecuteException(R.string.dlg_error_msg_invalid_credentials, R.string.dlg_error_msg_title); } catch (SecureCodeRequiredException e) { throw new ActionExecuteException(R.string.dlg_error_msg_securecode, R.string.dlg_error_msg_title); } catch(HttpClientException e) { throw new ActionExecuteException(e); } }
diff --git a/src/main/java/net/serubin/serubans/SeruBans.java b/src/main/java/net/serubin/serubans/SeruBans.java index 58ccdf9..e7614d1 100644 --- a/src/main/java/net/serubin/serubans/SeruBans.java +++ b/src/main/java/net/serubin/serubans/SeruBans.java @@ -1,252 +1,252 @@ package net.serubin.serubans; import java.util.logging.Logger; import net.serubin.serubans.commands.BanCommand; import net.serubin.serubans.commands.CheckBanCommand; import net.serubin.serubans.commands.DebugCommand; import net.serubin.serubans.commands.KickCommand; import net.serubin.serubans.commands.SearchCommand; import net.serubin.serubans.commands.TempBanCommand; import net.serubin.serubans.commands.UnbanCommand; import net.serubin.serubans.commands.UpdateCommand; import net.serubin.serubans.commands.WarnCommand; import net.serubin.serubans.search.DisplayManager; import net.serubin.serubans.search.SearchMethods; import net.serubin.serubans.util.ArgProcessing; import net.serubin.serubans.util.CheckPlayer; import net.serubin.serubans.util.MySqlDatabase; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class SeruBans extends JavaPlugin { /* * Base class of SeruBans * * By Serubin323, Solomon Rubin */ public SeruBans plugin; public Logger log = Logger.getLogger("Minecraft"); private static boolean debug; private static String name; private static String version; public static SeruBans self = null; /* * Class Short Cuts */ MySqlDatabase db; DisplayManager dm = null; /* * defines config variables */ public static String BanMessage; public static String GlobalBanMessage; public static String TempBanMessage; public static String GlobalTempBanMessage; public static String KickMessage; public static String GlobalKickMessage; public static String WarnMessage; public static String WarnPlayerMessage; public static String UnBanMessage; /* * sql variables */ public static String username; public static String password; public static String database; public static String host; /* * Ban types */ public static final int BAN = 1; public static final int TEMPBAN = 2; public static final int KICK = 3; public static final int WARN = 4; public static final int UNBAN = 11; public static final int UNTEMPBAN = 12; /* * perms */ public static final String BANPERM = "serubans.ban"; public static final String TEMPBANPERM = "serubans.tempban"; public static final String KICKPERM = "serubans.kick"; public static final String WARNPERM = "serubans.warn"; public static final String UNBANPERM = "serubans.unban"; public static final String CHECKBANPERM = "serubans.checkban"; public static final String UPDATEPERM = "serubans.update"; public static final String SEARCHPERM = "serubans.search"; public static final String DEBUGPERM = "serubans.debug"; public static final String BROADCASTPERM = "serubans.broadcast"; /* * other, final */ public static final int SHOW = 0; public static final int HIDE = 1; int taskId; int taskId_maintain; public void onDisable() { reloadConfig(); saveConfig(); getServer().getScheduler().cancelTask(taskId); log.info(name + " has been disabled"); } public void onEnable() { version = this.getDescription().getVersion(); name = this.getDescription().getName(); self = this; log.info(name + " version " + version + " has started..."); PluginManager pm = getServer().getPluginManager(); getConfig().options().copyDefaults(true); saveConfig(); /* * Ban messages */ BanMessage = getConfig().getString("SeruBans.messages.ban.BanMessage"); GlobalBanMessage = getConfig().getString( "SeruBans.messages.ban.GlobalBanMessage"); TempBanMessage = getConfig().getString( "SeruBans.messages.tempban.TempBanMessage"); GlobalTempBanMessage = getConfig().getString( "SeruBans.messages.tempban.GlobalTempBanMessage"); /* * kick messages */ KickMessage = getConfig().getString( "SeruBans.messages.kick.KickMessage"); GlobalKickMessage = getConfig().getString( "SeruBans.messages.kick.GlobalKickMessage"); /* * warn message */ WarnMessage = getConfig().getString( "SeruBans.messages.warn.WarnMessage"); WarnPlayerMessage = getConfig().getString( "SeruBans.messages.warn.WarnPlayerMessage"); UnBanMessage = getConfig().getString("SeruBans.messages.UnBanMessage"); /* * MySql */ host = getConfig().getString("SeruBans.database.host"); username = getConfig().getString("SeruBans.database.username"); password = getConfig().getString("SeruBans.database.password"); database = getConfig().getString("SeruBans.database.database"); debug = getConfig().getBoolean("SeruBans.debug"); /* * Add Classes */ BanCommand Ban = new BanCommand(BanMessage, GlobalBanMessage, name, this); TempBanCommand TempBan = new TempBanCommand(TempBanMessage, GlobalTempBanMessage, name, this); KickCommand Kick = new KickCommand(KickMessage, GlobalKickMessage, name, this); WarnCommand Warn = new WarnCommand(WarnMessage, WarnPlayerMessage, name, this); UnbanCommand Unban = new UnbanCommand(this); MySqlDatabase sqldb = new MySqlDatabase(host, username, password, database, this); CheckPlayer CheckPlayer = new CheckPlayer(); DebugCommand DebugC = new DebugCommand(this); CheckBanCommand CheckBan = new CheckBanCommand(this); UnTempbanThread UnTempanThread = new UnTempbanThread(this); SearchCommand Search = new SearchCommand(this); UpdateCommand Update = new UpdateCommand(this); /* * init commands */ getCommand("ban").setExecutor(Ban); getCommand("tempban").setExecutor(TempBan); getCommand("kick").setExecutor(Kick); getCommand("warn").setExecutor(Warn); getCommand("unban").setExecutor(Unban); getCommand("checkban").setExecutor(CheckBan); getCommand("bsearch").setExecutor(Search); - getCommand("update").setExecutor(Update); + getCommand("bupdate").setExecutor(Update); getCommand("serubans").setExecutor(DebugC); MySqlDatabase.startSQL(); /* * Create listener */ getServer().getPluginManager().registerEvents( new SeruBansPlayerListener(this, BanMessage, TempBanMessage), this); /* * Create Thread */ taskId = getServer().getScheduler().scheduleAsyncRepeatingTask(this, UnTempanThread, 1200, 1200); taskId_maintain = getServer().getScheduler().scheduleAsyncRepeatingTask(this, sqldb, 5800, 5800); } public static void printInfo(String line) { self.log.info("[SeruBans] " + line); } public void printDebug(String line) { if (debug) { log.info("[SeruBans] DEBUG: " + line); } } public static void printServer(String line) { Player[] players = Bukkit.getOnlinePlayers(); for (Player player : players) { if (player.hasPermission(BROADCASTPERM) || player.isOp()) { player.sendMessage(ArgProcessing.GetColor(line)); } } } public static void printError(String line) { self.log.severe("[SeruBans] " + line); } public static void printWarning(String line) { self.log.warning("[SeruBans] " + line); } /* * API GETTER / SETTER */ }
true
true
public void onEnable() { version = this.getDescription().getVersion(); name = this.getDescription().getName(); self = this; log.info(name + " version " + version + " has started..."); PluginManager pm = getServer().getPluginManager(); getConfig().options().copyDefaults(true); saveConfig(); /* * Ban messages */ BanMessage = getConfig().getString("SeruBans.messages.ban.BanMessage"); GlobalBanMessage = getConfig().getString( "SeruBans.messages.ban.GlobalBanMessage"); TempBanMessage = getConfig().getString( "SeruBans.messages.tempban.TempBanMessage"); GlobalTempBanMessage = getConfig().getString( "SeruBans.messages.tempban.GlobalTempBanMessage"); /* * kick messages */ KickMessage = getConfig().getString( "SeruBans.messages.kick.KickMessage"); GlobalKickMessage = getConfig().getString( "SeruBans.messages.kick.GlobalKickMessage"); /* * warn message */ WarnMessage = getConfig().getString( "SeruBans.messages.warn.WarnMessage"); WarnPlayerMessage = getConfig().getString( "SeruBans.messages.warn.WarnPlayerMessage"); UnBanMessage = getConfig().getString("SeruBans.messages.UnBanMessage"); /* * MySql */ host = getConfig().getString("SeruBans.database.host"); username = getConfig().getString("SeruBans.database.username"); password = getConfig().getString("SeruBans.database.password"); database = getConfig().getString("SeruBans.database.database"); debug = getConfig().getBoolean("SeruBans.debug"); /* * Add Classes */ BanCommand Ban = new BanCommand(BanMessage, GlobalBanMessage, name, this); TempBanCommand TempBan = new TempBanCommand(TempBanMessage, GlobalTempBanMessage, name, this); KickCommand Kick = new KickCommand(KickMessage, GlobalKickMessage, name, this); WarnCommand Warn = new WarnCommand(WarnMessage, WarnPlayerMessage, name, this); UnbanCommand Unban = new UnbanCommand(this); MySqlDatabase sqldb = new MySqlDatabase(host, username, password, database, this); CheckPlayer CheckPlayer = new CheckPlayer(); DebugCommand DebugC = new DebugCommand(this); CheckBanCommand CheckBan = new CheckBanCommand(this); UnTempbanThread UnTempanThread = new UnTempbanThread(this); SearchCommand Search = new SearchCommand(this); UpdateCommand Update = new UpdateCommand(this); /* * init commands */ getCommand("ban").setExecutor(Ban); getCommand("tempban").setExecutor(TempBan); getCommand("kick").setExecutor(Kick); getCommand("warn").setExecutor(Warn); getCommand("unban").setExecutor(Unban); getCommand("checkban").setExecutor(CheckBan); getCommand("bsearch").setExecutor(Search); getCommand("update").setExecutor(Update); getCommand("serubans").setExecutor(DebugC); MySqlDatabase.startSQL(); /* * Create listener */ getServer().getPluginManager().registerEvents( new SeruBansPlayerListener(this, BanMessage, TempBanMessage), this); /* * Create Thread */ taskId = getServer().getScheduler().scheduleAsyncRepeatingTask(this, UnTempanThread, 1200, 1200); taskId_maintain = getServer().getScheduler().scheduleAsyncRepeatingTask(this, sqldb, 5800, 5800); }
public void onEnable() { version = this.getDescription().getVersion(); name = this.getDescription().getName(); self = this; log.info(name + " version " + version + " has started..."); PluginManager pm = getServer().getPluginManager(); getConfig().options().copyDefaults(true); saveConfig(); /* * Ban messages */ BanMessage = getConfig().getString("SeruBans.messages.ban.BanMessage"); GlobalBanMessage = getConfig().getString( "SeruBans.messages.ban.GlobalBanMessage"); TempBanMessage = getConfig().getString( "SeruBans.messages.tempban.TempBanMessage"); GlobalTempBanMessage = getConfig().getString( "SeruBans.messages.tempban.GlobalTempBanMessage"); /* * kick messages */ KickMessage = getConfig().getString( "SeruBans.messages.kick.KickMessage"); GlobalKickMessage = getConfig().getString( "SeruBans.messages.kick.GlobalKickMessage"); /* * warn message */ WarnMessage = getConfig().getString( "SeruBans.messages.warn.WarnMessage"); WarnPlayerMessage = getConfig().getString( "SeruBans.messages.warn.WarnPlayerMessage"); UnBanMessage = getConfig().getString("SeruBans.messages.UnBanMessage"); /* * MySql */ host = getConfig().getString("SeruBans.database.host"); username = getConfig().getString("SeruBans.database.username"); password = getConfig().getString("SeruBans.database.password"); database = getConfig().getString("SeruBans.database.database"); debug = getConfig().getBoolean("SeruBans.debug"); /* * Add Classes */ BanCommand Ban = new BanCommand(BanMessage, GlobalBanMessage, name, this); TempBanCommand TempBan = new TempBanCommand(TempBanMessage, GlobalTempBanMessage, name, this); KickCommand Kick = new KickCommand(KickMessage, GlobalKickMessage, name, this); WarnCommand Warn = new WarnCommand(WarnMessage, WarnPlayerMessage, name, this); UnbanCommand Unban = new UnbanCommand(this); MySqlDatabase sqldb = new MySqlDatabase(host, username, password, database, this); CheckPlayer CheckPlayer = new CheckPlayer(); DebugCommand DebugC = new DebugCommand(this); CheckBanCommand CheckBan = new CheckBanCommand(this); UnTempbanThread UnTempanThread = new UnTempbanThread(this); SearchCommand Search = new SearchCommand(this); UpdateCommand Update = new UpdateCommand(this); /* * init commands */ getCommand("ban").setExecutor(Ban); getCommand("tempban").setExecutor(TempBan); getCommand("kick").setExecutor(Kick); getCommand("warn").setExecutor(Warn); getCommand("unban").setExecutor(Unban); getCommand("checkban").setExecutor(CheckBan); getCommand("bsearch").setExecutor(Search); getCommand("bupdate").setExecutor(Update); getCommand("serubans").setExecutor(DebugC); MySqlDatabase.startSQL(); /* * Create listener */ getServer().getPluginManager().registerEvents( new SeruBansPlayerListener(this, BanMessage, TempBanMessage), this); /* * Create Thread */ taskId = getServer().getScheduler().scheduleAsyncRepeatingTask(this, UnTempanThread, 1200, 1200); taskId_maintain = getServer().getScheduler().scheduleAsyncRepeatingTask(this, sqldb, 5800, 5800); }
diff --git a/qcadoo-plugin/src/main/java/com/qcadoo/plugin/internal/descriptorresolver/DefaultPluginDescriptorResolver.java b/qcadoo-plugin/src/main/java/com/qcadoo/plugin/internal/descriptorresolver/DefaultPluginDescriptorResolver.java index 10dfde877..9b78693b8 100644 --- a/qcadoo-plugin/src/main/java/com/qcadoo/plugin/internal/descriptorresolver/DefaultPluginDescriptorResolver.java +++ b/qcadoo-plugin/src/main/java/com/qcadoo/plugin/internal/descriptorresolver/DefaultPluginDescriptorResolver.java @@ -1,144 +1,144 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo Framework * Version: 1.2.0-SNAPSHOT * * This file is part of Qcadoo. * * Qcadoo is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.plugin.internal.descriptorresolver; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.stereotype.Service; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; import com.qcadoo.plugin.internal.JarEntryResource; import com.qcadoo.plugin.internal.PluginException; import com.qcadoo.plugin.internal.api.PluginDescriptorResolver; @Service public class DefaultPluginDescriptorResolver implements PluginDescriptorResolver { private static final Logger LOG = LoggerFactory.getLogger(DefaultPluginDescriptorResolver.class); private final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); @Value("#{plugin.descriptors}") private String descriptor; @Value("#{plugin.pluginsTmpPath}") private String pluginsTmpPath; private final PathMatcher matcher = new AntPathMatcher(); @Override public Resource[] getDescriptors() { try { Resource[] descriptors = resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + descriptor); HashSet<Resource> uniqueDescriptors = new HashSet<Resource>(Arrays.asList(descriptors)); return uniqueDescriptors.toArray(new Resource[uniqueDescriptors.size()]); } catch (IOException e) { throw new IllegalStateException("Failed to find classpath resources for " + ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + descriptor, e); } } @Override public JarEntryResource[] getTemporaryDescriptors() { if (pluginsTmpPath == null || pluginsTmpPath.trim().isEmpty()) { return new JarEntryResource[0]; } File pluginsTmpFile = new File(pluginsTmpPath); if (!pluginsTmpFile.exists()) { LOG.warn("Plugins temporary directory does not exist: " + pluginsTmpPath); return new JarEntryResource[0]; } try { FilenameFilter jarsFilter = new WildcardFileFilter("*.jar"); if (!pluginsTmpFile.exists()) { throw new IOException(); } File[] pluginJars = pluginsTmpFile.listFiles(jarsFilter); JarEntryResource[] pluginDescriptors = new JarEntryResource[pluginJars.length]; for (int i = 0; i < pluginJars.length; ++i) { File jarRes = pluginJars[i]; JarEntryResource descriptorResource = getDescriptor(jarRes); pluginDescriptors[i] = descriptorResource; } return pluginDescriptors; } catch (IOException e) { throw new IllegalStateException("Failed to reading plugins from " + pluginsTmpPath, e); } } @Override public JarEntryResource getDescriptor(final File file) { JarFile jarFile = null; try { jarFile = new JarFile(file); JarEntry descriptorEntry = null; Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (matcher.match(descriptor, jarEntry.getName())) { descriptorEntry = jarEntry; break; } } if (descriptorEntry == null) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath()); } return new JarEntryResource(file, jarFile.getInputStream(descriptorEntry)); } catch (IOException e) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); } finally { if (jarFile != null) { - try { - jarFile.close(); - } catch (IOException e) { - throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); - } + // try { + // jarFile.close(); + // } catch (IOException e) { + // throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); + // } } } } public void setDescriptor(final String descriptor) { this.descriptor = descriptor; } }
true
true
public JarEntryResource getDescriptor(final File file) { JarFile jarFile = null; try { jarFile = new JarFile(file); JarEntry descriptorEntry = null; Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (matcher.match(descriptor, jarEntry.getName())) { descriptorEntry = jarEntry; break; } } if (descriptorEntry == null) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath()); } return new JarEntryResource(file, jarFile.getInputStream(descriptorEntry)); } catch (IOException e) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); } } } }
public JarEntryResource getDescriptor(final File file) { JarFile jarFile = null; try { jarFile = new JarFile(file); JarEntry descriptorEntry = null; Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (matcher.match(descriptor, jarEntry.getName())) { descriptorEntry = jarEntry; break; } } if (descriptorEntry == null) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath()); } return new JarEntryResource(file, jarFile.getInputStream(descriptorEntry)); } catch (IOException e) { throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); } finally { if (jarFile != null) { // try { // jarFile.close(); // } catch (IOException e) { // throw new PluginException("Plugin descriptor " + descriptor + " not found in " + file.getAbsolutePath(), e); // } } } }
diff --git a/src/net/runal/jtool/logging/StorageTableHandler.java b/src/net/runal/jtool/logging/StorageTableHandler.java index d3f150b..2820a7c 100755 --- a/src/net/runal/jtool/logging/StorageTableHandler.java +++ b/src/net/runal/jtool/logging/StorageTableHandler.java @@ -1,382 +1,382 @@ /* * $Id$ * * Copyright (c) 2012 Runal House. * All Rights Reserved. */ package net.runal.jtool.logging; import com.microsoft.windowsazure.serviceruntime.RoleEnvironment; import com.microsoft.windowsazure.services.core.storage.CloudStorageAccount; import com.microsoft.windowsazure.services.core.storage.StorageCredentials; import com.microsoft.windowsazure.services.core.storage.StorageCredentialsAccountAndKey; import com.microsoft.windowsazure.services.core.storage.StorageException; import com.microsoft.windowsazure.services.table.client.CloudTable; import com.microsoft.windowsazure.services.table.client.CloudTableClient; import com.microsoft.windowsazure.services.table.client.TableOperation; import com.microsoft.windowsazure.services.table.client.TableQuery; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.*; import java.util.regex.Pattern; import net.runal.jtool.storage.StorageConstants; import net.runal.jtool.util.CloudProperties; /** * * @author yasuo */ public class StorageTableHandler extends Handler { private static final Logger LOGGER = Logger.getLogger(StorageTableHandler.class.getName()); private static Exception log(Level level, String msg, Throwable thrown) throws Error { LOGGER.log(level, msg, thrown); if(thrown instanceof Exception) { return (Exception)thrown; } else if(thrown instanceof Error) { throw (Error)thrown; } else { return new IllegalArgumentException(thrown); } } private static void log(Level level, String pattern, Object... args) { LOGGER.log(level, pattern, args); } public static final String TABLE_NAME_KEY = "TableName"; public static final String DEFAULT_TABLE_NAME = "LogRecordTable"; // private CloudTable table; private final List<LogRecordTableEntity> list; public StorageTableHandler() { list = new ArrayList<LogRecordTableEntity>(10); LogManager manager = LogManager.getLogManager(); manager.checkAccess(); configure(); connect(); } private int limit; private Cfg cfg; private Level getLevelProperty(String string, Level defaultValue) { try { return Level.parse(string); } catch(Exception ex) { return defaultValue; } } private Filter getFilterProperty(String string, Filter defaultValue) { try { Class<?> cls = Class.forName(string); if(Filter.class.isAssignableFrom(cls)) { Object instance = cls.newInstance(); return (Filter) instance; } else { return defaultValue; } } catch(Exception ex) { return defaultValue; } } private Formatter getFormatterProperty(String string, Formatter defaultValue) { try { Class<?> cls = Class.forName(string); if(Formatter.class.isAssignableFrom(cls)) { Object instance = cls.newInstance(); return (Formatter) instance; } else { return defaultValue; } } catch(Exception ex) { return defaultValue; } } // private String getStringProperty(String string, String defaultValue) { // if(string instanceof String) { // return string; // } else { // return defaultValue; // } // } private int getIntProperty(String string, int defaultValue) { try { return Integer.valueOf(string); } catch(Exception ex) { return defaultValue; } } //////////////////////////////////////////////////////////////////////////////// private class Cfg implements StorageConstants { private String accountName; private String accountKey; private String endPoint; private String connectionString; private String diagnosticsConnectionString; private String tableName; private void configure() { final LogManager manager = LogManager.getLogManager(); final CloudProperties prop = CloudProperties.getInstance(); - final String cname = getClass().getName(); + final String cname = StorageTableHandler.class.getName(); // accountName = manager.getProperty(cname + "." +ACCOUNT_NAME_KEY); if(accountName == null) { accountName = prop.getProperty(cname + "." +ACCOUNT_NAME_KEY); } if(accountName == null) { accountName = prop.getProperty(ACCOUNT_NAME_KEY); } // accountKey = manager.getProperty(cname + "." +ACCOUNT_KEY_KEY); if(accountKey == null) { accountKey = prop.getProperty(cname + "." +ACCOUNT_KEY_KEY); } if(accountKey == null) { accountKey = prop.getProperty(ACCOUNT_KEY_KEY); } // endPoint = manager.getProperty(cname + "." +ENDPOINT_KEY); if(endPoint == null) { endPoint = prop.getProperty(cname + "." +ENDPOINT_KEY); } if(endPoint == null) { endPoint = prop.getProperty(ENDPOINT_KEY); } // connectionString = manager.getProperty(cname + "." +CONNECTION_STRING_KEY); if(connectionString == null) { connectionString = prop.getProperty(cname + "." +CONNECTION_STRING_KEY); } if(connectionString == null) { connectionString = prop.getProperty(CONNECTION_STRING_KEY); } // if(RoleEnvironment.isAvailable()) { diagnosticsConnectionString = RoleEnvironment .getConfigurationSettings().get(DIAGNOSTICS_CONNECTION_STRING_KEY); } else { diagnosticsConnectionString = null; } // if(endPoint != null && accountName != null && !accountName.isEmpty()) { endPoint = endPoint.replaceFirst(Pattern.quote("${" + ACCOUNT_NAME_KEY +"}"), accountName); } // tableName = manager.getProperty(cname + "." +TABLE_NAME_KEY); if(tableName == null) { tableName = DEFAULT_TABLE_NAME; } } /** * TABLEストレージクライアントを取得します。 * * @return */ private CloudTableClient getClient() { configure(); // switch(0) { case 0: try { StorageCredentials credentails = new StorageCredentialsAccountAndKey(accountName, accountKey); // CloudTableClient newClient = new CloudTableClient(new URI(endPoint), credentails); log(Level.CONFIG, "getClient({0}, {1})", ACCOUNT_NAME_KEY, ACCOUNT_KEY_KEY); return newClient; } catch (Exception ex) { log(Level.FINEST, null, ex); } case 1: try { CloudStorageAccount storageAccount = CloudStorageAccount.parse(connectionString); // CloudTableClient newClient = storageAccount.createCloudTableClient(); log(Level.CONFIG, "getClient({0})", CONNECTION_STRING_KEY); return newClient; } catch (Exception ex) { log(Level.FINEST, null, ex); } case 2: try { CloudStorageAccount storageAccount = CloudStorageAccount.parse(diagnosticsConnectionString); // CloudTableClient newClient = storageAccount.createCloudTableClient(); log(Level.CONFIG, "getClient({0})", DIAGNOSTICS_CONNECTION_STRING_KEY); return newClient; } catch (Exception ex) { log(Level.FINEST, null, ex); } default: log(Level.CONFIG, "getClient()"); return null; } } } //////////////////////////////////////////////////////////////////////////////// private void configure() { LogManager manager = LogManager.getLogManager(); CloudProperties prop = CloudProperties.getInstance(); String cname = getClass().getName(); limit = getIntProperty(manager.getProperty(cname + ".limit"), 10); if (limit < 0) { limit = 0; } setLevel(getLevelProperty(manager.getProperty(cname + ".level"), Level.ALL)); setFilter(getFilterProperty(manager.getProperty(cname + ".filter"), null)); setFormatter(getFormatterProperty(manager.getProperty(cname + ".formatter"), new XMLFormatter())); cfg = new Cfg(); } private void connect() { LogManager manager = LogManager.getLogManager(); manager.checkAccess(); try { CloudTableClient newClient = cfg.getClient(); if(newClient == null) { table = null; } else { CloudTable newTable = new CloudTable(cfg.tableName, newClient); table = newTable; } } catch (Exception ex) { } } public URI getEndPointURI() { if (table != null) { return table.getServiceClient().getEndpoint(); } else { return null; } } public String getTableName() { if (table != null) { return table.getName(); } else { return null; } } public Iterator<LogRecordTableEntity> query(String condition) throws StorageException { if (table != null) { if(!table.exists()) { return Collections.emptyIterator(); } // クエリ TableQuery<LogRecordTableEntity> query = TableQuery.from(table.getName(), LogRecordTableEntity.class) .where(condition) ; return table.getServiceClient().execute(query).iterator(); } else { throw new IllegalStateException(); } } @Override public boolean isLoggable(LogRecord record) { if (table == null || record == null) { return false; } return super.isLoggable(record); } @Override public void publish(LogRecord record) { if (!isLoggable(record)) { return; } String msg; try { msg = getFormatter().format(record); } catch (Exception ex) { // We don't want to throw an exception here, but we // report the exception to any registered ErrorManager. reportError(null, ex, ErrorManager.FORMAT_FAILURE); return; } synchronized(list) { if(limit == 0 || limit > list.size()) { list.add(new LogRecordTableEntity(record, msg)); } else { reportError(null, new IllegalStateException("overflow"), ErrorManager.WRITE_FAILURE); } } flush(); } private void write(Iterator<LogRecordTableEntity> it) throws StorageException { while(it.hasNext()) { TableOperation insert = TableOperation.insert(it.next()); table.getServiceClient().execute(table.getName(), insert); it.remove(); } } @Override public void flush() { if (table != null) { synchronized(list) { final Iterator<LogRecordTableEntity> it = list.iterator(); try { write(it); } catch(StorageException ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); try { if(!table.exists()) { table.create(); } write(it); } catch(StorageException ex2) { reportError(null, ex2, ErrorManager.FLUSH_FAILURE); } } } } } @Override public void close() throws SecurityException { flush(); table = null; } }
true
true
private void configure() { final LogManager manager = LogManager.getLogManager(); final CloudProperties prop = CloudProperties.getInstance(); final String cname = getClass().getName(); // accountName = manager.getProperty(cname + "." +ACCOUNT_NAME_KEY); if(accountName == null) { accountName = prop.getProperty(cname + "." +ACCOUNT_NAME_KEY); } if(accountName == null) { accountName = prop.getProperty(ACCOUNT_NAME_KEY); } // accountKey = manager.getProperty(cname + "." +ACCOUNT_KEY_KEY); if(accountKey == null) { accountKey = prop.getProperty(cname + "." +ACCOUNT_KEY_KEY); } if(accountKey == null) { accountKey = prop.getProperty(ACCOUNT_KEY_KEY); } // endPoint = manager.getProperty(cname + "." +ENDPOINT_KEY); if(endPoint == null) { endPoint = prop.getProperty(cname + "." +ENDPOINT_KEY); } if(endPoint == null) { endPoint = prop.getProperty(ENDPOINT_KEY); } // connectionString = manager.getProperty(cname + "." +CONNECTION_STRING_KEY); if(connectionString == null) { connectionString = prop.getProperty(cname + "." +CONNECTION_STRING_KEY); } if(connectionString == null) { connectionString = prop.getProperty(CONNECTION_STRING_KEY); } // if(RoleEnvironment.isAvailable()) { diagnosticsConnectionString = RoleEnvironment .getConfigurationSettings().get(DIAGNOSTICS_CONNECTION_STRING_KEY); } else { diagnosticsConnectionString = null; } // if(endPoint != null && accountName != null && !accountName.isEmpty()) { endPoint = endPoint.replaceFirst(Pattern.quote("${" + ACCOUNT_NAME_KEY +"}"), accountName); } // tableName = manager.getProperty(cname + "." +TABLE_NAME_KEY); if(tableName == null) { tableName = DEFAULT_TABLE_NAME; } }
private void configure() { final LogManager manager = LogManager.getLogManager(); final CloudProperties prop = CloudProperties.getInstance(); final String cname = StorageTableHandler.class.getName(); // accountName = manager.getProperty(cname + "." +ACCOUNT_NAME_KEY); if(accountName == null) { accountName = prop.getProperty(cname + "." +ACCOUNT_NAME_KEY); } if(accountName == null) { accountName = prop.getProperty(ACCOUNT_NAME_KEY); } // accountKey = manager.getProperty(cname + "." +ACCOUNT_KEY_KEY); if(accountKey == null) { accountKey = prop.getProperty(cname + "." +ACCOUNT_KEY_KEY); } if(accountKey == null) { accountKey = prop.getProperty(ACCOUNT_KEY_KEY); } // endPoint = manager.getProperty(cname + "." +ENDPOINT_KEY); if(endPoint == null) { endPoint = prop.getProperty(cname + "." +ENDPOINT_KEY); } if(endPoint == null) { endPoint = prop.getProperty(ENDPOINT_KEY); } // connectionString = manager.getProperty(cname + "." +CONNECTION_STRING_KEY); if(connectionString == null) { connectionString = prop.getProperty(cname + "." +CONNECTION_STRING_KEY); } if(connectionString == null) { connectionString = prop.getProperty(CONNECTION_STRING_KEY); } // if(RoleEnvironment.isAvailable()) { diagnosticsConnectionString = RoleEnvironment .getConfigurationSettings().get(DIAGNOSTICS_CONNECTION_STRING_KEY); } else { diagnosticsConnectionString = null; } // if(endPoint != null && accountName != null && !accountName.isEmpty()) { endPoint = endPoint.replaceFirst(Pattern.quote("${" + ACCOUNT_NAME_KEY +"}"), accountName); } // tableName = manager.getProperty(cname + "." +TABLE_NAME_KEY); if(tableName == null) { tableName = DEFAULT_TABLE_NAME; } }
diff --git a/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/util/JSF2ResourceUtil.java b/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/util/JSF2ResourceUtil.java index 790432ebe..341ab41ff 100644 --- a/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/util/JSF2ResourceUtil.java +++ b/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/util/JSF2ResourceUtil.java @@ -1,359 +1,359 @@ /******************************************************************************* * Copyright (c) 2007-2010 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.jsf.jsf2.util; import java.io.File; import java.util.zip.ZipEntry; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.core.ExternalPackageFragmentRoot; import org.eclipse.jdt.internal.core.JarEntryDirectory; import org.eclipse.jdt.internal.core.JarEntryFile; import org.eclipse.jdt.internal.core.JarEntryResource; import org.eclipse.jdt.internal.core.JarPackageFragmentRoot; import org.eclipse.wst.common.componentcore.ComponentCore; import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; import org.eclipse.wst.common.componentcore.resources.IVirtualFolder; import org.eclipse.wst.sse.ui.internal.reconcile.validator.IncrementalHelper; import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; import org.eclipse.wst.xml.core.internal.document.ElementImpl; import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement; import org.jboss.tools.jsf.JSFModelPlugin; import org.jboss.tools.jsf.jsf2.model.JSF2ComponentModelManager; import org.jboss.tools.jsf.web.validation.jsf2.util.JSF2TemplateManager; import org.jboss.tools.jst.web.WebUtils; /** * * @author yzhishko * */ @SuppressWarnings("restriction") public class JSF2ResourceUtil { public static final String JSF2_URI_PREFIX = "http://java.sun.com/jsf/composite"; //$NON-NLS-1$ public static final String COMPONENT_RESOURCE_PATH_KEY = "component_resource_path_key"; //$NON-NLS-1$ public static final String JSF2_COMPONENT_NAME = "jsf2_resource_name"; //$NON-NLS-1$ public static final int JAR_FILE_RESOURCE_TYPE = 1; public static final int JAR_DIRECTORY_RESOURCE_TYPE = JAR_FILE_RESOURCE_TYPE << 1; public static Object findCompositeComponentContainer(IProject project, IDOMElement jsf2Element) { ElementImpl elementImpl = (ElementImpl) jsf2Element; String nameSpaceURI = elementImpl.getNamespaceURI(); if (nameSpaceURI == null || nameSpaceURI.indexOf(JSF2_URI_PREFIX) == -1) { return null; } String nodeName = jsf2Element.getLocalName(); String relativeLocation = "/resources" + nameSpaceURI.replaceFirst( //$NON-NLS-1$ JSF2ResourceUtil.JSF2_URI_PREFIX, ""); //$NON-NLS-1$ IVirtualComponent component = ComponentCore.createComponent(project); if (component != null) { IVirtualFolder webRootFolder = component.getRootFolder().getFolder( new Path("/")); //$NON-NLS-1$ IContainer[] folders = webRootFolder.getUnderlyingFolders(); for (IContainer folder: folders) { IPath path = folder.getFullPath().append(relativeLocation).append( "/" + nodeName + ".xhtml"); //$NON-NLS-1$ //$NON-NLS-2$ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); if (file.isAccessible()) { return file; } } } String classPathResource = "META-INF" + relativeLocation //$NON-NLS-1$ + "/" + nodeName + ".xhtml"; //$NON-NLS-1$ //$NON-NLS-2$ JarEntryResource jer = searchInClassPath(project, classPathResource, JAR_FILE_RESOURCE_TYPE); if(jer != null) { return jer; } IResource r = searchInClassPath2(project, classPathResource, JAR_FILE_RESOURCE_TYPE); if(r != null) { return r; } return null; } private static JarEntryResource searchInClassPath(IProject project, String classPathResource, int jarResourceType) { IJavaProject javaProject = JavaCore.create(project); try { for (IPackageFragmentRoot fragmentRoot : javaProject .getAllPackageFragmentRoots()) { if (fragmentRoot instanceof JarPackageFragmentRoot) { JarPackageFragmentRoot jarPackageFragmentRoot = (JarPackageFragmentRoot) fragmentRoot; ZipEntry zipEntry = jarPackageFragmentRoot.getJar() .getEntry(classPathResource); if (zipEntry != null) { if (jarResourceType == JAR_FILE_RESOURCE_TYPE) { JarEntryFile fileInJar = new JarEntryFile( classPathResource); fileInJar.setParent(jarPackageFragmentRoot); return fileInJar; } if (jarResourceType == JAR_DIRECTORY_RESOURCE_TYPE) { JarEntryDirectory directoryInJar = new JarEntryDirectory( classPathResource); directoryInJar.setParent(jarPackageFragmentRoot); return directoryInJar; } } } } } catch (JavaModelException e) { JSFModelPlugin.getPluginLog().logError(e); } catch (CoreException e) { JSFModelPlugin.getPluginLog().logError(e); } return null; } private static IResource searchInClassPath2(IProject project, String classPathResource, int jarResourceType) { IJavaProject javaProject = JavaCore.create(project); try { for (IPackageFragmentRoot fragmentRoot : javaProject .getAllPackageFragmentRoots()) { IResource r = fragmentRoot.getResource(); if(fragmentRoot instanceof ExternalPackageFragmentRoot) { r = ((ExternalPackageFragmentRoot) fragmentRoot).resource(); } if(r instanceof IFolder && r.exists()) { IFolder f = (IFolder)r; IFile f1 = f.getFile(classPathResource); if(f1.exists()) { return f1; } IFolder f2 = f.getFolder(classPathResource); if(f2.exists()) { return f2; } } } } catch (JavaModelException e) { JSFModelPlugin.getPluginLog().logError(e); } catch (CoreException e) { JSFModelPlugin.getPluginLog().logError(e); } return null; } public static Object findResourcesFolderContainerByNameSpace( IProject project, String nameSpaceURI) { if (nameSpaceURI == null || nameSpaceURI.indexOf(JSF2_URI_PREFIX) == -1) { return null; } String relativeLocation = "/resources" + nameSpaceURI.replaceFirst( //$NON-NLS-1$ JSF2ResourceUtil.JSF2_URI_PREFIX, ""); //$NON-NLS-1$ IVirtualComponent component = ComponentCore.createComponent(project); if (component != null) { IVirtualFolder webRootFolder = component.getRootFolder().getFolder( new Path("/")); //$NON-NLS-1$ IContainer[] folders = webRootFolder.getUnderlyingFolders(); for (IContainer folder: folders) { IPath path = folder.getFullPath().append(relativeLocation); IFolder resFolder = ResourcesPlugin.getWorkspace().getRoot() .getFolder(path); if (resFolder.isAccessible()) { return resFolder; } } } String classPathResource = "META-INF" + relativeLocation; //$NON-NLS-1$ JarEntryResource jer = searchInClassPath(project, classPathResource, JAR_DIRECTORY_RESOURCE_TYPE); if(jer != null) { return jer; } IResource r = searchInClassPath2(project, classPathResource, JAR_DIRECTORY_RESOURCE_TYPE); if(r != null) { return r; } return null; } public static boolean isResourcesFolderExists(IProject project, String nameSpaceURI) { return findResourcesFolderContainerByNameSpace(project, nameSpaceURI) == null ? false : true; } public static IFolder createResourcesFolderByNameSpace(IProject project, String nameSpaceURI) throws CoreException { IFolder compositeCompResFolder = null; String relativeLocation = nameSpaceURI.replaceFirst( JSF2ResourceUtil.JSF2_URI_PREFIX, ""); //$NON-NLS-1$ if (!project.exists()) { return null; } if (!project.isAccessible()) { try { project.open(new NullProgressMonitor()); } catch (CoreException e) { JSFModelPlugin.getPluginLog().logError(e); return compositeCompResFolder; } } IVirtualComponent component = ComponentCore.createComponent(project); if (component != null) { IVirtualFolder webRootFolder = component.getRootFolder().getFolder( new Path("/")); //$NON-NLS-1$ IContainer folder = webRootFolder.getUnderlyingFolder(); IFolder webFolder = ResourcesPlugin.getWorkspace().getRoot() .getFolder(folder.getFullPath()); IFolder resourcesFolder = webFolder.getFolder("resources"); //$NON-NLS-1$ NullProgressMonitor monitor = new NullProgressMonitor(); if (!resourcesFolder.exists()) { resourcesFolder.create(true, true, monitor); } String[] segments = new Path(relativeLocation).segments(); compositeCompResFolder = resourcesFolder; for (int i = 0; i < segments.length; i++) { compositeCompResFolder = compositeCompResFolder .getFolder(segments[i]); if (!compositeCompResFolder.exists()) { compositeCompResFolder.create(true, true, monitor); } } } return compositeCompResFolder; } public static IFile createCompositeComponentFile(IProject project, IPath resourceRelativePath) throws CoreException { IFile compositeCompResFile = null; if (!project.exists()) { return null; } if (!project.isAccessible()) { try { project.open(new NullProgressMonitor()); } catch (CoreException e) { JSFModelPlugin.getPluginLog().logError(e); return compositeCompResFile; } } IVirtualComponent component = ComponentCore.createComponent(project); if (component != null) { - IContainer[] folders = WebUtils.getWebRootFolders(project, false); + IContainer[] folders = WebUtils.getWebRootFolders(project); if(folders == null || folders.length == 0) return null; IFolder webFolder = ResourcesPlugin.getWorkspace().getRoot() .getFolder(folders[0].getFullPath()); IFolder resourcesFolder = webFolder.getFolder("resources"); //$NON-NLS-1$ NullProgressMonitor monitor = new NullProgressMonitor(); if (!resourcesFolder.exists()) { resourcesFolder.create(true, true, monitor); } String[] segments = resourceRelativePath.segments(); IFolder componentPathFolder = resourcesFolder; for (int i = 0; i < segments.length - 1; i++) { componentPathFolder = componentPathFolder .getFolder(segments[i]); if (!componentPathFolder.exists()) { componentPathFolder.create(true, true, monitor); } } compositeCompResFile = componentPathFolder .getFile(segments[segments.length - 1]); if (!compositeCompResFile.exists()) { compositeCompResFile.create(JSF2TemplateManager.getManager() .createStreamFromTemplate("composite.xhtml"), true, //$NON-NLS-1$ monitor); } else { compositeCompResFile = JSF2ComponentModelManager.getManager() .revalidateCompositeComponentFile(compositeCompResFile); } } return compositeCompResFile; } public static IFile createCompositeComponentFile(IProject project, IPath resourceRelativePath, String[] attrNames) throws CoreException { IFile jsf2ResFile = createCompositeComponentFile(project, resourceRelativePath); if (jsf2ResFile == null) { return null; } if (attrNames == null || attrNames.length == 0) { return jsf2ResFile; } return JSF2ComponentModelManager.getManager() .updateJSF2CompositeComponentFile(jsf2ResFile, attrNames); } /** * Calculates workspace relative jsf2 resources string * @return workspace relative resource string * @author mareshkau */ public static String calculateProjectRelativeJSF2ResourceProposal( IProject project){ IVirtualComponent component = ComponentCore.createComponent(project); String projectResourceRelativePath = ""; if (component != null) { IVirtualFolder webRootFolder = component.getRootFolder().getFolder( new Path("/")); //$NON-NLS-1$ IContainer folder = webRootFolder.getUnderlyingFolder(); IFolder webFolder = ResourcesPlugin.getWorkspace().getRoot() .getFolder(folder.getFullPath()); IFolder resourcesFolder = webFolder.getFolder("resources"); resourcesFolder.getProjectRelativePath().toString(); projectResourceRelativePath=project.getName()+File.separator+resourcesFolder.getProjectRelativePath().toString(); } return projectResourceRelativePath; } /** * Get validating resource * @param helper * @return IResource on which validator works */ public static IResource getValidatingResource(IValidationContext helper){ IResource resource=null; if (helper instanceof IncrementalHelper) { IncrementalHelper incrementalHelper = (IncrementalHelper) helper; IProject project = incrementalHelper.getProject(); if (project == null) { return resource; } String[] uris = helper.getURIs(); if (uris == null || uris.length < 1) { return resource; } String filePath = uris[0]; if (filePath == null) { return resource; } filePath = filePath.substring(filePath.indexOf('/') + 1); resource = project.findMember(filePath .substring(filePath.indexOf('/') + 1)); } return resource; } }
true
true
public static IFile createCompositeComponentFile(IProject project, IPath resourceRelativePath) throws CoreException { IFile compositeCompResFile = null; if (!project.exists()) { return null; } if (!project.isAccessible()) { try { project.open(new NullProgressMonitor()); } catch (CoreException e) { JSFModelPlugin.getPluginLog().logError(e); return compositeCompResFile; } } IVirtualComponent component = ComponentCore.createComponent(project); if (component != null) { IContainer[] folders = WebUtils.getWebRootFolders(project, false); if(folders == null || folders.length == 0) return null; IFolder webFolder = ResourcesPlugin.getWorkspace().getRoot() .getFolder(folders[0].getFullPath()); IFolder resourcesFolder = webFolder.getFolder("resources"); //$NON-NLS-1$ NullProgressMonitor monitor = new NullProgressMonitor(); if (!resourcesFolder.exists()) { resourcesFolder.create(true, true, monitor); } String[] segments = resourceRelativePath.segments(); IFolder componentPathFolder = resourcesFolder; for (int i = 0; i < segments.length - 1; i++) { componentPathFolder = componentPathFolder .getFolder(segments[i]); if (!componentPathFolder.exists()) { componentPathFolder.create(true, true, monitor); } } compositeCompResFile = componentPathFolder .getFile(segments[segments.length - 1]); if (!compositeCompResFile.exists()) { compositeCompResFile.create(JSF2TemplateManager.getManager() .createStreamFromTemplate("composite.xhtml"), true, //$NON-NLS-1$ monitor); } else { compositeCompResFile = JSF2ComponentModelManager.getManager() .revalidateCompositeComponentFile(compositeCompResFile); } } return compositeCompResFile; }
public static IFile createCompositeComponentFile(IProject project, IPath resourceRelativePath) throws CoreException { IFile compositeCompResFile = null; if (!project.exists()) { return null; } if (!project.isAccessible()) { try { project.open(new NullProgressMonitor()); } catch (CoreException e) { JSFModelPlugin.getPluginLog().logError(e); return compositeCompResFile; } } IVirtualComponent component = ComponentCore.createComponent(project); if (component != null) { IContainer[] folders = WebUtils.getWebRootFolders(project); if(folders == null || folders.length == 0) return null; IFolder webFolder = ResourcesPlugin.getWorkspace().getRoot() .getFolder(folders[0].getFullPath()); IFolder resourcesFolder = webFolder.getFolder("resources"); //$NON-NLS-1$ NullProgressMonitor monitor = new NullProgressMonitor(); if (!resourcesFolder.exists()) { resourcesFolder.create(true, true, monitor); } String[] segments = resourceRelativePath.segments(); IFolder componentPathFolder = resourcesFolder; for (int i = 0; i < segments.length - 1; i++) { componentPathFolder = componentPathFolder .getFolder(segments[i]); if (!componentPathFolder.exists()) { componentPathFolder.create(true, true, monitor); } } compositeCompResFile = componentPathFolder .getFile(segments[segments.length - 1]); if (!compositeCompResFile.exists()) { compositeCompResFile.create(JSF2TemplateManager.getManager() .createStreamFromTemplate("composite.xhtml"), true, //$NON-NLS-1$ monitor); } else { compositeCompResFile = JSF2ComponentModelManager.getManager() .revalidateCompositeComponentFile(compositeCompResFile); } } return compositeCompResFile; }
diff --git a/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java b/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java index c6b480e0..61368c56 100644 --- a/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java +++ b/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java @@ -1,212 +1,212 @@ package grisu.backend.model.job.gt5; import grith.jgrith.plainProxy.LocalProxy; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.logging.Level; import org.apache.log4j.Logger; import org.globus.gram.Gram; import org.globus.gram.GramException; import org.globus.gram.GramJob; import org.globus.gram.GramJobListener; import org.globus.gram.internal.GRAMConstants; import org.globus.gram.internal.GRAMProtocolErrorConstants; import org.globus.gsi.GlobusCredentialException; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; public class Gram5Client implements GramJobListener { private static HashMap<String, Integer> statuses = new HashMap<String, Integer>(); private static HashMap<String, Integer> errors = new HashMap<String, Integer>(); static final Logger myLogger = Logger .getLogger(Gram5Client.class.getName()); public static void main(String[] args) { final String testRSL = args[1]; final String contact = "ng1.canterbury.ac.nz"; try { final Gram gram = new Gram(); Gram.ping(contact); final GramJob testJob = new GramJob(testRSL); testJob.setCredentials(LocalProxy.loadGSSCredential()); final Gram5Client gram5 = new Gram5Client(); testJob.addListener(gram5); // testJob.bind(); testJob.request("ng1.canterbury.ac.nz", true); testJob.bind(); Gram.registerListener(testJob); Gram.jobStatus(testJob); System.out .println("job status is : " + testJob.getStatusAsString()); System.out.println("the job is : " + testJob.toString()); System.out.println("number of currently active jobs : " + Gram.getActiveJobs()); while (true) { Gram.jobStatus(testJob); System.out.println("job status is : " + testJob.getStatusAsString()); Thread.sleep(1000); } } catch (final GlobusCredentialException gx) { gx.printStackTrace(); } catch (final GramException grx) { grx.printStackTrace(); } catch (final GSSException gssx) { gssx.printStackTrace(); } catch (final Exception ex) { ex.printStackTrace(); } } public Gram5Client() { } private String getContactString(String handle) { try { final URL url = new URL(handle); myLogger.debug("job handle is " + handle); myLogger.debug("returned handle is " + url.getHost()); return url.getHost(); } catch (final MalformedURLException ex1) { java.util.logging.Logger.getLogger(Gram5Client.class.getName()) .log(Level.SEVERE, null, ex1); return null; } } public int[] getJobStatus(String handle, GSSCredential cred) { final int[] results = new int[2]; // we need this to catch quick failure Integer status = statuses.get(handle); myLogger.debug("status is " + status); if ((status != null) && (status == GRAMConstants.STATUS_FAILED)) { myLogger.debug("job failed : " + errors.get(handle)); results[0] = status; results[1] = errors.get(handle); return results; } final String contact = getContactString(handle); final GramJob job = new GramJob(null); try { // lets try to see if gateway is working first... Gram.ping(cred,contact); } catch (final GramException ex) { myLogger.info(ex); // have no idea what the status is, gateway is down: return new int[] { GRAMConstants.STATUS_UNSUBMITTED, 0 }; } catch (final GSSException ex) { myLogger.error(ex); } try { job.setID(handle); job.setCredentials(cred); job.bind(); Gram.jobStatus(job); myLogger.debug("job status is " + job.getStatusAsString()); myLogger.debug("job error is " + job.getError()); } catch (final GramException ex) { - if (ex.getErrorCode() == GRAMProtocolErrorConstants.CONNECTION_FAILED) { + if (ex.getErrorCode() == 156 /* job contact not found*/) { // maybe the job finished, but maybe we need to kick job manager myLogger.debug("restarting job"); final String rsl = "&(restart=" + handle + ")"; final GramJob restartJob = new GramJob(rsl); restartJob.setCredentials(cred); restartJob.addListener(this); try { restartJob.request(contact, false); } catch (final GramException ex1) { // ok, now we are really done return new int[] { GRAMConstants.STATUS_DONE, 0 }; } catch (final GSSException ex1) { throw new RuntimeException(ex1); } // nope, not done yet. return getJobStatus(handle, cred); } else { myLogger.error("error code is " + ex.getErrorCode()); myLogger.error(ex); } } catch (final GSSException ex) { myLogger.error(ex); } catch (final MalformedURLException ex) { myLogger.error(ex); } status = job.getStatus(); final int error = job.getError(); return new int[] { status, error }; } public int kill(String handle, GSSCredential cred) { try { final GramJob job = new GramJob(null); job.setID(handle); job.setCredentials(cred); try { new Gram(); Gram.cancel(job); // job.signal(job.SIGNAL_CANCEL); } catch (final GramException ex) { java.util.logging.Logger.getLogger(Gram5Client.class.getName()) .log(Level.SEVERE, null, ex); } catch (final GSSException ex) { java.util.logging.Logger.getLogger(Gram5Client.class.getName()) .log(Level.SEVERE, null, ex); } final int status = job.getStatus(); return status; } catch (final MalformedURLException ex) { java.util.logging.Logger.getLogger(Gram5Client.class.getName()) .log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } } public void statusChanged(GramJob job) { myLogger.debug("job status changed " + job.getStatusAsString()); statuses.put(job.getIDAsString(), job.getStatus()); errors.put(job.getIDAsString(), job.getError()); myLogger.debug("the job is : " + job.toString()); } public String submit(String rsl, String endPoint, GSSCredential cred) { final GramJob job = new GramJob(rsl); job.setCredentials(cred); job.addListener(this); try { job.request(endPoint, false); Gram.jobStatus(job); return job.getIDAsString(); } catch (final GramException ex) { java.util.logging.Logger.getLogger(Gram5Client.class.getName()) .log(Level.SEVERE, null, ex); return null; } catch (final GSSException ex) { java.util.logging.Logger.getLogger(Gram5Client.class.getName()) .log(Level.SEVERE, null, ex); return null; } } }
true
true
public int[] getJobStatus(String handle, GSSCredential cred) { final int[] results = new int[2]; // we need this to catch quick failure Integer status = statuses.get(handle); myLogger.debug("status is " + status); if ((status != null) && (status == GRAMConstants.STATUS_FAILED)) { myLogger.debug("job failed : " + errors.get(handle)); results[0] = status; results[1] = errors.get(handle); return results; } final String contact = getContactString(handle); final GramJob job = new GramJob(null); try { // lets try to see if gateway is working first... Gram.ping(cred,contact); } catch (final GramException ex) { myLogger.info(ex); // have no idea what the status is, gateway is down: return new int[] { GRAMConstants.STATUS_UNSUBMITTED, 0 }; } catch (final GSSException ex) { myLogger.error(ex); } try { job.setID(handle); job.setCredentials(cred); job.bind(); Gram.jobStatus(job); myLogger.debug("job status is " + job.getStatusAsString()); myLogger.debug("job error is " + job.getError()); } catch (final GramException ex) { if (ex.getErrorCode() == GRAMProtocolErrorConstants.CONNECTION_FAILED) { // maybe the job finished, but maybe we need to kick job manager myLogger.debug("restarting job"); final String rsl = "&(restart=" + handle + ")"; final GramJob restartJob = new GramJob(rsl); restartJob.setCredentials(cred); restartJob.addListener(this); try { restartJob.request(contact, false); } catch (final GramException ex1) { // ok, now we are really done return new int[] { GRAMConstants.STATUS_DONE, 0 }; } catch (final GSSException ex1) { throw new RuntimeException(ex1); } // nope, not done yet. return getJobStatus(handle, cred); } else { myLogger.error("error code is " + ex.getErrorCode()); myLogger.error(ex); } } catch (final GSSException ex) { myLogger.error(ex); } catch (final MalformedURLException ex) { myLogger.error(ex); } status = job.getStatus(); final int error = job.getError(); return new int[] { status, error }; }
public int[] getJobStatus(String handle, GSSCredential cred) { final int[] results = new int[2]; // we need this to catch quick failure Integer status = statuses.get(handle); myLogger.debug("status is " + status); if ((status != null) && (status == GRAMConstants.STATUS_FAILED)) { myLogger.debug("job failed : " + errors.get(handle)); results[0] = status; results[1] = errors.get(handle); return results; } final String contact = getContactString(handle); final GramJob job = new GramJob(null); try { // lets try to see if gateway is working first... Gram.ping(cred,contact); } catch (final GramException ex) { myLogger.info(ex); // have no idea what the status is, gateway is down: return new int[] { GRAMConstants.STATUS_UNSUBMITTED, 0 }; } catch (final GSSException ex) { myLogger.error(ex); } try { job.setID(handle); job.setCredentials(cred); job.bind(); Gram.jobStatus(job); myLogger.debug("job status is " + job.getStatusAsString()); myLogger.debug("job error is " + job.getError()); } catch (final GramException ex) { if (ex.getErrorCode() == 156 /* job contact not found*/) { // maybe the job finished, but maybe we need to kick job manager myLogger.debug("restarting job"); final String rsl = "&(restart=" + handle + ")"; final GramJob restartJob = new GramJob(rsl); restartJob.setCredentials(cred); restartJob.addListener(this); try { restartJob.request(contact, false); } catch (final GramException ex1) { // ok, now we are really done return new int[] { GRAMConstants.STATUS_DONE, 0 }; } catch (final GSSException ex1) { throw new RuntimeException(ex1); } // nope, not done yet. return getJobStatus(handle, cred); } else { myLogger.error("error code is " + ex.getErrorCode()); myLogger.error(ex); } } catch (final GSSException ex) { myLogger.error(ex); } catch (final MalformedURLException ex) { myLogger.error(ex); } status = job.getStatus(); final int error = job.getError(); return new int[] { status, error }; }
diff --git a/lucene/src/java/org/apache/lucene/search/BooleanQuery.java b/lucene/src/java/org/apache/lucene/search/BooleanQuery.java index b1c643f4..d1f3ebca 100644 --- a/lucene/src/java/org/apache/lucene/search/BooleanQuery.java +++ b/lucene/src/java/org/apache/lucene/search/BooleanQuery.java @@ -1,484 +1,489 @@ package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.util.ToStringUtils; import org.apache.lucene.search.BooleanClause.Occur; import java.io.IOException; import java.util.*; /** A Query that matches documents matching boolean combinations of other * queries, e.g. {@link TermQuery}s, {@link PhraseQuery}s or other * BooleanQuerys. */ public class BooleanQuery extends Query implements Iterable<BooleanClause> { private static int maxClauseCount = 1024; /** Thrown when an attempt is made to add more than {@link * #getMaxClauseCount()} clauses. This typically happens if * a PrefixQuery, FuzzyQuery, WildcardQuery, or TermRangeQuery * is expanded to many terms during search. */ public static class TooManyClauses extends RuntimeException { public TooManyClauses() {} @Override public String getMessage() { return "maxClauseCount is set to " + maxClauseCount; } } /** Return the maximum number of clauses permitted, 1024 by default. * Attempts to add more than the permitted number of clauses cause {@link * TooManyClauses} to be thrown. * @see #setMaxClauseCount(int) */ public static int getMaxClauseCount() { return maxClauseCount; } /** * Set the maximum number of clauses permitted per BooleanQuery. * Default value is 1024. */ public static void setMaxClauseCount(int maxClauseCount) { if (maxClauseCount < 1) throw new IllegalArgumentException("maxClauseCount must be >= 1"); BooleanQuery.maxClauseCount = maxClauseCount; } private ArrayList<BooleanClause> clauses = new ArrayList<BooleanClause>(); private boolean disableCoord; /** Constructs an empty boolean query. */ public BooleanQuery() {} /** Constructs an empty boolean query. * * {@link Similarity#coord(int,int)} may be disabled in scoring, as * appropriate. For example, this score factor does not make sense for most * automatically generated queries, like {@link WildcardQuery} and {@link * FuzzyQuery}. * * @param disableCoord disables {@link Similarity#coord(int,int)} in scoring. */ public BooleanQuery(boolean disableCoord) { this.disableCoord = disableCoord; } /** Returns true iff {@link Similarity#coord(int,int)} is disabled in * scoring for this query instance. * @see #BooleanQuery(boolean) */ public boolean isCoordDisabled() { return disableCoord; } // Implement coord disabling. // Inherit javadoc. @Override public Similarity getSimilarity(Searcher searcher) { Similarity result = super.getSimilarity(searcher); if (disableCoord) { // disable coord as requested result = new SimilarityDelegator(result) { @Override public float coord(int overlap, int maxOverlap) { return 1.0f; } }; } return result; } /** * Specifies a minimum number of the optional BooleanClauses * which must be satisfied. * * <p> * By default no optional clauses are necessary for a match * (unless there are no required clauses). If this method is used, * then the specified number of clauses is required. * </p> * <p> * Use of this method is totally independent of specifying that * any specific clauses are required (or prohibited). This number will * only be compared against the number of matching optional clauses. * </p> * * @param min the number of optional clauses that must match */ public void setMinimumNumberShouldMatch(int min) { this.minNrShouldMatch = min; } protected int minNrShouldMatch = 0; /** * Gets the minimum number of the optional BooleanClauses * which must be satisfied. */ public int getMinimumNumberShouldMatch() { return minNrShouldMatch; } /** Adds a clause to a boolean query. * * @throws TooManyClauses if the new number of clauses exceeds the maximum clause number * @see #getMaxClauseCount() */ public void add(Query query, BooleanClause.Occur occur) { add(new BooleanClause(query, occur)); } /** Adds a clause to a boolean query. * @throws TooManyClauses if the new number of clauses exceeds the maximum clause number * @see #getMaxClauseCount() */ public void add(BooleanClause clause) { if (clauses.size() >= maxClauseCount) throw new TooManyClauses(); clauses.add(clause); } /** Returns the set of clauses in this query. */ public BooleanClause[] getClauses() { return clauses.toArray(new BooleanClause[clauses.size()]); } /** Returns the list of clauses in this query. */ public List<BooleanClause> clauses() { return clauses; } /** Returns an iterator on the clauses in this query. It implements the {@link Iterable} interface to * make it possible to do: * <pre>for (BooleanClause clause : booleanQuery) {}</pre> */ public final Iterator<BooleanClause> iterator() { return clauses().iterator(); } /** * Expert: the Weight for BooleanQuery, used to * normalize, score and explain these queries. * * <p>NOTE: this API and implementation is subject to * change suddenly in the next release.</p> */ protected class BooleanWeight extends Weight { /** The Similarity implementation. */ protected Similarity similarity; protected ArrayList<Weight> weights; protected int maxCoord; // num optional + num required public BooleanWeight(Searcher searcher) throws IOException { this.similarity = getSimilarity(searcher); weights = new ArrayList<Weight>(clauses.size()); for (int i = 0 ; i < clauses.size(); i++) { BooleanClause c = clauses.get(i); weights.add(c.getQuery().createWeight(searcher)); if (!c.isProhibited()) maxCoord++; } } @Override public Query getQuery() { return BooleanQuery.this; } @Override public float getValue() { return getBoost(); } @Override public float sumOfSquaredWeights() throws IOException { float sum = 0.0f; for (int i = 0 ; i < weights.size(); i++) { // call sumOfSquaredWeights for all clauses in case of side effects float s = weights.get(i).sumOfSquaredWeights(); // sum sub weights if (!clauses.get(i).isProhibited()) // only add to sum for non-prohibited clauses sum += s; } sum *= getBoost() * getBoost(); // boost each sub-weight return sum ; } @Override public void normalize(float norm) { norm *= getBoost(); // incorporate boost for (Weight w : weights) { // normalize all clauses, (even if prohibited in case of side affects) w.normalize(norm); } } @Override public Explanation explain(IndexReader reader, int doc) throws IOException { final int minShouldMatch = BooleanQuery.this.getMinimumNumberShouldMatch(); ComplexExplanation sumExpl = new ComplexExplanation(); sumExpl.setDescription("sum of:"); int coord = 0; float sum = 0.0f; boolean fail = false; int shouldMatchCount = 0; Iterator<BooleanClause> cIter = clauses.iterator(); for (Iterator<Weight> wIter = weights.iterator(); wIter.hasNext();) { Weight w = wIter.next(); BooleanClause c = cIter.next(); if (w.scorer(reader, true, true) == null) { + if (c.isRequired()) { + fail = true; + Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")"); + sumExpl.addDetail(r); + } continue; } Explanation e = w.explain(reader, doc); if (e.isMatch()) { if (!c.isProhibited()) { sumExpl.addDetail(e); sum += e.getValue(); coord++; } else { Explanation r = new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")"); r.addDetail(e); sumExpl.addDetail(r); fail = true; } if (c.getOccur() == Occur.SHOULD) shouldMatchCount++; } else if (c.isRequired()) { Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")"); r.addDetail(e); sumExpl.addDetail(r); fail = true; } } if (fail) { sumExpl.setMatch(Boolean.FALSE); sumExpl.setValue(0.0f); sumExpl.setDescription ("Failure to meet condition(s) of required/prohibited clause(s)"); return sumExpl; } else if (shouldMatchCount < minShouldMatch) { sumExpl.setMatch(Boolean.FALSE); sumExpl.setValue(0.0f); sumExpl.setDescription("Failure to match minimum number "+ "of optional clauses: " + minShouldMatch); return sumExpl; } sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE); sumExpl.setValue(sum); float coordFactor = similarity.coord(coord, maxCoord); if (coordFactor == 1.0f) // coord is no-op return sumExpl; // eliminate wrapper else { ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(), sum*coordFactor, "product of:"); result.addDetail(sumExpl); result.addDetail(new Explanation(coordFactor, "coord("+coord+"/"+maxCoord+")")); return result; } } @Override public Scorer scorer(IndexReader reader, boolean scoreDocsInOrder, boolean topScorer) throws IOException { List<Scorer> required = new ArrayList<Scorer>(); List<Scorer> prohibited = new ArrayList<Scorer>(); List<Scorer> optional = new ArrayList<Scorer>(); Iterator<BooleanClause> cIter = clauses.iterator(); for (Weight w : weights) { BooleanClause c = cIter.next(); Scorer subScorer = w.scorer(reader, true, false); if (subScorer == null) { if (c.isRequired()) { return null; } } else if (c.isRequired()) { required.add(subScorer); } else if (c.isProhibited()) { prohibited.add(subScorer); } else { optional.add(subScorer); } } // Check if we can return a BooleanScorer if (!scoreDocsInOrder && topScorer && required.size() == 0 && prohibited.size() < 32) { return new BooleanScorer(this, similarity, minNrShouldMatch, optional, prohibited, maxCoord); } if (required.size() == 0 && optional.size() == 0) { // no required and optional clauses. return null; } else if (optional.size() < minNrShouldMatch) { // either >1 req scorer, or there are 0 req scorers and at least 1 // optional scorer. Therefore if there are not enough optional scorers // no documents will be matched by the query return null; } // Return a BooleanScorer2 return new BooleanScorer2(this, similarity, minNrShouldMatch, required, prohibited, optional, maxCoord); } @Override public boolean scoresDocsOutOfOrder() { int numProhibited = 0; for (BooleanClause c : clauses) { if (c.isRequired()) { return false; // BS2 (in-order) will be used by scorer() } else if (c.isProhibited()) { ++numProhibited; } } if (numProhibited > 32) { // cannot use BS return false; } // scorer() will return an out-of-order scorer if requested. return true; } } @Override public Weight createWeight(Searcher searcher) throws IOException { return new BooleanWeight(searcher); } @Override public Query rewrite(IndexReader reader) throws IOException { if (minNrShouldMatch == 0 && clauses.size() == 1) { // optimize 1-clause queries BooleanClause c = clauses.get(0); if (!c.isProhibited()) { // just return clause Query query = c.getQuery().rewrite(reader); // rewrite first if (getBoost() != 1.0f) { // incorporate boost if (query == c.getQuery()) // if rewrite was no-op query = (Query)query.clone(); // then clone before boost query.setBoost(getBoost() * query.getBoost()); } return query; } } BooleanQuery clone = null; // recursively rewrite for (int i = 0 ; i < clauses.size(); i++) { BooleanClause c = clauses.get(i); Query query = c.getQuery().rewrite(reader); if (query != c.getQuery()) { // clause rewrote: must clone if (clone == null) clone = (BooleanQuery)this.clone(); clone.clauses.set(i, new BooleanClause(query, c.getOccur())); } } if (clone != null) { return clone; // some clauses rewrote } else return this; // no clauses rewrote } // inherit javadoc @Override public void extractTerms(Set<Term> terms) { for (BooleanClause clause : clauses) { clause.getQuery().extractTerms(terms); } } @Override @SuppressWarnings("unchecked") public Object clone() { BooleanQuery clone = (BooleanQuery)super.clone(); clone.clauses = (ArrayList<BooleanClause>) this.clauses.clone(); return clone; } /** Prints a user-readable version of this query. */ @Override public String toString(String field) { StringBuilder buffer = new StringBuilder(); boolean needParens=(getBoost() != 1.0) || (getMinimumNumberShouldMatch()>0) ; if (needParens) { buffer.append("("); } for (int i = 0 ; i < clauses.size(); i++) { BooleanClause c = clauses.get(i); if (c.isProhibited()) buffer.append("-"); else if (c.isRequired()) buffer.append("+"); Query subQuery = c.getQuery(); if (subQuery != null) { if (subQuery instanceof BooleanQuery) { // wrap sub-bools in parens buffer.append("("); buffer.append(subQuery.toString(field)); buffer.append(")"); } else { buffer.append(subQuery.toString(field)); } } else { buffer.append("null"); } if (i != clauses.size()-1) buffer.append(" "); } if (needParens) { buffer.append(")"); } if (getMinimumNumberShouldMatch()>0) { buffer.append('~'); buffer.append(getMinimumNumberShouldMatch()); } if (getBoost() != 1.0f) { buffer.append(ToStringUtils.boost(getBoost())); } return buffer.toString(); } /** Returns true iff <code>o</code> is equal to this. */ @Override public boolean equals(Object o) { if (!(o instanceof BooleanQuery)) return false; BooleanQuery other = (BooleanQuery)o; return (this.getBoost() == other.getBoost()) && this.clauses.equals(other.clauses) && this.getMinimumNumberShouldMatch() == other.getMinimumNumberShouldMatch() && this.disableCoord == other.disableCoord; } /** Returns a hash code value for this object.*/ @Override public int hashCode() { return Float.floatToIntBits(getBoost()) ^ clauses.hashCode() + getMinimumNumberShouldMatch() + (disableCoord ? 17:0); } }
true
true
public Explanation explain(IndexReader reader, int doc) throws IOException { final int minShouldMatch = BooleanQuery.this.getMinimumNumberShouldMatch(); ComplexExplanation sumExpl = new ComplexExplanation(); sumExpl.setDescription("sum of:"); int coord = 0; float sum = 0.0f; boolean fail = false; int shouldMatchCount = 0; Iterator<BooleanClause> cIter = clauses.iterator(); for (Iterator<Weight> wIter = weights.iterator(); wIter.hasNext();) { Weight w = wIter.next(); BooleanClause c = cIter.next(); if (w.scorer(reader, true, true) == null) { continue; } Explanation e = w.explain(reader, doc); if (e.isMatch()) { if (!c.isProhibited()) { sumExpl.addDetail(e); sum += e.getValue(); coord++; } else { Explanation r = new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")"); r.addDetail(e); sumExpl.addDetail(r); fail = true; } if (c.getOccur() == Occur.SHOULD) shouldMatchCount++; } else if (c.isRequired()) { Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")"); r.addDetail(e); sumExpl.addDetail(r); fail = true; } } if (fail) { sumExpl.setMatch(Boolean.FALSE); sumExpl.setValue(0.0f); sumExpl.setDescription ("Failure to meet condition(s) of required/prohibited clause(s)"); return sumExpl; } else if (shouldMatchCount < minShouldMatch) { sumExpl.setMatch(Boolean.FALSE); sumExpl.setValue(0.0f); sumExpl.setDescription("Failure to match minimum number "+ "of optional clauses: " + minShouldMatch); return sumExpl; } sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE); sumExpl.setValue(sum); float coordFactor = similarity.coord(coord, maxCoord); if (coordFactor == 1.0f) // coord is no-op return sumExpl; // eliminate wrapper else { ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(), sum*coordFactor, "product of:"); result.addDetail(sumExpl); result.addDetail(new Explanation(coordFactor, "coord("+coord+"/"+maxCoord+")")); return result; } }
public Explanation explain(IndexReader reader, int doc) throws IOException { final int minShouldMatch = BooleanQuery.this.getMinimumNumberShouldMatch(); ComplexExplanation sumExpl = new ComplexExplanation(); sumExpl.setDescription("sum of:"); int coord = 0; float sum = 0.0f; boolean fail = false; int shouldMatchCount = 0; Iterator<BooleanClause> cIter = clauses.iterator(); for (Iterator<Weight> wIter = weights.iterator(); wIter.hasNext();) { Weight w = wIter.next(); BooleanClause c = cIter.next(); if (w.scorer(reader, true, true) == null) { if (c.isRequired()) { fail = true; Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")"); sumExpl.addDetail(r); } continue; } Explanation e = w.explain(reader, doc); if (e.isMatch()) { if (!c.isProhibited()) { sumExpl.addDetail(e); sum += e.getValue(); coord++; } else { Explanation r = new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")"); r.addDetail(e); sumExpl.addDetail(r); fail = true; } if (c.getOccur() == Occur.SHOULD) shouldMatchCount++; } else if (c.isRequired()) { Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")"); r.addDetail(e); sumExpl.addDetail(r); fail = true; } } if (fail) { sumExpl.setMatch(Boolean.FALSE); sumExpl.setValue(0.0f); sumExpl.setDescription ("Failure to meet condition(s) of required/prohibited clause(s)"); return sumExpl; } else if (shouldMatchCount < minShouldMatch) { sumExpl.setMatch(Boolean.FALSE); sumExpl.setValue(0.0f); sumExpl.setDescription("Failure to match minimum number "+ "of optional clauses: " + minShouldMatch); return sumExpl; } sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE); sumExpl.setValue(sum); float coordFactor = similarity.coord(coord, maxCoord); if (coordFactor == 1.0f) // coord is no-op return sumExpl; // eliminate wrapper else { ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(), sum*coordFactor, "product of:"); result.addDetail(sumExpl); result.addDetail(new Explanation(coordFactor, "coord("+coord+"/"+maxCoord+")")); return result; } }
diff --git a/rtp-text-t140/src/se/omnitor/protocol/rtp/text/SyncBuffer.java b/rtp-text-t140/src/se/omnitor/protocol/rtp/text/SyncBuffer.java index a980b53..90afb79 100644 --- a/rtp-text-t140/src/se/omnitor/protocol/rtp/text/SyncBuffer.java +++ b/rtp-text-t140/src/se/omnitor/protocol/rtp/text/SyncBuffer.java @@ -1,460 +1,460 @@ /* * RTP text/t140 Library * * Copyright (C) 2004 Board of Regents of the University of Wisconsin System * (Univ. of Wisconsin-Madison, Trace R&D Center) * Copyright (C) 2004 Omnitor AB * * This software was developed with support from the National Institute on * Disability and Rehabilitation Research, US Dept of Education under Grant * # H133E990006 and H133E040014 * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Please send a copy of any improved versions of the library to: * Gunnar Hellstrom, Omnitor AB, Renathvagen 2, SE 121 37 Johanneshov, SWEDEN * Gregg Vanderheiden, Trace Center, U of Wisconsin, Madison, Wi 53706 * */ package se.omnitor.protocol.rtp.text; import se.omnitor.util.FifoBuffer; // import LogClasses and Classes import java.util.logging.Level; import java.util.logging.Logger; /** * RFC 4103 states that text should be buffered 300 ms before sending. If * no text has been written in 300 ms and we have redundant data that should * be sent, empty data should be appended. <br> * <br> * All this is handled by this class. <br> * <br> * Text should be sent from GUI to this class, and data should be read by * the RTP sender. <br> * <br> * All data added to this class must be in T.140 format. <br> * * @author Andreas Piirimets, Omnitor AB */ public class SyncBuffer extends FifoBuffer implements Runnable { private byte[] dataWaiting; private byte[] dataToSend; private int redGensToSend; private int redGen; private int bufferTime; private boolean running; private Thread thread; private Integer dataSetSemaphore; private boolean sendOnCR = false; // declare package and classname public final static String CLASS_NAME = SyncBuffer.class.getName(); // get an instance of Logger private static Logger logger = Logger.getLogger(CLASS_NAME); /** * Initializes. * * @param redGen Number of redundant generations. A value of zero turns * off redundancy. * @param bufferTime The number of milliseconds to buffer data. According * to RFC 4103, this SHOULD be 300 ms. */ public SyncBuffer(int redGen, int bufferTime) { // write methodname final String METHOD = "SyncBuffer(int redGen, int bufferTime)"; // log when entering a method logger.entering(CLASS_NAME, METHOD); this.redGen = redGen; this.bufferTime = bufferTime; dataSetSemaphore = new Integer(0); dataWaiting = new byte[0]; dataToSend = new byte[0]; redGensToSend = 0; running = false; thread = null; logger.exiting(CLASS_NAME, METHOD); } public void start() { // write methodname final String METHOD = "start()"; // log when entering a method logger.entering(CLASS_NAME, METHOD); if (!running) { running = true; thread = new Thread(this, "SyncBuffer"); thread.start(); } logger.exiting(CLASS_NAME, METHOD); } public void stop() { running = false; thread.interrupt(); } /** * Sets new data, this should be called from GUI. If data exists it is * appended to the existing data. * * @param newData The data to set/append. * * @todo Backspace handling - If a backspace is in the middle of the * buffer, remove characters from buffer instead of sending backspace. */ public synchronized void setData(byte[] newData) { synchronized (dataSetSemaphore) { byte[] temp = null; if (dataWaiting.length == 0) { dataWaiting = newData; } else { temp = dataWaiting; dataWaiting = new byte[temp.length + newData.length]; System.arraycopy(temp, 0, dataWaiting, 0, temp.length); System.arraycopy(newData, 0, dataWaiting, temp.length, newData.length); } /* int arrayCnt = temp.length; int cnt; for (cnt=0; cnt<data.length; cnt++) { if (data[cnt] == TextConstants.BACKSPACE && arrayCnt > 0 && (int)this.data[arrayCnt-1] != 8) { arrayCnt--; } else { this.data[arrayCnt] = data[cnt]; arrayCnt++; } } if (arrayCnt != cnt+temp.length) { temp = this.data; this.data = new byte[arrayCnt]; System.arraycopy(temp, 0, this.data, 0, arrayCnt); } */ dataSetSemaphore.notify(); } } /** * Gets the data of this object. * Data is consumed it is retrieved. * This method blocks until data is available. * * @throws InterruptedException If the wait was interrupted. * @return The data. */ public synchronized byte[] getData() throws InterruptedException { // write methodname final String METHOD = "getData()"; // log when entering a method logger.entering(CLASS_NAME, METHOD); byte[] temp = null; wait(); try { temp = dataToSend; if (sendOnCR) { int containsCR = -100; // check if temp contains CR, and if it does you get the position of the first element containsCR = containsCR(temp); // if data does not contain CR if (containsCR == -1) { temp = new byte[0]; } // data contains CR else { logger.logp(Level.FINEST, CLASS_NAME, METHOD, "data contains one or more CR"); byte[] temp2 = temp; int lastPositionOfCR = containsCR; // while we don't find the last CR while((containsCR = getPositionOfNextCR(temp, lastPositionOfCR))>-1) { lastPositionOfCR = containsCR; } temp = new byte[lastPositionOfCR+3]; System.arraycopy(temp2, 0, temp, 0, temp.length); // if the data ended with an CR if(lastPositionOfCR+3 == temp2.length) { logger.logp(Level.FINEST, CLASS_NAME, METHOD, "the data ended with an CR"); dataToSend = new byte[0]; } // else we have to save the data after the last CR else { logger.logp(Level.FINEST, CLASS_NAME, METHOD, "the data ended with data after last CR"); dataToSend = new byte[temp2.length -(lastPositionOfCR + 3)]; System.arraycopy(temp2, lastPositionOfCR+3, dataToSend, 0, dataToSend.length); } } } // else don't wait for CR else { dataToSend = new byte[0]; } } catch(Throwable t) { logger.logp(Level.SEVERE, CLASS_NAME, METHOD, "unexpected throwable caught (swallowed), probably due to a bug", t); } finally { return temp; } } /* A Java byte has a value of -128 to 127. With eight bits and no sign, the negative numbers could be represented as a value of 128 to 255. This method makes such a conversion, but stores the result in an integer since Java does not support unsigned bytes. <p> @param aByte The byte with a possibly negative value. <p> @return An integer with a value of 0 to 255. <p> */ public static int byteToPositiveInt( byte aByte ) { int i = aByte ; if ( i < 0 ) { i += 256 ; } return i ; } /** * checks if a bytearray contains a CR (carrige return) * @param byte[] aDataArray the byte array to be examined * @return int first position of the CR, returns -1 if aDataArray is null or * does not contain a CR */ private int containsCR(byte[] aDataArray) { // if null or lenght<3, CR takes at least 3 bytes if(aDataArray==null || aDataArray.length<3) { return -1; } // else might contain CR, lets check else { // check for the value of CR in three bytes for (int i = 0; i < aDataArray.length-2; i++) { if (byteToPositiveInt(aDataArray[i]) == 0xE2 && byteToPositiveInt(aDataArray[i+1]) == 0x80 && byteToPositiveInt(aDataArray[i+2]) == 0xA8) { return i; } } // we have checked the bytearray and it did not contain CR return -1; } } /** * checks if for the position of next CR (carrige return) (if any) * @param byte[] aDataArray the byte array to be examined * @param int aStartPosition where to start looking for CR * @return int the first position of a CR from aStartPosition+3, * returns -1 if aDataArray is null or if aStartPosition+3 til end does not contain a CR * */ private int getPositionOfNextCR(byte[] aDataArray, int aStartPosition) { byte[] temp = null; int position = -1; if(aDataArray==null || aStartPosition>(aDataArray.length-1)) { return position; } else { temp = new byte[aDataArray.length-(aStartPosition+3)]; System.arraycopy(aDataArray, aStartPosition+3, temp, 0, temp.length); position = containsCR(temp); if(position==-1) { return position; } else { return aStartPosition+position+3; } } } /** * Empties the buffers. * */ public synchronized void empty() { dataWaiting = new byte[0]; dataToSend = new byte[0]; } /** * Handles buffer times. * * @todo CPS handling - According to RFC 4103, we must respect remote's * CPS demand. */ public void run() { // write methodname final String METHOD = "run()"; // log when entering a method logger.entering(CLASS_NAME, METHOD); while (running) { try { synchronized (dataSetSemaphore) { - if (dataToSend.length == 0) { + if (dataWaiting.length == 0) { dataSetSemaphore.wait(55000); } } } catch (InterruptedException ie) { - logger.logp(Level.WARNING, CLASS_NAME, METHOD, "Thread was interrupted, possible cause of to many BOM", ie); + logger.logp(Level.FINE, CLASS_NAME, METHOD, "Thread was interrupted, possible cause of hangup", ie); } // If nothing is sent in 55 seconds, send a zero width no break // space. This will prevent NATs closing the UDP hole. if (dataWaiting.length == 0) { setData(TextConstants.ZERO_WIDTH_NO_BREAK_SPACE); } logger.logp(Level.FINEST, CLASS_NAME, METHOD, "the buffertime is", new Integer(bufferTime)); while (dataWaiting.length > 0 || redGensToSend > 0) { try { Thread.sleep(bufferTime); } catch (InterruptedException ie) { } synchronized (this) { if (dataWaiting.length > 0) { if (dataToSend.length > 0) { byte[] temp = dataToSend; dataToSend = new byte[temp.length + dataWaiting.length]; System.arraycopy(temp, 0, dataToSend, 0, temp.length); System.arraycopy(dataWaiting, 0, dataToSend, temp.length, dataWaiting.length); } else { dataToSend = dataWaiting; } dataWaiting = new byte[0]; notify(); redGensToSend = redGen; } else if (redGensToSend > 0) { notify(); if (dataToSend.length == 0) { redGensToSend--; } } } } } logger.exiting(CLASS_NAME, METHOD); } /** * Sets the number of redundant generations. * * @param redGen The number of redundant generations to use, a value of * zero disables redundancy. */ public void setRedGen(int redGen) { this.redGen = redGen; } /** * Sets the buffer time. * * @param bufferTime The buffer time */ public void setBufferTime(int bufferTime) { this.bufferTime = bufferTime; } /** * Sets if the SynchBuffer should send on CR or realtime. * * @param boolean aSendOnCR should buffer send on CR */ public void setSendOnCR(boolean aSendOnCR) { this.sendOnCR = aSendOnCR; } /** * Gets if syncbuffer is set to send on CR. * * @return The boolean. */ public boolean getSendOnCR() { return sendOnCR; } /** * Gets the buffer time. * * @return The buffer time. */ public int getBufferTime() { return bufferTime; } }
false
true
public void run() { // write methodname final String METHOD = "run()"; // log when entering a method logger.entering(CLASS_NAME, METHOD); while (running) { try { synchronized (dataSetSemaphore) { if (dataToSend.length == 0) { dataSetSemaphore.wait(55000); } } } catch (InterruptedException ie) { logger.logp(Level.WARNING, CLASS_NAME, METHOD, "Thread was interrupted, possible cause of to many BOM", ie); } // If nothing is sent in 55 seconds, send a zero width no break // space. This will prevent NATs closing the UDP hole. if (dataWaiting.length == 0) { setData(TextConstants.ZERO_WIDTH_NO_BREAK_SPACE); } logger.logp(Level.FINEST, CLASS_NAME, METHOD, "the buffertime is", new Integer(bufferTime)); while (dataWaiting.length > 0 || redGensToSend > 0) { try { Thread.sleep(bufferTime); } catch (InterruptedException ie) { } synchronized (this) { if (dataWaiting.length > 0) { if (dataToSend.length > 0) { byte[] temp = dataToSend; dataToSend = new byte[temp.length + dataWaiting.length]; System.arraycopy(temp, 0, dataToSend, 0, temp.length); System.arraycopy(dataWaiting, 0, dataToSend, temp.length, dataWaiting.length); } else { dataToSend = dataWaiting; } dataWaiting = new byte[0]; notify(); redGensToSend = redGen; } else if (redGensToSend > 0) { notify(); if (dataToSend.length == 0) { redGensToSend--; } } } } } logger.exiting(CLASS_NAME, METHOD); }
public void run() { // write methodname final String METHOD = "run()"; // log when entering a method logger.entering(CLASS_NAME, METHOD); while (running) { try { synchronized (dataSetSemaphore) { if (dataWaiting.length == 0) { dataSetSemaphore.wait(55000); } } } catch (InterruptedException ie) { logger.logp(Level.FINE, CLASS_NAME, METHOD, "Thread was interrupted, possible cause of hangup", ie); } // If nothing is sent in 55 seconds, send a zero width no break // space. This will prevent NATs closing the UDP hole. if (dataWaiting.length == 0) { setData(TextConstants.ZERO_WIDTH_NO_BREAK_SPACE); } logger.logp(Level.FINEST, CLASS_NAME, METHOD, "the buffertime is", new Integer(bufferTime)); while (dataWaiting.length > 0 || redGensToSend > 0) { try { Thread.sleep(bufferTime); } catch (InterruptedException ie) { } synchronized (this) { if (dataWaiting.length > 0) { if (dataToSend.length > 0) { byte[] temp = dataToSend; dataToSend = new byte[temp.length + dataWaiting.length]; System.arraycopy(temp, 0, dataToSend, 0, temp.length); System.arraycopy(dataWaiting, 0, dataToSend, temp.length, dataWaiting.length); } else { dataToSend = dataWaiting; } dataWaiting = new byte[0]; notify(); redGensToSend = redGen; } else if (redGensToSend > 0) { notify(); if (dataToSend.length == 0) { redGensToSend--; } } } } } logger.exiting(CLASS_NAME, METHOD); }
diff --git a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java index de1a9fd7a..ca2627a8c 100644 --- a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java +++ b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/browser/FIBBrowserElementType.java @@ -1,508 +1,509 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenFlexo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.fib.view.widget.browser; import java.awt.Font; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.logging.Logger; import javax.swing.Icon; import org.openflexo.antar.binding.BindingEvaluationContext; import org.openflexo.antar.binding.BindingVariable; import org.openflexo.antar.binding.DataBinding; import org.openflexo.antar.expr.NotSettableContextException; import org.openflexo.antar.expr.NullReferenceException; import org.openflexo.antar.expr.TypeMismatchException; import org.openflexo.fib.controller.FIBController; import org.openflexo.fib.model.FIBAttributeNotification; import org.openflexo.fib.model.FIBBrowser; import org.openflexo.fib.model.FIBBrowserElement; import org.openflexo.fib.model.FIBBrowserElement.FIBBrowserElementChildren; import org.openflexo.fib.view.widget.FIBBrowserWidget; import org.openflexo.localization.FlexoLocalization; import org.openflexo.toolbox.ToolBox; import com.google.common.base.Function; import com.google.common.collect.Lists; public class FIBBrowserElementType implements BindingEvaluationContext, Observer { private final class CastFunction implements Function<Object, Object>, BindingEvaluationContext { private final FIBBrowserElementChildren children; private Object child; private CastFunction(FIBBrowserElementChildren children) { this.children = children; } @Override public synchronized Object apply(Object arg0) { child = arg0; try { Object result = null; try { result = children.getCast().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return result; } finally { child = null; } } @Override public Object getValue(BindingVariable variable) { if (variable.getVariableName().equals("child")) { return child; } else { return FIBBrowserElementType.this.getValue(variable); } } } private static final Logger logger = Logger.getLogger(FIBBrowserElementType.class.getPackage().getName()); private FIBBrowserModel fibBrowserModel; private FIBBrowserElement browserElementDefinition; private boolean isFiltered = false; private FIBController controller; public FIBBrowserElementType(FIBBrowserElement browserElementDefinition, FIBBrowserModel browserModel, FIBController controller) { super(); this.controller = controller; this.fibBrowserModel = browserModel; this.browserElementDefinition = browserElementDefinition; browserElementDefinition.addObserver(this); } public void delete() { if (browserElementDefinition != null) { browserElementDefinition.deleteObserver(this); } this.controller = null; this.browserElementDefinition = null; } public FIBBrowserModel getBrowserModel() { return fibBrowserModel; } @Override public void update(Observable o, Object arg) { if (arg instanceof FIBAttributeNotification && o == browserElementDefinition) { FIBAttributeNotification dataModification = (FIBAttributeNotification) arg; ((FIBBrowserWidget) controller.viewForComponent(browserElementDefinition.getBrowser())).updateBrowser(); } } public FIBController getController() { return controller; } public FIBBrowser getBrowser() { return browserElementDefinition.getBrowser(); } public String getLocalized(String key) { return FlexoLocalization.localizedForKey(getController().getLocalizerForComponent(getBrowser()), key); } protected void setModel(FIBBrowserModel model) { fibBrowserModel = model; } protected FIBBrowserModel getModel() { return fibBrowserModel; } public List<DataBinding<?>> getDependencyBindings(final Object object) { if (browserElementDefinition == null) { return null; } iteratorObject = object; List<DataBinding<?>> returned = new ArrayList<DataBinding<?>>(); returned.add(browserElementDefinition.getLabel()); returned.add(browserElementDefinition.getIcon()); returned.add(browserElementDefinition.getTooltip()); returned.add(browserElementDefinition.getEnabled()); returned.add(browserElementDefinition.getVisible()); for (FIBBrowserElementChildren children : browserElementDefinition.getChildren()) { returned.add(children.getData()); returned.add(children.getCast()); returned.add(children.getVisible()); } return returned; } public String getLabelFor(final Object object) { if (browserElementDefinition == null) { return "???" + object.toString(); } if (browserElementDefinition.getLabel().isSet()) { iteratorObject = object; try { return browserElementDefinition.getLabel().getBindingValue(this); } catch (TypeMismatchException e) { // System.out.println("While evaluating " + browserElementDefinition.getLabel()); e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return object.toString(); } public String getTooltipFor(final Object object) { if (browserElementDefinition == null) { return "???" + object.toString(); } if (browserElementDefinition.getTooltip().isSet()) { iteratorObject = object; try { return browserElementDefinition.getTooltip().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return browserElementDefinition.getName(); } public Icon getIconFor(final Object object) { if (browserElementDefinition == null) { return null; } if (browserElementDefinition.getIcon().isSet()) { iteratorObject = object; Object returned = null; try { returned = browserElementDefinition.getIcon().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (returned instanceof Icon) { return (Icon) returned; } return null; } else { return browserElementDefinition.getImageIcon(); } } public boolean isEnabled(final Object object) { if (browserElementDefinition == null) { return false; } if (browserElementDefinition.getEnabled().isSet()) { iteratorObject = object; Object enabledValue = null; try { enabledValue = browserElementDefinition.getEnabled().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (enabledValue != null) { return (Boolean) enabledValue; } return true; } else { return true; } } public boolean isVisible(final Object object) { if (browserElementDefinition == null) { return false; } if (isFiltered()) { return false; } if (browserElementDefinition.getVisible().isSet()) { iteratorObject = object; try { Boolean returned = browserElementDefinition.getVisible().getBindingValue(this); if (returned != null) { return returned; } return true; } catch (TypeMismatchException e) { e.printStackTrace(); return true; } catch (NullReferenceException e) { e.printStackTrace(); return true; } catch (InvocationTargetException e) { e.printStackTrace(); return true; } } else { return true; } } public List<Object> getChildrenFor(final Object object) { if (browserElementDefinition == null) { return Collections.EMPTY_LIST; } List<Object> returned = new ArrayList<Object>(); for (FIBBrowserElementChildren children : browserElementDefinition.getChildren()) { if (children.isMultipleAccess()) { // System.out.println("add all children for "+browserElementDefinition.getName()+" children "+children.getName()+" data="+children.getData()); // System.out.println("Obtain "+getChildrenListFor(children, object)); List<?> childrenObjects = getChildrenListFor(children, object); // Might be null if some visibility was declared if (childrenObjects != null) { returned.addAll(childrenObjects); } // System.out.println("For " + object + " of " + object.getClass().getSimpleName() + " children=" + children.getData() // + " values=" + object); } else { // System.out.println("add children for "+browserElementDefinition.getName()+" children "+children.getName()+" data="+children.getData()); // System.out.println("Obtain "+getChildrenFor(children, object)); // System.out.println("accessed type="+children.getAccessedType()); Object childrenObject = getChildrenFor(children, object); // Might be null if some visibility was declared if (childrenObject != null) { returned.add(childrenObject); } // System.out.println("For " + object + " of " + object.getClass().getSimpleName() + " children=" + children.getData() // + " value=" + childrenObject); } } return returned; } protected Object getChildrenFor(FIBBrowserElementChildren children, final Object object) { if (children.getData().isSet()) { iteratorObject = object; if (children.getVisible().isSet()) { boolean visible; try { visible = children.getVisible().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); visible = true; } catch (NullReferenceException e) { e.printStackTrace(); visible = true; } catch (InvocationTargetException e) { e.printStackTrace(); visible = true; } if (!visible) { // Finally we dont want to see it return null; } } Object result = null; try { result = children.getData().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (children.getCast().isSet()) { return new CastFunction(children).apply(result); } return result; } else { return null; } } protected List<?> getChildrenListFor(final FIBBrowserElementChildren children, final Object object) { if (children.getData().isSet() && children.isMultipleAccess()) { iteratorObject = object; if (children.getVisible().isSet()) { boolean visible; try { visible = children.getVisible().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); visible = true; } catch (NullReferenceException e) { e.printStackTrace(); visible = true; } catch (InvocationTargetException e) { e.printStackTrace(); visible = true; } if (!visible) { // Finally we dont want to see it return null; } } Object bindingValue = null; try { bindingValue = children.getData().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } List<?> list = ToolBox.getListFromIterable(bindingValue); - List returned = list; if (list != null && children.getCast().isSet()) { list = Lists.transform(list, new CastFunction(children)); + List returned = list; // Remove all occurences of null (caused by cast) /*while (list.contains(null)) { list.remove(null); }*/ if (list.contains(null)) { // The list contains null // We have to consider only non-null instances of elements, but we must avoid to destroy initial list: // This is the reason for what we have to clone the list while avoiding null elements returned = new ArrayList<Object>(); for (Object o : list) { if (o != null) { returned.add(o); } } } + return returned; } - return returned; + return list; } else { return null; } } public boolean isLabelEditable() { return getBrowserElement().getIsEditable() && getBrowserElement().getEditableLabel().isSet() && getBrowserElement().getEditableLabel().isSettable(); } public synchronized String getEditableLabelFor(final Object object) { if (isLabelEditable()) { iteratorObject = object; try { return browserElementDefinition.getEditableLabel().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return object.toString(); } public synchronized void setEditableLabelFor(final Object object, String value) { if (isLabelEditable()) { iteratorObject = object; try { browserElementDefinition.getEditableLabel().setBindingValue(value, this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NotSettableContextException e) { e.printStackTrace(); } } } protected Object iteratorObject; @Override public synchronized Object getValue(BindingVariable variable) { if (variable.getVariableName().equals(browserElementDefinition.getName())) { return iteratorObject; } else if (variable.getVariableName().equals("object")) { return iteratorObject; } else { return getController().getValue(variable); } } public FIBBrowserElement getBrowserElement() { return browserElementDefinition; } public Font getFont(final Object object) { if (browserElementDefinition.getDynamicFont().isSet()) { iteratorObject = object; try { return browserElementDefinition.getDynamicFont().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } if (getBrowserElement() != null) { return getBrowserElement().retrieveValidFont(); } return null; } public boolean isFiltered() { return isFiltered; } public void setFiltered(boolean isFiltered) { System.out.println("Element " + getBrowserElement().getName() + " filtered: " + isFiltered); if (this.isFiltered != isFiltered) { this.isFiltered = isFiltered; // Later, try to implement a way to rebuild tree with same expanded nodes fibBrowserModel.fireTreeRestructured(); } } }
false
true
protected List<?> getChildrenListFor(final FIBBrowserElementChildren children, final Object object) { if (children.getData().isSet() && children.isMultipleAccess()) { iteratorObject = object; if (children.getVisible().isSet()) { boolean visible; try { visible = children.getVisible().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); visible = true; } catch (NullReferenceException e) { e.printStackTrace(); visible = true; } catch (InvocationTargetException e) { e.printStackTrace(); visible = true; } if (!visible) { // Finally we dont want to see it return null; } } Object bindingValue = null; try { bindingValue = children.getData().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } List<?> list = ToolBox.getListFromIterable(bindingValue); List returned = list; if (list != null && children.getCast().isSet()) { list = Lists.transform(list, new CastFunction(children)); // Remove all occurences of null (caused by cast) /*while (list.contains(null)) { list.remove(null); }*/ if (list.contains(null)) { // The list contains null // We have to consider only non-null instances of elements, but we must avoid to destroy initial list: // This is the reason for what we have to clone the list while avoiding null elements returned = new ArrayList<Object>(); for (Object o : list) { if (o != null) { returned.add(o); } } } } return returned; } else {
protected List<?> getChildrenListFor(final FIBBrowserElementChildren children, final Object object) { if (children.getData().isSet() && children.isMultipleAccess()) { iteratorObject = object; if (children.getVisible().isSet()) { boolean visible; try { visible = children.getVisible().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); visible = true; } catch (NullReferenceException e) { e.printStackTrace(); visible = true; } catch (InvocationTargetException e) { e.printStackTrace(); visible = true; } if (!visible) { // Finally we dont want to see it return null; } } Object bindingValue = null; try { bindingValue = children.getData().getBindingValue(this); } catch (TypeMismatchException e) { e.printStackTrace(); } catch (NullReferenceException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } List<?> list = ToolBox.getListFromIterable(bindingValue); if (list != null && children.getCast().isSet()) { list = Lists.transform(list, new CastFunction(children)); List returned = list; // Remove all occurences of null (caused by cast) /*while (list.contains(null)) { list.remove(null); }*/ if (list.contains(null)) { // The list contains null // We have to consider only non-null instances of elements, but we must avoid to destroy initial list: // This is the reason for what we have to clone the list while avoiding null elements returned = new ArrayList<Object>(); for (Object o : list) { if (o != null) { returned.add(o); } } } return returned; } return list; } else {
diff --git a/de.xwic.appkit.webbase/src/de/xwic/appkit/webbase/table/filter/ColumnFilterControl.java b/de.xwic.appkit.webbase/src/de/xwic/appkit/webbase/table/filter/ColumnFilterControl.java index 6228e5e1..e5334ba1 100644 --- a/de.xwic.appkit.webbase/src/de/xwic/appkit/webbase/table/filter/ColumnFilterControl.java +++ b/de.xwic.appkit.webbase/src/de/xwic/appkit/webbase/table/filter/ColumnFilterControl.java @@ -1,509 +1,509 @@ /* * Copyright (c) 2009 Network Appliance, Inc. * All rights reserved. */ package de.xwic.appkit.webbase.table.filter; import java.util.List; import de.jwic.base.ControlContainer; import de.jwic.base.Event; import de.jwic.base.IControlContainer; import de.jwic.base.JavaScriptSupport; import de.jwic.controls.Button; import de.jwic.controls.LabelControl; import de.jwic.controls.RadioGroupControl; import de.jwic.ecolib.controls.StackedContainer; import de.jwic.ecolib.tableviewer.TableColumn; import de.jwic.ecolib.tableviewer.TableViewer; import de.jwic.events.ElementSelectedEvent; import de.jwic.events.ElementSelectedListener; import de.jwic.events.KeyEvent; import de.jwic.events.KeyListener; import de.jwic.events.SelectionEvent; import de.jwic.events.SelectionListener; import de.xwic.appkit.core.config.model.Property; import de.xwic.appkit.core.model.queries.PropertyQuery; import de.xwic.appkit.core.model.queries.QueryElement; import de.xwic.appkit.webbase.table.Column; import de.xwic.appkit.webbase.table.EntityTableExtensionHelper; import de.xwic.appkit.webbase.table.EntityTableModel; import de.xwic.appkit.webbase.table.columns.ColumnSelectorDialog; import de.xwic.appkit.webbase.toolkit.app.ExtendedApplication; import de.xwic.appkit.webbase.toolkit.util.ImageLibrary; /** * This control is placed inside of a balloon that is opened when a column is clicked. * @author lippisch */ @JavaScriptSupport public class ColumnFilterControl extends ControlContainer implements IFilterControlListener { private int positionIdx = 0; private Column column = null; private final EntityTableModel model; private TableViewer tblViewer; private StackedContainer filterStack; private DefaultFilter defFilter = null; private PicklistFilter plFilter = null; private DateFilter dateFilter = null; private NumberFilter numFilter = null; private LabelControl lblNoFilter = null; private AbstractFilterControl currentFilter = null; private BooleanFilter bolFilter = null; private AbstractFilterControl customFilter = null; private IFilterControlCreator customFilterCreator = null; private ColumnAction btFilterClear; // make these protected so we can hide them when we want from the custom filter protected ColumnAction btSortUp; protected ColumnAction btSortDown; private RadioGroupControl rdToogleBlanks; /** * @param container * @param name */ public ColumnFilterControl(IControlContainer container, String name, EntityTableModel model) { super(container, name); this.model = model; createButtons(); createFilters(); setVisible(false); // hidden by default. } /** * */ private void createFilters() { filterStack = new StackedContainer(this, "filters"); lblNoFilter = new LabelControl(filterStack, "noFilter"); lblNoFilter.setText("No filter options available"); defFilter = new DefaultFilter(filterStack, "default"); defFilter.addListener(this); plFilter = new PicklistFilter(filterStack, "plFilter"); plFilter.addListener(this); dateFilter = new DateFilter(filterStack, "dateFilter"); dateFilter.addListener(this); bolFilter = new BooleanFilter(filterStack, "bolFilter"); bolFilter.addListener(this); numFilter = new NumberFilter(filterStack, "numFilter"); numFilter.addListener(this); numFilter.addKeyPressedListener(new KeyListener() { @Override public void keyPressed(KeyEvent event) { actionOk(); } }); } /** * Returns the calculated height. * @return */ public int getHeight() { int height = 40; // base height if (btSortDown.isVisible()) height += 26; if (btSortUp.isVisible()) height += 26; if (rdToogleBlanks.isVisible()) height += 28; if (btFilterClear.isVisible()) height += 26; height += getFilterHeight(); return height; } /** * Returns the width of the filter control * @return */ public int getWidth() { if (currentFilter != null) { return currentFilter.getPreferredWidth() + 40; } return 300; } /** * Returns the height of the filter. * @return */ public int getFilterHeight() { if (currentFilter == null) { return 25; } else { return currentFilter.getPreferredHeight(); } } /** * Returns the width of the filter * @return */ public int getFilterWidth() { if (currentFilter != null) { return currentFilter.getPreferredWidth(); } return 264; } /** * */ private void createButtons() { Button btColSetup = new Button(this, "btColSetup"); btColSetup.setTitle(""); btColSetup.setIconEnabled(ImageLibrary.ICON_TABLE); btColSetup.setTooltip("Column Configuration"); btColSetup.setWidth(32); btColSetup.addSelectionListener(new SelectionListener() { @Override public void objectSelected(SelectionEvent event) { actionColumnConfiguration(); } }); Button btOk = new Button(this, "btOk"); btOk.setTitle("Ok"); btOk.setWidth(80); btOk.addSelectionListener(new SelectionListener() { @Override public void objectSelected(SelectionEvent event) { actionOk(); } }); Button btCancel = new Button(this, "btCancel"); btCancel.setTitle("Close"); btCancel.setWidth(80); btCancel.addSelectionListener(new SelectionListener() { @Override public void objectSelected(SelectionEvent event) { actionCancel(); } }); btSortUp = new ColumnAction(this, "btSortUp"); btSortUp.setTitle("Sort A to Z, 0-9"); btSortUp.setImage(ImageLibrary.ICON_SORT_AZ); btSortUp.addSelectionListener(new SelectionListener() { @Override public void objectSelected(SelectionEvent event) { actionSortUp(); } }); btSortDown = new ColumnAction(this, "btSortDown"); btSortDown.setTitle("Sort Z to A, 9-0"); btSortDown.setImage(ImageLibrary.ICON_SORT_ZA); btSortDown.addSelectionListener(new SelectionListener() { @Override public void objectSelected(SelectionEvent event) { actionSortDown(); } }); btFilterClear = new ColumnAction(this, "btFilterClear"); btFilterClear.setImage(ImageLibrary.ICON_TBL_FILTER_CLEAR); btFilterClear.setTitle("Remove active filter"); btFilterClear.addSelectionListener(new SelectionListener() { @Override public void objectSelected(SelectionEvent event) { actionClearFilter(); } }); rdToogleBlanks = new RadioGroupControl(this, "rdToogleBlanks"); rdToogleBlanks.addElement("Is Not Empty", "notNull"); rdToogleBlanks.addElement("Is Empty", "null"); rdToogleBlanks.addElement("All", "all"); rdToogleBlanks.setSelectedKey("all"); rdToogleBlanks.setChangeNotification(true); rdToogleBlanks.setCssClass(".radioButton"); rdToogleBlanks.addElementSelectedListener(new ElementSelectedListener() { @Override public void elementSelected(ElementSelectedEvent event) { String key = rdToogleBlanks.getSelectedKey(); if (key.equals("null")) { actionToogleNull(true); } else if (key.equals("notNull")) { actionToogleNull(false); } else { actionClearFilter(); } } }); } /** * Open Column Configuration. */ protected void actionColumnConfiguration() { ColumnSelectorDialog dialog = new ColumnSelectorDialog(ExtendedApplication.getInstance(this).getSite(), model); dialog.show(); hide(); } /** * */ protected void actionClearFilter() { model.updateFilter(column, null); hide(); } protected void hide() { setVisible(false); } /** * */ protected void actionSortDown() { model.sortColumn(column, Column.Sort.DOWN); hide(); } /** * */ protected void actionSortUp() { model.sortColumn(column, Column.Sort.UP); hide(); } /** * */ protected void actionCancel() { hide(); } /** * */ protected void actionOk() { if (currentFilter != null) { model.updateFilter(column, currentFilter.getQueryElement()); } hide(); } /** * @param isNull */ protected void actionToogleNull(boolean isNull) { PropertyQuery query = new PropertyQuery(); String property = column.getListColumn().getPropertyId(); if (isNull) { query.addEquals(property, null); } else { query.addNotEquals(property, null); } QueryElement qe = new QueryElement(QueryElement.AND, query); model.updateFilter(column, qe); hide(); } /** * Returns the title of the column. * @return */ public String getColumnTitle() { return column != null ? model.getBundle().getString(column.getTitleId()) : "No Column"; } /** * @return the column */ public Column getColumn() { return column; } /** * @param column the column to set */ public void setColumn(Column column) { this.column = column; } /** * @param tableColumn */ public void open(TableColumn tableColumn) { btSortUp.setVisible(true); btSortDown.setVisible(true); positionIdx = tableColumn.getIndex(); setColumn((Column) tableColumn.getUserObject()); - rdToogleBlanks.setVisible(!column.getListColumn().getFinalProperty().isCollection()); + rdToogleBlanks.setVisible((column.getListColumn().getFinalProperty() != null && !column.getListColumn().getFinalProperty().isCollection() ? true : false)); initializeRadio(); // choose the right filter currentFilter = null; //if (column.getPropertyIds() != null && column.getPropertyIds().length > 0) { Property finalProperty = column.getListColumn().getFinalProperty(); if (finalProperty == null) { return; } IFilterControlCreator fcc = null; // first look for a custom filter control for this specific field String fieldName = finalProperty.getEntityDescriptor().getClassname() + "." + finalProperty.getName(); fcc = EntityTableExtensionHelper.getFieldColumnFilterControl(fieldName); // if not found and the property is an entity, look for a custom filter control for the entity type String entityType = finalProperty.getEntityType(); if (fcc == null && finalProperty.isEntity()) { fcc = EntityTableExtensionHelper.getEntityColumnFilterControl(entityType); } if(fcc != null){ // if we found a custom filter control, use it if (customFilterCreator == null || !fcc.getClass().getName().equals(customFilterCreator.getClass().getName())) { // if different than the last custom filter control used, create an instance and use it as the customFilter customFilterCreator = fcc; filterStack.removeControl("customFilter"); customFilter = fcc.createFilterControl(filterStack, "customFilter"); customFilter.addListener(this); } currentFilter = customFilter; btSortUp.setTitle("Sort First to Last"); btSortDown.setTitle("Sort Last to First"); } else { if (finalProperty.isEntity()) { if (finalProperty.getPicklistId() != null) { currentFilter = plFilter; } else { currentFilter = defFilter; } btSortUp.setTitle("Sort A-Z, 0-9"); btSortDown.setTitle("Sort Z-A, 9-0"); } else if ("java.util.Date".equals(entityType)) { currentFilter = dateFilter; btSortUp.setTitle("Sort Oldest to Newest"); btSortDown.setTitle("Sort Newest to Oldest"); } else if ("java.lang.Boolean".equals(entityType) || "boolean".equals(entityType)) { currentFilter = bolFilter; btSortUp.setTitle("Sort False to True "); btSortDown.setTitle("Sort True to False"); rdToogleBlanks.setVisible(false); } else if ("int".equals(entityType) || "java.lang.Integer".equals(entityType) || "long".equals(entityType) || "java.lang.Long".equals(entityType) || "double".equals(entityType) || "java.lang.Double".equals(entityType)) { currentFilter = numFilter; btSortUp.setTitle("Sort 0-9"); btSortDown.setTitle("Sort 9-0"); } else if (finalProperty.isCollection()) { btSortUp.setVisible(false); btSortDown.setVisible(false); if (finalProperty.getPicklistId() != null) { // it's a picklist currentFilter = plFilter; } } else { currentFilter = defFilter; btSortUp.setTitle("Sort A-Z, 0-9"); btSortDown.setTitle("Sort Z-A, 9-0"); } } //} if (currentFilter != null) { currentFilter.initialize(column, column.getFilter()); filterStack.setCurrentControlName(currentFilter.getName()); } else { filterStack.setCurrentControlName(lblNoFilter.getName()); } btFilterClear.setVisible(column.getFilter() != null); setVisible(true); requireRedraw(); } /** * Initialize the radio button control to reflect the current filters */ protected void initializeRadio() { QueryElement qe = column.getFilter(); rdToogleBlanks.setSelectedKey("all"); if (qe != null && qe.getSubQuery() != null) { List<QueryElement> elements = qe.getSubQuery().getElements(); for (QueryElement elem : elements) { if (QueryElement.NOT_EQUALS.equals(elem.getOperation()) && elem.getValue() == null) { rdToogleBlanks.setSelectedKey("notNull"); break; } if (QueryElement.EQUALS.equals(elem.getOperation()) && elem.getValue() == null) { rdToogleBlanks.setSelectedKey("null"); break; } } } } /** * @return the positionIdx */ public int getPositionIdx() { return positionIdx; } /** * @param tblViewer */ public void setTableViewer(TableViewer tblViewer) { this.tblViewer = tblViewer; } /** * Returns the id of the tableViewer. * @return */ public String getTableViewerId() { return tblViewer.getControlID(); } /* * (non-Javadoc) * @see de.xwic.appkit.webbase.table.filter.IFilterControlListener#applyFilter(de.jwic.base.Event) */ @Override public void applyFilter(Event event) { actionOk(); } /** * Used in vtl * @return */ public boolean canToogleBlanks() { return rdToogleBlanks.isVisible(); } }
true
true
public void open(TableColumn tableColumn) { btSortUp.setVisible(true); btSortDown.setVisible(true); positionIdx = tableColumn.getIndex(); setColumn((Column) tableColumn.getUserObject()); rdToogleBlanks.setVisible(!column.getListColumn().getFinalProperty().isCollection()); initializeRadio(); // choose the right filter currentFilter = null; //if (column.getPropertyIds() != null && column.getPropertyIds().length > 0) { Property finalProperty = column.getListColumn().getFinalProperty(); if (finalProperty == null) { return; } IFilterControlCreator fcc = null; // first look for a custom filter control for this specific field String fieldName = finalProperty.getEntityDescriptor().getClassname() + "." + finalProperty.getName(); fcc = EntityTableExtensionHelper.getFieldColumnFilterControl(fieldName); // if not found and the property is an entity, look for a custom filter control for the entity type String entityType = finalProperty.getEntityType(); if (fcc == null && finalProperty.isEntity()) { fcc = EntityTableExtensionHelper.getEntityColumnFilterControl(entityType); } if(fcc != null){ // if we found a custom filter control, use it if (customFilterCreator == null || !fcc.getClass().getName().equals(customFilterCreator.getClass().getName())) { // if different than the last custom filter control used, create an instance and use it as the customFilter customFilterCreator = fcc; filterStack.removeControl("customFilter"); customFilter = fcc.createFilterControl(filterStack, "customFilter"); customFilter.addListener(this); } currentFilter = customFilter; btSortUp.setTitle("Sort First to Last"); btSortDown.setTitle("Sort Last to First"); } else { if (finalProperty.isEntity()) { if (finalProperty.getPicklistId() != null) { currentFilter = plFilter; } else { currentFilter = defFilter; } btSortUp.setTitle("Sort A-Z, 0-9"); btSortDown.setTitle("Sort Z-A, 9-0"); } else if ("java.util.Date".equals(entityType)) { currentFilter = dateFilter; btSortUp.setTitle("Sort Oldest to Newest"); btSortDown.setTitle("Sort Newest to Oldest"); } else if ("java.lang.Boolean".equals(entityType) || "boolean".equals(entityType)) { currentFilter = bolFilter; btSortUp.setTitle("Sort False to True "); btSortDown.setTitle("Sort True to False"); rdToogleBlanks.setVisible(false); } else if ("int".equals(entityType) || "java.lang.Integer".equals(entityType) || "long".equals(entityType) || "java.lang.Long".equals(entityType) || "double".equals(entityType) || "java.lang.Double".equals(entityType)) { currentFilter = numFilter; btSortUp.setTitle("Sort 0-9"); btSortDown.setTitle("Sort 9-0"); } else if (finalProperty.isCollection()) { btSortUp.setVisible(false); btSortDown.setVisible(false); if (finalProperty.getPicklistId() != null) { // it's a picklist currentFilter = plFilter; } } else { currentFilter = defFilter; btSortUp.setTitle("Sort A-Z, 0-9"); btSortDown.setTitle("Sort Z-A, 9-0"); } } //} if (currentFilter != null) { currentFilter.initialize(column, column.getFilter()); filterStack.setCurrentControlName(currentFilter.getName()); } else { filterStack.setCurrentControlName(lblNoFilter.getName()); } btFilterClear.setVisible(column.getFilter() != null); setVisible(true); requireRedraw(); }
public void open(TableColumn tableColumn) { btSortUp.setVisible(true); btSortDown.setVisible(true); positionIdx = tableColumn.getIndex(); setColumn((Column) tableColumn.getUserObject()); rdToogleBlanks.setVisible((column.getListColumn().getFinalProperty() != null && !column.getListColumn().getFinalProperty().isCollection() ? true : false)); initializeRadio(); // choose the right filter currentFilter = null; //if (column.getPropertyIds() != null && column.getPropertyIds().length > 0) { Property finalProperty = column.getListColumn().getFinalProperty(); if (finalProperty == null) { return; } IFilterControlCreator fcc = null; // first look for a custom filter control for this specific field String fieldName = finalProperty.getEntityDescriptor().getClassname() + "." + finalProperty.getName(); fcc = EntityTableExtensionHelper.getFieldColumnFilterControl(fieldName); // if not found and the property is an entity, look for a custom filter control for the entity type String entityType = finalProperty.getEntityType(); if (fcc == null && finalProperty.isEntity()) { fcc = EntityTableExtensionHelper.getEntityColumnFilterControl(entityType); } if(fcc != null){ // if we found a custom filter control, use it if (customFilterCreator == null || !fcc.getClass().getName().equals(customFilterCreator.getClass().getName())) { // if different than the last custom filter control used, create an instance and use it as the customFilter customFilterCreator = fcc; filterStack.removeControl("customFilter"); customFilter = fcc.createFilterControl(filterStack, "customFilter"); customFilter.addListener(this); } currentFilter = customFilter; btSortUp.setTitle("Sort First to Last"); btSortDown.setTitle("Sort Last to First"); } else { if (finalProperty.isEntity()) { if (finalProperty.getPicklistId() != null) { currentFilter = plFilter; } else { currentFilter = defFilter; } btSortUp.setTitle("Sort A-Z, 0-9"); btSortDown.setTitle("Sort Z-A, 9-0"); } else if ("java.util.Date".equals(entityType)) { currentFilter = dateFilter; btSortUp.setTitle("Sort Oldest to Newest"); btSortDown.setTitle("Sort Newest to Oldest"); } else if ("java.lang.Boolean".equals(entityType) || "boolean".equals(entityType)) { currentFilter = bolFilter; btSortUp.setTitle("Sort False to True "); btSortDown.setTitle("Sort True to False"); rdToogleBlanks.setVisible(false); } else if ("int".equals(entityType) || "java.lang.Integer".equals(entityType) || "long".equals(entityType) || "java.lang.Long".equals(entityType) || "double".equals(entityType) || "java.lang.Double".equals(entityType)) { currentFilter = numFilter; btSortUp.setTitle("Sort 0-9"); btSortDown.setTitle("Sort 9-0"); } else if (finalProperty.isCollection()) { btSortUp.setVisible(false); btSortDown.setVisible(false); if (finalProperty.getPicklistId() != null) { // it's a picklist currentFilter = plFilter; } } else { currentFilter = defFilter; btSortUp.setTitle("Sort A-Z, 0-9"); btSortDown.setTitle("Sort Z-A, 9-0"); } } //} if (currentFilter != null) { currentFilter.initialize(column, column.getFilter()); filterStack.setCurrentControlName(currentFilter.getName()); } else { filterStack.setCurrentControlName(lblNoFilter.getName()); } btFilterClear.setVisible(column.getFilter() != null); setVisible(true); requireRedraw(); }
diff --git a/faims-android-app/src/au/org/intersect/faims/android/ui/form/TabGroup.java b/faims-android-app/src/au/org/intersect/faims/android/ui/form/TabGroup.java index 03a28a4c..ef2b8fec 100644 --- a/faims-android-app/src/au/org/intersect/faims/android/ui/form/TabGroup.java +++ b/faims-android-app/src/au/org/intersect/faims/android/ui/form/TabGroup.java @@ -1,151 +1,153 @@ package au.org.intersect.faims.android.ui.form; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TabWidget; import au.org.intersect.faims.android.R; import au.org.intersect.faims.android.ui.activity.ShowProjectActivity; import au.org.intersect.faims.android.util.BeanShellLinker; public class TabGroup extends Fragment { private Context context; private TabHost tabHost; private HashMap<String, Tab> tabMap; private LinkedList<Tab> tabs; private List<String> onLoadCommands; private List<String> onShowCommands; private String label = ""; public TabGroup() { tabMap = new HashMap<String, Tab>(); tabs = new LinkedList<Tab>(); onLoadCommands = new ArrayList<String>(); onShowCommands = new ArrayList<String>(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("FAIMS","TabGroup: " + this.label + " onCreateView()"); if (tabHost == null){ tabHost = (TabHost) inflater.inflate(R.layout.tab_group, container, false); tabHost.setup(); for (Tab tab : tabs) { tabHost.addTab(tab.createTabSpec(tabHost)); } TabWidget widget = tabHost.getTabWidget(); - boolean first = true; - for (int i = 0; i < widget.getChildCount(); i++) { - Tab tab = tabs.get(i); - if (tab.getHidden()) { - widget.getChildAt(i).setVisibility(View.GONE); - } else if (first) { - tabHost.setCurrentTab(i); - first = false; + if (widget != null) { + boolean first = true; + for (int i = 0; i < widget.getChildCount(); i++) { + Tab tab = tabs.get(i); + if (tab.getHidden()) { + widget.getChildAt(i).setVisibility(View.GONE); + } else if (first) { + tabHost.setCurrentTab(i); + first = false; + } + } + if (first == true) { + // all tabs are hidden + // TODO: maybe hide the frame layout } - } - if (first == true) { - // all tabs are hidden - // TODO: maybe hide the frame layout } if(this.onLoadCommands.size() > 0){ executeCommands(this.onLoadCommands); } } if(this.onShowCommands.size() > 0){ executeCommands(this.onShowCommands); } // Solves a prob the back button gives us with the TabHost already having a parent if (tabHost.getParent() != null){ ((ViewGroup) tabHost.getParent()).removeView(tabHost); } return tabHost; } /* private TabSpec createTabSpec(TabHost tabHost, final String name) { TabSpec spec = tabHost.newTabSpec(name); spec.setIndicator(name); final ScrollView scrollView = new ScrollView(this.context); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); spec.setContent(new TabContentFactory() { @Override public View createTabContent(String tag) { TextView text = new TextView(context); text.setText(name); return text; } }); return spec; } */ public Tab createTab(String name, String label, boolean hidden) { Tab tab = new Tab(context, name, label, hidden); tabMap.put(name, tab); tabs.add(tab); return tab; } public void setContext(Context context) { this.context = context; } public void setLabel(String label) { this.label = label; } public String getLabel(){ return this.label; } public void addOnLoadCommand(String command){ this.onLoadCommands.add(command); } public void addOnShowCommand(String command){ this.onShowCommands.add(command); } private void executeCommands(List<String> commands){ BeanShellLinker linker = ((ShowProjectActivity) getActivity()).getBeanShellLinker(); for(String command : commands){ linker.execute(command); } } public LinkedList<Tab> getTabs() { return tabs; } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("FAIMS","TabGroup: " + this.label + " onCreateView()"); if (tabHost == null){ tabHost = (TabHost) inflater.inflate(R.layout.tab_group, container, false); tabHost.setup(); for (Tab tab : tabs) { tabHost.addTab(tab.createTabSpec(tabHost)); } TabWidget widget = tabHost.getTabWidget(); boolean first = true; for (int i = 0; i < widget.getChildCount(); i++) { Tab tab = tabs.get(i); if (tab.getHidden()) { widget.getChildAt(i).setVisibility(View.GONE); } else if (first) { tabHost.setCurrentTab(i); first = false; } } if (first == true) { // all tabs are hidden // TODO: maybe hide the frame layout } if(this.onLoadCommands.size() > 0){ executeCommands(this.onLoadCommands); } } if(this.onShowCommands.size() > 0){ executeCommands(this.onShowCommands); } // Solves a prob the back button gives us with the TabHost already having a parent if (tabHost.getParent() != null){ ((ViewGroup) tabHost.getParent()).removeView(tabHost); } return tabHost; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("FAIMS","TabGroup: " + this.label + " onCreateView()"); if (tabHost == null){ tabHost = (TabHost) inflater.inflate(R.layout.tab_group, container, false); tabHost.setup(); for (Tab tab : tabs) { tabHost.addTab(tab.createTabSpec(tabHost)); } TabWidget widget = tabHost.getTabWidget(); if (widget != null) { boolean first = true; for (int i = 0; i < widget.getChildCount(); i++) { Tab tab = tabs.get(i); if (tab.getHidden()) { widget.getChildAt(i).setVisibility(View.GONE); } else if (first) { tabHost.setCurrentTab(i); first = false; } } if (first == true) { // all tabs are hidden // TODO: maybe hide the frame layout } } if(this.onLoadCommands.size() > 0){ executeCommands(this.onLoadCommands); } } if(this.onShowCommands.size() > 0){ executeCommands(this.onShowCommands); } // Solves a prob the back button gives us with the TabHost already having a parent if (tabHost.getParent() != null){ ((ViewGroup) tabHost.getParent()).removeView(tabHost); } return tabHost; }
diff --git a/src/com/android/phone/BluetoothPhoneService.java b/src/com/android/phone/BluetoothPhoneService.java old mode 100644 new mode 100755 index e930488b..b25b8b22 --- a/src/com/android/phone/BluetoothPhoneService.java +++ b/src/com/android/phone/BluetoothPhoneService.java @@ -1,917 +1,918 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothHeadsetPhone; import android.content.Context; import android.content.Intent; import android.os.AsyncResult; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.SystemProperties; import android.telephony.PhoneNumberUtils; import android.telephony.ServiceState; import android.util.Log; import com.android.internal.telephony.Call; import com.android.internal.telephony.Connection; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.CallManager; import java.io.IOException; import java.util.LinkedList; import java.util.List; /** * Bluetooth headset manager for the Phone app. * @hide */ public class BluetoothPhoneService extends Service { private static final String TAG = "BluetoothPhoneService"; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // even more logging private BluetoothAdapter mAdapter; private CallManager mCM; private BluetoothHeadset mBluetoothHeadset; private PowerManager mPowerManager; private WakeLock mStartCallWakeLock; // held while waiting for the intent to start call private PhoneConstants.State mPhoneState = PhoneConstants.State.IDLE; CdmaPhoneCallState.PhoneCallState mCdmaThreeWayCallState = CdmaPhoneCallState.PhoneCallState.IDLE; private Call.State mForegroundCallState; private Call.State mRingingCallState; private CallNumber mRingNumber; // number of active calls int mNumActive; // number of background (held) calls int mNumHeld; long mBgndEarliestConnectionTime = 0; private boolean mRoam = false; // CDMA specific flag used in context with BT devices having display capabilities // to show which Caller is active. This state might not be always true as in CDMA // networks if a caller drops off no update is provided to the Phone. // This flag is just used as a toggle to provide a update to the BT device to specify // which caller is active. private boolean mCdmaIsSecondCallActive = false; private boolean mCdmaCallsSwapped = false; private long[] mClccTimestamps; // Timestamps associated with each clcc index private boolean[] mClccUsed; // Is this clcc index in use private static final int GSM_MAX_CONNECTIONS = 6; // Max connections allowed by GSM private static final int CDMA_MAX_CONNECTIONS = 2; // Max connections allowed by CDMA @Override public void onCreate() { super.onCreate(); mCM = CallManager.getInstance(); mAdapter = BluetoothAdapter.getDefaultAdapter(); if (mAdapter == null) { if (VDBG) Log.d(TAG, "mAdapter null"); return; } mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mStartCallWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + ":StartCall"); mStartCallWakeLock.setReferenceCounted(false); mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET); mForegroundCallState = Call.State.IDLE; mRingingCallState = Call.State.IDLE; mNumActive = 0; mNumHeld = 0; mRingNumber = new CallNumber("", 0);; mRoam = false; updateServiceState(mCM.getDefaultPhone().getServiceState()); handlePreciseCallStateChange(null); if(VDBG) Log.d(TAG, "registerForServiceStateChanged"); // register for updates // Use the service state of default phone as BT service state to // avoid situation such as no cell or wifi connection but still // reporting in service (since SipPhone always reports in service). mCM.getDefaultPhone().registerForServiceStateChanged(mHandler, SERVICE_STATE_CHANGED, null); mCM.registerForPreciseCallStateChanged(mHandler, PRECISE_CALL_STATE_CHANGED, null); mCM.registerForCallWaiting(mHandler, PHONE_CDMA_CALL_WAITING, null); // TODO(BT) registerForIncomingRing? // TODO(BT) registerdisconnection? mClccTimestamps = new long[GSM_MAX_CONNECTIONS]; mClccUsed = new boolean[GSM_MAX_CONNECTIONS]; for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) { mClccUsed[i] = false; } } @Override public void onStart(Intent intent, int startId) { if (mAdapter == null) { Log.w(TAG, "Stopping Bluetooth BluetoothPhoneService Service: device does not have BT"); stopSelf(); } if (VDBG) Log.d(TAG, "BluetoothPhoneService started"); } @Override public void onDestroy() { super.onDestroy(); if (DBG) log("Stopping Bluetooth BluetoothPhoneService Service"); } @Override public IBinder onBind(Intent intent) { return mBinder; } private static final int SERVICE_STATE_CHANGED = 1; private static final int PRECISE_CALL_STATE_CHANGED = 2; private static final int PHONE_CDMA_CALL_WAITING = 3; private static final int LIST_CURRENT_CALLS = 4; private static final int QUERY_PHONE_STATE = 5; private static final int CDMA_SWAP_SECOND_CALL_STATE = 6; private static final int CDMA_SET_SECOND_CALL_STATE = 7; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (VDBG) Log.d(TAG, "handleMessage: " + msg.what); switch(msg.what) { case SERVICE_STATE_CHANGED: ServiceState state = (ServiceState) ((AsyncResult) msg.obj).result; updateServiceState(state); break; case PRECISE_CALL_STATE_CHANGED: case PHONE_CDMA_CALL_WAITING: Connection connection = null; if (((AsyncResult) msg.obj).result instanceof Connection) { connection = (Connection) ((AsyncResult) msg.obj).result; } handlePreciseCallStateChange(connection); break; case LIST_CURRENT_CALLS: handleListCurrentCalls(); break; case QUERY_PHONE_STATE: handleQueryPhoneState(); break; case CDMA_SWAP_SECOND_CALL_STATE: handleCdmaSwapSecondCallState(); break; case CDMA_SET_SECOND_CALL_STATE: handleCdmaSetSecondCallState((Boolean) msg.obj); break; } } }; private void updateBtPhoneStateAfterRadioTechnologyChange() { if(VDBG) Log.d(TAG, "updateBtPhoneStateAfterRadioTechnologyChange..."); //Unregister all events from the old obsolete phone mCM.getDefaultPhone().unregisterForServiceStateChanged(mHandler); mCM.unregisterForPreciseCallStateChanged(mHandler); mCM.unregisterForCallWaiting(mHandler); //Register all events new to the new active phone mCM.getDefaultPhone().registerForServiceStateChanged(mHandler, SERVICE_STATE_CHANGED, null); mCM.registerForPreciseCallStateChanged(mHandler, PRECISE_CALL_STATE_CHANGED, null); mCM.registerForCallWaiting(mHandler, PHONE_CDMA_CALL_WAITING, null); } private void updateServiceState(ServiceState state) { boolean roam = state.getRoaming(); if (roam != mRoam) { mRoam = roam; if (mBluetoothHeadset != null) { mBluetoothHeadset.roamChanged(roam); } } } private void handlePreciseCallStateChange(Connection connection) { // get foreground call state int oldNumActive = mNumActive; int oldNumHeld = mNumHeld; Call.State oldRingingCallState = mRingingCallState; Call.State oldForegroundCallState = mForegroundCallState; CallNumber oldRingNumber = mRingNumber; Call foregroundCall = mCM.getActiveFgCall(); if (VDBG) Log.d(TAG, " handlePreciseCallStateChange: foreground: " + foregroundCall + " background: " + mCM.getFirstActiveBgCall() + " ringing: " + mCM.getFirstActiveRingingCall()); mForegroundCallState = foregroundCall.getState(); /* if in transition, do not update */ if (mForegroundCallState == Call.State.DISCONNECTING) { Log.d(TAG, "handlePreciseCallStateChange. Call disconnecting, wait before update"); return; } else mNumActive = (mForegroundCallState == Call.State.ACTIVE) ? 1 : 0; Call ringingCall = mCM.getFirstActiveRingingCall(); mRingingCallState = ringingCall.getState(); mRingNumber = getCallNumber(connection, ringingCall); if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { mNumHeld = getNumHeldCdma(); PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState = app.cdmaPhoneCallState.getPreviousCallState(); log("CDMA call state: " + currCdmaThreeWayCallState + " prev state:" + prevCdmaThreeWayCallState); - if (mCdmaThreeWayCallState != currCdmaThreeWayCallState) { + if ((mBluetoothHeadset != null) && + (mCdmaThreeWayCallState != currCdmaThreeWayCallState)) { // In CDMA, the network does not provide any feedback // to the phone when the 2nd MO call goes through the // stages of DIALING > ALERTING -> ACTIVE we fake the // sequence log("CDMA 3way call state change. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld + " IsThreeWayCallOrigStateDialing: " + app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); if ((currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { // Mimic dialing, put the call on hold, alerting mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.DIALING), mRingNumber.mNumber, mRingNumber.mType); mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.ALERTING), mRingNumber.mNumber, mRingNumber.mType); } // In CDMA, the network does not provide any feedback to // the phone when a user merges a 3way call or swaps // between two calls we need to send a CIEV response // indicating that a call state got changed which should // trigger a CLCC update request from the BT client. if (currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL && prevCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { log("CDMA 3way conf call. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld); mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(Call.State.IDLE, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } mCdmaThreeWayCallState = currCdmaThreeWayCallState; } } else { mNumHeld = getNumHeldUmts(); } boolean callsSwitched = false; if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && mCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { callsSwitched = mCdmaCallsSwapped; } else { Call backgroundCall = mCM.getFirstActiveBgCall(); callsSwitched = (mNumHeld == 1 && ! (backgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = backgroundCall.getEarliestConnectTime(); } if (mNumActive != oldNumActive || mNumHeld != oldNumHeld || mRingingCallState != oldRingingCallState || mForegroundCallState != oldForegroundCallState || !mRingNumber.equalTo(oldRingNumber) || callsSwitched) { if (mBluetoothHeadset != null) { mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(mRingingCallState, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } } private void handleListCurrentCalls() { Phone phone = mCM.getDefaultPhone(); int phoneType = phone.getPhoneType(); // TODO(BT) handle virtual call if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { listCurrentCallsCdma(); } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) { listCurrentCallsGsm(); } else { Log.e(TAG, "Unexpected phone type: " + phoneType); } // end the result // when index is 0, other parameter does not matter mBluetoothHeadset.clccResponse(0, 0, 0, 0, false, "", 0); } private void handleQueryPhoneState() { if (mBluetoothHeadset != null) { mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(mRingingCallState, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } private int getNumHeldUmts() { int countHeld = 0; List<Call> heldCalls = mCM.getBackgroundCalls(); for (Call call : heldCalls) { if (call.getState() == Call.State.HOLDING) { countHeld++; } } return countHeld; } private int getNumHeldCdma() { int numHeld = 0; PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState curr3WayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prev3WayCallState = app.cdmaPhoneCallState.getPreviousCallState(); log("CDMA call state: " + curr3WayCallState + " prev state:" + prev3WayCallState); if (curr3WayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (prev3WayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { numHeld = 0; //0: no calls held, as now *both* the caller are active } else { numHeld = 1; //1: held call and active call, as on answering a // Call Waiting, one of the caller *is* put on hold } } else if (curr3WayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { numHeld = 1; //1: held call and active call, as on make a 3 Way Call // the first caller *is* put on hold } else { numHeld = 0; //0: no calls held as this is a SINGLE_ACTIVE call } } return numHeld; } private CallNumber getCallNumber(Connection connection, Call call) { String number = null; int type = 128; // find phone number and type if (connection == null) { connection = call.getEarliestConnection(); if (connection == null) { Log.e(TAG, "Could not get a handle on Connection object for the call"); } } if (connection != null) { number = connection.getAddress(); if (number != null) { type = PhoneNumberUtils.toaFromString(number); } } if (number == null) { number = ""; } return new CallNumber(number, type); } private class CallNumber { private String mNumber = null; private int mType = 0; private CallNumber(String number, int type) { mNumber = number; mType = type; } private boolean equalTo(CallNumber callNumber) { if (mType != callNumber.mType) return false; if (mNumber != null && mNumber.compareTo(callNumber.mNumber) == 0) { return true; } return false; } } private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() { public void onServiceConnected(int profile, BluetoothProfile proxy) { mBluetoothHeadset = (BluetoothHeadset) proxy; } public void onServiceDisconnected(int profile) { mBluetoothHeadset = null; } }; private void listCurrentCallsGsm() { // Collect all known connections // clccConnections isindexed by CLCC index Connection[] clccConnections = new Connection[GSM_MAX_CONNECTIONS]; LinkedList<Connection> newConnections = new LinkedList<Connection>(); LinkedList<Connection> connections = new LinkedList<Connection>(); Call foregroundCall = mCM.getActiveFgCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); Call ringingCall = mCM.getFirstActiveRingingCall(); if (ringingCall.getState().isAlive()) { connections.addAll(ringingCall.getConnections()); } if (foregroundCall.getState().isAlive()) { connections.addAll(foregroundCall.getConnections()); } if (backgroundCall.getState().isAlive()) { connections.addAll(backgroundCall.getConnections()); } // Mark connections that we already known about boolean clccUsed[] = new boolean[GSM_MAX_CONNECTIONS]; for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) { clccUsed[i] = mClccUsed[i]; mClccUsed[i] = false; } for (Connection c : connections) { boolean found = false; long timestamp = c.getCreateTime(); for (int i = 0; i < GSM_MAX_CONNECTIONS; i++) { if (clccUsed[i] && timestamp == mClccTimestamps[i]) { mClccUsed[i] = true; found = true; clccConnections[i] = c; break; } } if (!found) { newConnections.add(c); } } // Find a CLCC index for new connections while (!newConnections.isEmpty()) { // Find lowest empty index int i = 0; while (mClccUsed[i]) i++; // Find earliest connection long earliestTimestamp = newConnections.get(0).getCreateTime(); Connection earliestConnection = newConnections.get(0); for (int j = 0; j < newConnections.size(); j++) { long timestamp = newConnections.get(j).getCreateTime(); if (timestamp < earliestTimestamp) { earliestTimestamp = timestamp; earliestConnection = newConnections.get(j); } } // update mClccUsed[i] = true; mClccTimestamps[i] = earliestTimestamp; clccConnections[i] = earliestConnection; newConnections.remove(earliestConnection); } // Send CLCC response to Bluetooth headset service for (int i = 0; i < clccConnections.length; i++) { if (mClccUsed[i]) { sendClccResponseGsm(i, clccConnections[i]); } } } /** Convert a Connection object into a single +CLCC result */ private void sendClccResponseGsm(int index, Connection connection) { int state = convertCallState(connection.getState()); boolean mpty = false; Call call = connection.getCall(); if (call != null) { mpty = call.isMultiparty(); } int direction = connection.isIncoming() ? 1 : 0; String number = connection.getAddress(); int type = -1; if (number != null) { type = PhoneNumberUtils.toaFromString(number); } mBluetoothHeadset.clccResponse(index + 1, direction, state, 0, mpty, number, type); } /** Build the +CLCC result for CDMA * The complexity arises from the fact that we need to maintain the same * CLCC index even as a call moves between states. */ private synchronized void listCurrentCallsCdma() { // In CDMA at one time a user can have only two live/active connections Connection[] clccConnections = new Connection[CDMA_MAX_CONNECTIONS];// indexed by CLCC index Call foregroundCall = mCM.getActiveFgCall(); Call ringingCall = mCM.getFirstActiveRingingCall(); Call.State ringingCallState = ringingCall.getState(); // If the Ringing Call state is INCOMING, that means this is the very first call // hence there should not be any Foreground Call if (ringingCallState == Call.State.INCOMING) { if (VDBG) log("Filling clccConnections[0] for INCOMING state"); clccConnections[0] = ringingCall.getLatestConnection(); } else if (foregroundCall.getState().isAlive()) { // Getting Foreground Call connection based on Call state if (ringingCall.isRinging()) { if (VDBG) log("Filling clccConnections[0] & [1] for CALL WAITING state"); clccConnections[0] = foregroundCall.getEarliestConnection(); clccConnections[1] = ringingCall.getLatestConnection(); } else { if (foregroundCall.getConnections().size() <= 1) { // Single call scenario if (VDBG) { log("Filling clccConnections[0] with ForgroundCall latest connection"); } clccConnections[0] = foregroundCall.getLatestConnection(); } else { // Multiple Call scenario. This would be true for both // CONF_CALL and THRWAY_ACTIVE state if (VDBG) { log("Filling clccConnections[0] & [1] with ForgroundCall connections"); } clccConnections[0] = foregroundCall.getEarliestConnection(); clccConnections[1] = foregroundCall.getLatestConnection(); } } } // Update the mCdmaIsSecondCallActive flag based on the Phone call state if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE) { Message msg = mHandler.obtainMessage(CDMA_SET_SECOND_CALL_STATE, false); mHandler.sendMessage(msg); } else if (PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { Message msg = mHandler.obtainMessage(CDMA_SET_SECOND_CALL_STATE, true); mHandler.sendMessage(msg); } // send CLCC result for (int i = 0; (i < clccConnections.length) && (clccConnections[i] != null); i++) { sendClccResponseCdma(i, clccConnections[i]); } } /** Send ClCC results for a Connection object for CDMA phone */ private void sendClccResponseCdma(int index, Connection connection) { int state; PhoneApp app = PhoneApp.getInstance(); CdmaPhoneCallState.PhoneCallState currCdmaCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaCallState = app.cdmaPhoneCallState.getPreviousCallState(); if ((prevCdmaCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && (currCdmaCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL)) { // If the current state is reached after merging two calls // we set the state of all the connections as ACTIVE state = CALL_STATE_ACTIVE; } else { Call.State callState = connection.getState(); switch (callState) { case ACTIVE: // For CDMA since both the connections are set as active by FW after accepting // a Call waiting or making a 3 way call, we need to set the state specifically // to ACTIVE/HOLDING based on the mCdmaIsSecondCallActive flag. This way the // CLCC result will allow BT devices to enable the swap or merge options if (index == 0) { // For the 1st active connection state = mCdmaIsSecondCallActive ? CALL_STATE_HELD : CALL_STATE_ACTIVE; } else { // for the 2nd active connection state = mCdmaIsSecondCallActive ? CALL_STATE_ACTIVE : CALL_STATE_HELD; } break; case HOLDING: state = CALL_STATE_HELD; break; case DIALING: state = CALL_STATE_DIALING; break; case ALERTING: state = CALL_STATE_ALERTING; break; case INCOMING: state = CALL_STATE_INCOMING; break; case WAITING: state = CALL_STATE_WAITING; break; default: Log.e(TAG, "bad call state: " + callState); return; } } boolean mpty = false; if (currCdmaCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (prevCdmaCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { // If the current state is reached after merging two calls // we set the multiparty call true. mpty = true; } // else // CALL_CONF state is not from merging two calls, but from // accepting the second call. In this case first will be on // hold in most cases but in some cases its already merged. // However, we will follow the common case and the test case // as per Bluetooth SIG PTS } int direction = connection.isIncoming() ? 1 : 0; String number = connection.getAddress(); int type = -1; if (number != null) { type = PhoneNumberUtils.toaFromString(number); } else { number = ""; } mBluetoothHeadset.clccResponse(index + 1, direction, state, 0, mpty, number, type); } private void handleCdmaSwapSecondCallState() { if (VDBG) log("cdmaSwapSecondCallState: Toggling mCdmaIsSecondCallActive"); mCdmaIsSecondCallActive = !mCdmaIsSecondCallActive; mCdmaCallsSwapped = true; } private void handleCdmaSetSecondCallState(boolean state) { if (VDBG) log("cdmaSetSecondCallState: Setting mCdmaIsSecondCallActive to " + state); mCdmaIsSecondCallActive = state; if (!mCdmaIsSecondCallActive) { mCdmaCallsSwapped = false; } } private final IBluetoothHeadsetPhone.Stub mBinder = new IBluetoothHeadsetPhone.Stub() { public boolean answerCall() { return PhoneUtils.answerCall(mCM.getFirstActiveRingingCall()); } public boolean hangupCall() { if (mCM.hasActiveFgCall()) { return PhoneUtils.hangupActiveCall(mCM.getActiveFgCall()); } else if (mCM.hasActiveRingingCall()) { return PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall()); } else if (mCM.hasActiveBgCall()) { return PhoneUtils.hangupHoldingCall(mCM.getFirstActiveBgCall()); } // TODO(BT) handle virtual voice call return false; } public boolean sendDtmf(int dtmf) { return mCM.sendDtmf((char) dtmf); } public boolean processChld(int chld) { Phone phone = mCM.getDefaultPhone(); int phoneType = phone.getPhoneType(); Call ringingCall = mCM.getFirstActiveRingingCall(); Call backgroundCall = mCM.getFirstActiveBgCall(); if (chld == CHLD_TYPE_RELEASEHELD) { if (ringingCall.isRinging()) { return PhoneUtils.hangupRingingCall(ringingCall); } else { return PhoneUtils.hangupHoldingCall(backgroundCall); } } else if (chld == CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD) { if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { if (ringingCall.isRinging()) { // Hangup the active call and then answer call waiting call. if (VDBG) log("CHLD:1 Callwaiting Answer call"); PhoneUtils.hangupRingingAndActive(phone); } else { // If there is no Call waiting then just hangup // the active call. In CDMA this mean that the complete // call session would be ended if (VDBG) log("CHLD:1 Hangup Call"); PhoneUtils.hangup(PhoneApp.getInstance().mCM); } return true; } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) { // Hangup active call, answer held call return PhoneUtils.answerAndEndActive(PhoneApp.getInstance().mCM, ringingCall); } else { Log.e(TAG, "bad phone type: " + phoneType); return false; } } else if (chld == CHLD_TYPE_HOLDACTIVE_ACCEPTHELD) { if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { // For CDMA, the way we switch to a new incoming call is by // calling PhoneUtils.answerCall(). switchAndHoldActive() won't // properly update the call state within telephony. // If the Phone state is already in CONF_CALL then we simply send // a flash cmd by calling switchHoldingAndActive() if (ringingCall.isRinging()) { if (VDBG) log("CHLD:2 Callwaiting Answer call"); PhoneUtils.answerCall(ringingCall); PhoneUtils.setMute(false); // Setting the second callers state flag to TRUE (i.e. active) cdmaSetSecondCallState(true); return true; } else if (PhoneApp.getInstance().cdmaPhoneCallState .getCurrentCallState() == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { if (VDBG) log("CHLD:2 Swap Calls"); PhoneUtils.switchHoldingAndActive(backgroundCall); // Toggle the second callers active state flag cdmaSwapSecondCallState(); return true; } Log.e(TAG, "CDMA fail to do hold active and accept held"); return false; } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) { PhoneUtils.switchHoldingAndActive(backgroundCall); return true; } else { Log.e(TAG, "Unexpected phone type: " + phoneType); return false; } } else if (chld == CHLD_TYPE_ADDHELDTOCONF) { if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) { CdmaPhoneCallState.PhoneCallState state = PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState(); // For CDMA, we need to check if the call is in THRWAY_ACTIVE state if (state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { if (VDBG) log("CHLD:3 Merge Calls"); PhoneUtils.mergeCalls(); return true; } else if (state == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { // State is CONF_CALL already and we are getting a merge call // This can happen when CONF_CALL was entered from a Call Waiting // TODO(BT) return false; } Log.e(TAG, "GSG no call to add conference"); return false; } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) { if (mCM.hasActiveFgCall() && mCM.hasActiveBgCall()) { PhoneUtils.mergeCalls(); return true; } else { Log.e(TAG, "GSG no call to merge"); return false; } } else { Log.e(TAG, "Unexpected phone type: " + phoneType); return false; } } else { Log.e(TAG, "bad CHLD value: " + chld); return false; } } public String getNetworkOperator() { return mCM.getDefaultPhone().getServiceState().getOperatorAlphaLong(); } public String getSubscriberNumber() { return mCM.getDefaultPhone().getLine1Number(); } public boolean listCurrentCalls() { Message msg = Message.obtain(mHandler, LIST_CURRENT_CALLS); mHandler.sendMessage(msg); return true; } public boolean queryPhoneState() { Message msg = Message.obtain(mHandler, QUERY_PHONE_STATE); mHandler.sendMessage(msg); return true; } public void updateBtHandsfreeAfterRadioTechnologyChange() { if (VDBG) Log.d(TAG, "updateBtHandsfreeAfterRadioTechnologyChange..."); updateBtPhoneStateAfterRadioTechnologyChange(); } public void cdmaSwapSecondCallState() { Message msg = Message.obtain(mHandler, CDMA_SWAP_SECOND_CALL_STATE); mHandler.sendMessage(msg); } public void cdmaSetSecondCallState(boolean state) { Message msg = mHandler.obtainMessage(CDMA_SET_SECOND_CALL_STATE, state); mHandler.sendMessage(msg); } }; // match up with bthf_call_state_t of bt_hf.h final static int CALL_STATE_ACTIVE = 0; final static int CALL_STATE_HELD = 1; final static int CALL_STATE_DIALING = 2; final static int CALL_STATE_ALERTING = 3; final static int CALL_STATE_INCOMING = 4; final static int CALL_STATE_WAITING = 5; final static int CALL_STATE_IDLE = 6; // match up with bthf_chld_type_t of bt_hf.h final static int CHLD_TYPE_RELEASEHELD = 0; final static int CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD = 1; final static int CHLD_TYPE_HOLDACTIVE_ACCEPTHELD = 2; final static int CHLD_TYPE_ADDHELDTOCONF = 3; /* Convert telephony phone call state into hf hal call state */ static int convertCallState(Call.State ringingState, Call.State foregroundState) { if ((ringingState == Call.State.INCOMING) || (ringingState == Call.State.WAITING) ) return CALL_STATE_INCOMING; else if (foregroundState == Call.State.DIALING) return CALL_STATE_DIALING; else if (foregroundState == Call.State.ALERTING) return CALL_STATE_ALERTING; else return CALL_STATE_IDLE; } static int convertCallState(Call.State callState) { switch (callState) { case IDLE: case DISCONNECTED: case DISCONNECTING: return CALL_STATE_IDLE; case ACTIVE: return CALL_STATE_ACTIVE; case HOLDING: return CALL_STATE_HELD; case DIALING: return CALL_STATE_DIALING; case ALERTING: return CALL_STATE_ALERTING; case INCOMING: return CALL_STATE_INCOMING; case WAITING: return CALL_STATE_WAITING; default: Log.e(TAG, "bad call state: " + callState); return CALL_STATE_IDLE; } } private static void log(String msg) { Log.d(TAG, msg); } }
true
true
private void handlePreciseCallStateChange(Connection connection) { // get foreground call state int oldNumActive = mNumActive; int oldNumHeld = mNumHeld; Call.State oldRingingCallState = mRingingCallState; Call.State oldForegroundCallState = mForegroundCallState; CallNumber oldRingNumber = mRingNumber; Call foregroundCall = mCM.getActiveFgCall(); if (VDBG) Log.d(TAG, " handlePreciseCallStateChange: foreground: " + foregroundCall + " background: " + mCM.getFirstActiveBgCall() + " ringing: " + mCM.getFirstActiveRingingCall()); mForegroundCallState = foregroundCall.getState(); /* if in transition, do not update */ if (mForegroundCallState == Call.State.DISCONNECTING) { Log.d(TAG, "handlePreciseCallStateChange. Call disconnecting, wait before update"); return; } else mNumActive = (mForegroundCallState == Call.State.ACTIVE) ? 1 : 0; Call ringingCall = mCM.getFirstActiveRingingCall(); mRingingCallState = ringingCall.getState(); mRingNumber = getCallNumber(connection, ringingCall); if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { mNumHeld = getNumHeldCdma(); PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState = app.cdmaPhoneCallState.getPreviousCallState(); log("CDMA call state: " + currCdmaThreeWayCallState + " prev state:" + prevCdmaThreeWayCallState); if (mCdmaThreeWayCallState != currCdmaThreeWayCallState) { // In CDMA, the network does not provide any feedback // to the phone when the 2nd MO call goes through the // stages of DIALING > ALERTING -> ACTIVE we fake the // sequence log("CDMA 3way call state change. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld + " IsThreeWayCallOrigStateDialing: " + app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); if ((currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { // Mimic dialing, put the call on hold, alerting mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.DIALING), mRingNumber.mNumber, mRingNumber.mType); mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.ALERTING), mRingNumber.mNumber, mRingNumber.mType); } // In CDMA, the network does not provide any feedback to // the phone when a user merges a 3way call or swaps // between two calls we need to send a CIEV response // indicating that a call state got changed which should // trigger a CLCC update request from the BT client. if (currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL && prevCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { log("CDMA 3way conf call. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld); mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(Call.State.IDLE, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } mCdmaThreeWayCallState = currCdmaThreeWayCallState; } } else { mNumHeld = getNumHeldUmts(); } boolean callsSwitched = false; if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && mCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { callsSwitched = mCdmaCallsSwapped; } else { Call backgroundCall = mCM.getFirstActiveBgCall(); callsSwitched = (mNumHeld == 1 && ! (backgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = backgroundCall.getEarliestConnectTime(); } if (mNumActive != oldNumActive || mNumHeld != oldNumHeld || mRingingCallState != oldRingingCallState || mForegroundCallState != oldForegroundCallState || !mRingNumber.equalTo(oldRingNumber) || callsSwitched) { if (mBluetoothHeadset != null) { mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(mRingingCallState, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } }
private void handlePreciseCallStateChange(Connection connection) { // get foreground call state int oldNumActive = mNumActive; int oldNumHeld = mNumHeld; Call.State oldRingingCallState = mRingingCallState; Call.State oldForegroundCallState = mForegroundCallState; CallNumber oldRingNumber = mRingNumber; Call foregroundCall = mCM.getActiveFgCall(); if (VDBG) Log.d(TAG, " handlePreciseCallStateChange: foreground: " + foregroundCall + " background: " + mCM.getFirstActiveBgCall() + " ringing: " + mCM.getFirstActiveRingingCall()); mForegroundCallState = foregroundCall.getState(); /* if in transition, do not update */ if (mForegroundCallState == Call.State.DISCONNECTING) { Log.d(TAG, "handlePreciseCallStateChange. Call disconnecting, wait before update"); return; } else mNumActive = (mForegroundCallState == Call.State.ACTIVE) ? 1 : 0; Call ringingCall = mCM.getFirstActiveRingingCall(); mRingingCallState = ringingCall.getState(); mRingNumber = getCallNumber(connection, ringingCall); if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { mNumHeld = getNumHeldCdma(); PhoneApp app = PhoneApp.getInstance(); if (app.cdmaPhoneCallState != null) { CdmaPhoneCallState.PhoneCallState currCdmaThreeWayCallState = app.cdmaPhoneCallState.getCurrentCallState(); CdmaPhoneCallState.PhoneCallState prevCdmaThreeWayCallState = app.cdmaPhoneCallState.getPreviousCallState(); log("CDMA call state: " + currCdmaThreeWayCallState + " prev state:" + prevCdmaThreeWayCallState); if ((mBluetoothHeadset != null) && (mCdmaThreeWayCallState != currCdmaThreeWayCallState)) { // In CDMA, the network does not provide any feedback // to the phone when the 2nd MO call goes through the // stages of DIALING > ALERTING -> ACTIVE we fake the // sequence log("CDMA 3way call state change. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld + " IsThreeWayCallOrigStateDialing: " + app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()); if ((currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) && app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing()) { // Mimic dialing, put the call on hold, alerting mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.DIALING), mRingNumber.mNumber, mRingNumber.mType); mBluetoothHeadset.phoneStateChanged(0, mNumHeld, convertCallState(Call.State.IDLE, Call.State.ALERTING), mRingNumber.mNumber, mRingNumber.mType); } // In CDMA, the network does not provide any feedback to // the phone when a user merges a 3way call or swaps // between two calls we need to send a CIEV response // indicating that a call state got changed which should // trigger a CLCC update request from the BT client. if (currCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL && prevCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) { log("CDMA 3way conf call. mNumActive: " + mNumActive + " mNumHeld: " + mNumHeld); mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(Call.State.IDLE, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } mCdmaThreeWayCallState = currCdmaThreeWayCallState; } } else { mNumHeld = getNumHeldUmts(); } boolean callsSwitched = false; if (mCM.getDefaultPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && mCdmaThreeWayCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) { callsSwitched = mCdmaCallsSwapped; } else { Call backgroundCall = mCM.getFirstActiveBgCall(); callsSwitched = (mNumHeld == 1 && ! (backgroundCall.getEarliestConnectTime() == mBgndEarliestConnectionTime)); mBgndEarliestConnectionTime = backgroundCall.getEarliestConnectTime(); } if (mNumActive != oldNumActive || mNumHeld != oldNumHeld || mRingingCallState != oldRingingCallState || mForegroundCallState != oldForegroundCallState || !mRingNumber.equalTo(oldRingNumber) || callsSwitched) { if (mBluetoothHeadset != null) { mBluetoothHeadset.phoneStateChanged(mNumActive, mNumHeld, convertCallState(mRingingCallState, mForegroundCallState), mRingNumber.mNumber, mRingNumber.mType); } } }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/MessagingManager.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/MessagingManager.java index 81e86e031..c9e220a69 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/MessagingManager.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/MessagingManager.java @@ -1,463 +1,463 @@ /* * DPP - Serious Distributed Pair Programming * (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006 * (c) Riad Djemili - 2006 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package de.fu_berlin.inf.dpp; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Display; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smackx.MessageEventManager; import org.jivesoftware.smackx.muc.InvitationListener; import org.jivesoftware.smackx.muc.MultiUserChat; import de.fu_berlin.inf.dpp.Saros.ConnectionState; import de.fu_berlin.inf.dpp.net.IConnectionListener; import de.fu_berlin.inf.dpp.net.JID; import de.fu_berlin.inf.dpp.net.internal.MultiUserChatManager; import de.fu_berlin.inf.dpp.ui.MessagingWindow; /** * MessagingManager handles all instant messaging related communications. * * @author rdjemili */ public class MessagingManager implements PacketListener, MessageListener, IConnectionListener, InvitationListener { private static Logger log = Logger.getLogger(MessagingManager.class .getName()); MessageEventManager messageEventManager; MultiUserChatManager multitrans = null; private final String CHAT_ROOM = "saros"; public class ChatLine { public String sender; public String text; public Date date; public String packedID; } /** * Encapsulates the interface that is needed by the MessagingWindow. */ public interface SessionProvider { public List<ChatLine> getHistory(); public String getName(); public void sendMessage(String msg); } /** * Sessions are one-to-one IM chat sessions. Sessions are responsible for * * Since all sessions already handle their incoming messages, this method is * only to handle incoming chat messages for which no sessions have been yet * created. If it finds a chat message that belongs to no current session, * it creates a new session. sending and receiving their messages. They also * handle their IM chat window and save their history, even when their chat * windows are disposed and reopened again. * * TODO CJ: Rework needed, we don't want one-to-one chats anymore * * wanted: messages to all developers of programming session use this class * as fallback if muc fails? */ public class ChatSession implements SessionProvider, MessageListener { private final Logger logCH = Logger.getLogger(ChatSession.class .getName()); private final String name; private final Chat chat; private final JID participant; private MessagingWindow window; // is null if disposed private final List<ChatLine> history = new ArrayList<ChatLine>(); public ChatSession(Chat chat, String name) { this.chat = chat; this.name = name; this.participant = new JID(chat.getParticipant()); chat.addMessageListener(this); openWindow(); } public String getName() { return this.name; } public List<ChatLine> getHistory() { return this.history; } /** * @return the participant associated to the chat object. */ public JID getParticipant() { return this.participant; } public void processPacket(Packet packet) { this.logCH.debug("processPacket called"); final Message message = (Message) packet; if (message.getBody() == null) { return; } Display.getDefault().syncExec(new Runnable() { public void run() { openWindow(); addChatLine(ChatSession.this.name, message.getBody()); } }); } public void processMessage(Chat chat, Message message) { // TODO: new Method for messagelistener this.logCH.debug("processMessage called."); processPacket(message); } /** * Opens the chat window for this chat session. Refocuses the window if * it is already opened. */ public void openWindow() { if (this.window == null) { this.window = new MessagingWindow(this); this.window.open(); this.window.getShell().addDisposeListener( new DisposeListener() { public void widgetDisposed(DisposeEvent e) { ChatSession.this.window = null; } }); } this.window.getShell().forceActive(); this.window.getShell().forceFocus(); } /* * @see de.fu_berlin.inf.dpp.MessagingManager.SessionProvider */ public void sendMessage(String text) { try { Message msg = new Message(); msg.setBody(text); // send via muc process this.chat.sendMessage(msg); // for Testing addChatLine(Saros.getDefault().getMyJID().getName(), text); } catch (XMPPException e1) { e1.printStackTrace(); addChatLine("error", "Couldn't send message"); } } private void addChatLine(String sender, String text) { ChatLine chatLine = new ChatLine(); chatLine.sender = sender; chatLine.text = text; chatLine.date = new Date(); this.history.add(chatLine); this.window.addChatLine(chatLine); for (IChatListener chatListener : MessagingManager.this.chatListeners) { chatListener.chatMessageAdded(sender, text); } } } public class MultiChatSession implements SessionProvider, PacketListener, MessageListener { private final Logger logCH = Logger.getLogger(ChatSession.class .getName()); private final String name; private final MultiUserChat muc; private JID participant; private MessagingWindow window; // is null if disposed private final List<ChatLine> history = new ArrayList<ChatLine>(); public MultiChatSession(MultiUserChat muc) { this.muc = muc; this.name = "Multi User Chat (" + Saros.getDefault().getMyJID().getName() + ")"; muc.addMessageListener(this); } public String getName() { return this.name; } public List<ChatLine> getHistory() { return this.history; } /** * @return the participant associated to the chat object. */ public JID getParticipant() { return this.participant; } public void processPacket(Packet packet) { this.logCH.debug("processPacket called"); final Message message = (Message) packet; if (message.getBody() == null) { return; } // notify chat listener MessagingManager.log.debug("Notify Listener.."); for (IChatListener l : MessagingManager.this.chatListeners) { l.chatMessageAdded(message.getFrom(), message.getBody()); MessagingManager.log.debug("Notified Listener"); } } public void processMessage(Chat chat, Message message) { this.logCH.debug("processMessage called."); processPacket(message); } /* * @see de.fu_berlin.inf.dpp.MessagingManager.SessionProvider */ public void sendMessage(String text) { try { Message msg = this.muc.createMessage(); msg.setBody(text); if (this.muc != null) { this.muc.sendMessage(msg); } } catch (XMPPException e1) { e1.printStackTrace(); addChatLine("error", "Couldn't send message"); } } private void addChatLine(String sender, String text) { ChatLine chatLine = new ChatLine(); chatLine.sender = sender; chatLine.text = text; chatLine.date = new Date(); this.history.add(chatLine); this.window.addChatLine(chatLine); for (IChatListener chatListener : MessagingManager.this.chatListeners) { chatListener.chatMessageAdded(sender, text); } } } /** * Listener for incoming chat messages. */ public interface IChatListener { public void chatMessageAdded(String sender, String message); } private final List<ChatSession> sessions = new ArrayList<ChatSession>(); private MultiChatSession multiSession; private final List<IChatListener> chatListeners = new ArrayList<IChatListener>(); private MultiChatSession session; public MessagingManager() { Saros.getDefault().addListener(this); this.multitrans = new MultiUserChatManager(this.CHAT_ROOM); } /* * (non-Javadoc) * * @see de.fu_berlin.inf.dpp.listeners.IConnectionListener */ public void connectionStateChanged(XMPPConnection connection, ConnectionState newState) { if ((connection != null) && (newState == ConnectionState.NOT_CONNECTED)) { // TODO CJ Review: connection.removePacketListener(this); log.debug("unconnect"); } if (newState == ConnectionState.CONNECTED) { connection.addPacketListener(this, new MessageTypeFilter( Message.Type.chat)); initMultiChatListener(); } } /** * Since all sessions already handle their incoming messages, this method is * only to handle incoming chat messages for which no sessions have been yet * created. If it finds a chat message that belongs to no current session, * it creates a new session. * * @see org.jivesoftware.smack.PacketListener */ public void processPacket(Packet packet) { - MessagingManager.log.debug("messagePacket called"); + MessagingManager.log.trace("processPacket called"); final Message message = (Message) packet; final JID jid = new JID(message.getFrom()); if (message.getBody() == null) { return; } /* check for multi or single chat. */ if (message.getFrom().contains(this.multitrans.getRoomName())) { if (this.multiSession == null) { this.multiSession = new MultiChatSession(this.multitrans .getMUC()); this.multiSession.processPacket(message); } } else { /* old chat based message communication. */ for (ChatSession session : this.sessions) { if (jid.equals(session.getParticipant())) { return; // gets already handled by message handler in // session } } } } public void processMessage(Chat chat, Message message) { // TODO new method for message notify MessagingManager.log.debug("processMessage called."); processPacket(message); } /** * Adds the chat listener. */ public void addChatListener(IChatListener listener) { this.chatListeners.add(listener); } // TODO CJ Rework needed public void invitationReceived(XMPPConnection conn, String room, String inviter, String reason, String password, Message message) { try { // System.out.println(conn.getUser()); if (this.multitrans.getMUC() == null) { // this.muc = XMPPMultiChatTransmitter.joinMuc(conn, // Saros.getDefault().getConnection().getUser(), room); this.multitrans.initMUC(conn, conn.getUser()); } // muc.addMessageListener(mucl); // TODO: check if still connected if ((this.multiSession == null) && (this.multitrans.getMUC() != null)) { // muc.removeMessageListener(mucl); MultiChatSession session = new MultiChatSession(this.multitrans .getMUC()); this.multiSession = session; } } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * invitation listener for multi chat invitations. */ public void initMultiChatListener() { // listens for MUC invitations MultiUserChat.addInvitationListener(Saros.getDefault().getConnection(), this); } public MultiChatSession getSession() { return this.session; } public void connectMultiUserChat() throws XMPPException { if (!Saros.getDefault().isConnected()) { throw new XMPPException("No connection "); } String user = Saros.getDefault().getConnection().getUser(); if (this.session == null) { MultiUserChat muc = this.multitrans.getMUC(); if (muc == null) { this.multitrans.initMUC(Saros.getDefault().getConnection(), user); muc = this.multitrans.getMUC(); } MessagingManager.log.debug("Creating MUC session.."); this.session = new MultiChatSession(muc); } else { this.multitrans.getMUC().join(user); } } public void disconnectMultiUserChat() throws XMPPException { MessagingManager.log.debug("Leaving MUC session.."); this.multitrans.getMUC().leave(); } }
true
true
public void processPacket(Packet packet) { MessagingManager.log.debug("messagePacket called"); final Message message = (Message) packet; final JID jid = new JID(message.getFrom()); if (message.getBody() == null) { return; } /* check for multi or single chat. */ if (message.getFrom().contains(this.multitrans.getRoomName())) { if (this.multiSession == null) { this.multiSession = new MultiChatSession(this.multitrans .getMUC()); this.multiSession.processPacket(message); } } else { /* old chat based message communication. */ for (ChatSession session : this.sessions) { if (jid.equals(session.getParticipant())) { return; // gets already handled by message handler in // session } } } }
public void processPacket(Packet packet) { MessagingManager.log.trace("processPacket called"); final Message message = (Message) packet; final JID jid = new JID(message.getFrom()); if (message.getBody() == null) { return; } /* check for multi or single chat. */ if (message.getFrom().contains(this.multitrans.getRoomName())) { if (this.multiSession == null) { this.multiSession = new MultiChatSession(this.multitrans .getMUC()); this.multiSession.processPacket(message); } } else { /* old chat based message communication. */ for (ChatSession session : this.sessions) { if (jid.equals(session.getParticipant())) { return; // gets already handled by message handler in // session } } } }
diff --git a/AndroidVkSdk/src/com/perm/kate/api/Group.java b/AndroidVkSdk/src/com/perm/kate/api/Group.java index 9e30be7..807034c 100644 --- a/AndroidVkSdk/src/com/perm/kate/api/Group.java +++ b/AndroidVkSdk/src/com/perm/kate/api/Group.java @@ -1,65 +1,65 @@ package com.perm.kate.api; import java.io.Serializable; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Group implements Serializable { private static final long serialVersionUID = 1L; public long gid; public String name; public String photo;//50*50 public Boolean is_closed; public Boolean is_member; //��� ����� ����, ������� � ��� ���� ��� � ���� //public String screen_name; //public Boolean is_admin; public String photo_medium;//100*100 public String photo_big;//200*200 public String description; public static Group parse(JSONObject o) throws JSONException{ Group g=new Group(); g.gid = o.getLong("gid"); g.name = Api.unescape(o.getString("name")); - g.photo = o.getString("photo"); + g.photo = o.optString("photo"); g.photo_medium = o.optString("photo_medium"); g.photo_big = o.optString("photo_big"); String is_closed = o.optString("is_closed"); if(is_closed != null) g.is_closed = is_closed.equals("1"); String is_member = o.optString("is_member"); if(is_member != null) g.is_member = is_member.equals("1"); String description_text = o.optString("description"); if (description_text != null) g.description = Api.unescape(description_text); //��� ����� ����, ������� � ��� ���� ��� � ���� //g.screen_name=o.optString("screen_name"); //String is_admin=o.optString("is_admin"); //if(is_admin!=null) // g.is_admin=is_admin.equals("1"); //g.photo_medium = o.getString("photo_medium"); //g.photo_big = o.getString("photo_big"); return g; } public static ArrayList<Group> parseGroups(JSONArray jgroups) throws JSONException { ArrayList<Group> groups=new ArrayList<Group>(); for(int i = 0; i < jgroups.length(); i++) { //��� ������ groups.get ������ ������� - ���������� if(!(jgroups.get(i) instanceof JSONObject)) continue; JSONObject jgroup = (JSONObject)jgroups.get(i); Group group = Group.parse(jgroup); groups.add(group); } return groups; } }
true
true
public static Group parse(JSONObject o) throws JSONException{ Group g=new Group(); g.gid = o.getLong("gid"); g.name = Api.unescape(o.getString("name")); g.photo = o.getString("photo"); g.photo_medium = o.optString("photo_medium"); g.photo_big = o.optString("photo_big"); String is_closed = o.optString("is_closed"); if(is_closed != null) g.is_closed = is_closed.equals("1"); String is_member = o.optString("is_member"); if(is_member != null) g.is_member = is_member.equals("1"); String description_text = o.optString("description"); if (description_text != null) g.description = Api.unescape(description_text); //��� ����� ����, ������� � ��� ���� ��� � ���� //g.screen_name=o.optString("screen_name"); //String is_admin=o.optString("is_admin"); //if(is_admin!=null) // g.is_admin=is_admin.equals("1"); //g.photo_medium = o.getString("photo_medium"); //g.photo_big = o.getString("photo_big"); return g; }
public static Group parse(JSONObject o) throws JSONException{ Group g=new Group(); g.gid = o.getLong("gid"); g.name = Api.unescape(o.getString("name")); g.photo = o.optString("photo"); g.photo_medium = o.optString("photo_medium"); g.photo_big = o.optString("photo_big"); String is_closed = o.optString("is_closed"); if(is_closed != null) g.is_closed = is_closed.equals("1"); String is_member = o.optString("is_member"); if(is_member != null) g.is_member = is_member.equals("1"); String description_text = o.optString("description"); if (description_text != null) g.description = Api.unescape(description_text); //��� ����� ����, ������� � ��� ���� ��� � ���� //g.screen_name=o.optString("screen_name"); //String is_admin=o.optString("is_admin"); //if(is_admin!=null) // g.is_admin=is_admin.equals("1"); //g.photo_medium = o.getString("photo_medium"); //g.photo_big = o.getString("photo_big"); return g; }
diff --git a/sourceediting/tests/org.eclipse.wst.xml.vex.tests/src/org/eclipse/wst/xml/vex/tests/AllTestsSuite.java b/sourceediting/tests/org.eclipse.wst.xml.vex.tests/src/org/eclipse/wst/xml/vex/tests/AllTestsSuite.java index 42e9c46..f921749 100644 --- a/sourceediting/tests/org.eclipse.wst.xml.vex.tests/src/org/eclipse/wst/xml/vex/tests/AllTestsSuite.java +++ b/sourceediting/tests/org.eclipse.wst.xml.vex.tests/src/org/eclipse/wst/xml/vex/tests/AllTestsSuite.java @@ -1,43 +1,43 @@ /******************************************************************************* * Copyright (c) 2008 Standards for Technology in Automotive Retail and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Carver (STAR) - initial API and implementation *******************************************************************************/ package org.eclipse.wst.xml.vex.tests; import junit.framework.TestSuite; import org.eclipse.wst.xml.vex.core.tests.VEXCoreTestSuite; import org.eclipse.wst.xml.vex.ui.internal.editor.tests.FindReplaceTargetTest; import org.eclipse.wst.xml.vex.ui.internal.tests.ResourceTrackerTest; /** * This class specifies all the bundles of this component that provide a test * suite to run during automated testing. */ public class AllTestsSuite extends TestSuite { public AllTestsSuite() { - super("All Vex Test Suites"); //$NON-NLS-1$ + super("All VEX Test Suites"); //$NON-NLS-1$ addTest(VEXCoreTestSuite.suite()); // addTest(VexUiTestSuite.suite()); // addTestSuite(IconTest.class); addTestSuite(ResourceTrackerTest.class); addTestSuite(FindReplaceTargetTest.class); } /** * This is just need to run in a development environment workbench. */ public void testAll() { // this method needs to exist, but doesn't really do anything // other than to signal to create an instance of this class. // The rest it automatic from the tests added in constructor. } }
true
true
public AllTestsSuite() { super("All Vex Test Suites"); //$NON-NLS-1$ addTest(VEXCoreTestSuite.suite()); // addTest(VexUiTestSuite.suite()); // addTestSuite(IconTest.class); addTestSuite(ResourceTrackerTest.class); addTestSuite(FindReplaceTargetTest.class); }
public AllTestsSuite() { super("All VEX Test Suites"); //$NON-NLS-1$ addTest(VEXCoreTestSuite.suite()); // addTest(VexUiTestSuite.suite()); // addTestSuite(IconTest.class); addTestSuite(ResourceTrackerTest.class); addTestSuite(FindReplaceTargetTest.class); }
diff --git a/cobertura/src/net/sourceforge/cobertura/coveragedata/ProjectData.java b/cobertura/src/net/sourceforge/cobertura/coveragedata/ProjectData.java index a59135a..fb44504 100644 --- a/cobertura/src/net/sourceforge/cobertura/coveragedata/ProjectData.java +++ b/cobertura/src/net/sourceforge/cobertura/coveragedata/ProjectData.java @@ -1,188 +1,188 @@ /* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2003 jcoverage ltd. * Copyright (C) 2005 Mark Doliner * * Cobertura is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * Cobertura is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.coveragedata; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; public class ProjectData extends CoverageDataContainer implements HasBeenInstrumented { private static final long serialVersionUID = 6; private static ProjectData globalProjectData = null; private static SaveTimer saveTimer = null; /** This collection is used for quicker access to the list of source files. */ private Map sourceFiles = new HashMap(); /** This collection is used for quicker access to the list of classes. */ private Map classes = new HashMap(); public void addClassData(ClassData classData) { String packageName = classData.getPackageName(); PackageData packageData = (PackageData)children.get(packageName); if (packageData == null) { packageData = new PackageData(packageName); // Each key is a package name, stored as an String object. // Each value is information about the package, stored as a PackageData object. this.children.put(packageName, packageData); } packageData.addClassData(classData); this.sourceFiles.put(classData.getSourceFileName(), packageData.getChild(classData.getSourceFileName())); this.classes.put(classData.getName(), classData); } public ClassData getClassData(String name) { return (ClassData)this.classes.get(name); } public ClassData getOrCreateClassData(String name) { ClassData classData = (ClassData)this.classes.get(name); if (classData == null) { classData = new ClassData(name); addClassData(classData); } return classData; } public Collection getClasses() { return this.classes.values(); } public int getNumberOfClasses() { return this.classes.size(); } public int getNumberOfSourceFiles() { return this.sourceFiles.size(); } public SortedSet getPackages() { return new TreeSet(this.children.values()); } public Collection getSourceFiles() { return this.sourceFiles.values(); } /** * Get all subpackages of the given package. * * @param packageName The package name to find subpackages for. * For example, "com.example" * @return A collection containing PackageData objects. Each one * has a name beginning with the given packageName. For * example, "com.example.io" */ public SortedSet getSubPackages(String packageName) { SortedSet subPackages = new TreeSet(); Iterator iter = this.children.values().iterator(); while (iter.hasNext()) { PackageData packageData = (PackageData)iter.next(); if (packageData.getName().startsWith(packageName)) subPackages.add(packageData); } return subPackages; } public void merge(CoverageData coverageData) { super.merge(coverageData); ProjectData projectData = (ProjectData)coverageData; for (Iterator iter = projectData.classes.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); if (!this.classes.containsKey(key)) { this.classes.put(key, projectData.classes.get(key)); } } } public static ProjectData getGlobalProjectData() { if (globalProjectData != null) return globalProjectData; File dataFile = CoverageDataFileHandler.getDefaultDataFile(); // Read projectData from the serialized file. if (dataFile.isFile()) { //System.out.println("Cobertura: Loading global project data from " + dataFile.getAbsolutePath()); globalProjectData = CoverageDataFileHandler .loadCoverageData(dataFile); } if (globalProjectData == null) { // We could not read from the serialized file, so create a new object. System.out.println("Cobertura: Coverage data file " + dataFile.getAbsolutePath() + " either does not exist or is not readable. Creating a new data file."); globalProjectData = new ProjectData(); + } - // Add a hook to save the data when the JVM exits - saveTimer = new SaveTimer(); - Runtime.getRuntime().addShutdownHook(new Thread(saveTimer)); + // Add a hook to save the data when the JVM exits + saveTimer = new SaveTimer(); + Runtime.getRuntime().addShutdownHook(new Thread(saveTimer)); - // Possibly also save the coverage data every x seconds? - //Timer timer = new Timer(true); - //timer.schedule(saveTimer, 100); - } + // Possibly also save the coverage data every x seconds? + //Timer timer = new Timer(true); + //timer.schedule(saveTimer, 100); return globalProjectData; } public static void saveGlobalProjectData() { ProjectData projectData = getGlobalProjectData(); synchronized (projectData) { CoverageDataFileHandler.saveCoverageData(projectData, CoverageDataFileHandler.getDefaultDataFile()); } } }
false
true
public static ProjectData getGlobalProjectData() { if (globalProjectData != null) return globalProjectData; File dataFile = CoverageDataFileHandler.getDefaultDataFile(); // Read projectData from the serialized file. if (dataFile.isFile()) { //System.out.println("Cobertura: Loading global project data from " + dataFile.getAbsolutePath()); globalProjectData = CoverageDataFileHandler .loadCoverageData(dataFile); } if (globalProjectData == null) { // We could not read from the serialized file, so create a new object. System.out.println("Cobertura: Coverage data file " + dataFile.getAbsolutePath() + " either does not exist or is not readable. Creating a new data file."); globalProjectData = new ProjectData(); // Add a hook to save the data when the JVM exits saveTimer = new SaveTimer(); Runtime.getRuntime().addShutdownHook(new Thread(saveTimer)); // Possibly also save the coverage data every x seconds? //Timer timer = new Timer(true); //timer.schedule(saveTimer, 100); } return globalProjectData; }
public static ProjectData getGlobalProjectData() { if (globalProjectData != null) return globalProjectData; File dataFile = CoverageDataFileHandler.getDefaultDataFile(); // Read projectData from the serialized file. if (dataFile.isFile()) { //System.out.println("Cobertura: Loading global project data from " + dataFile.getAbsolutePath()); globalProjectData = CoverageDataFileHandler .loadCoverageData(dataFile); } if (globalProjectData == null) { // We could not read from the serialized file, so create a new object. System.out.println("Cobertura: Coverage data file " + dataFile.getAbsolutePath() + " either does not exist or is not readable. Creating a new data file."); globalProjectData = new ProjectData(); } // Add a hook to save the data when the JVM exits saveTimer = new SaveTimer(); Runtime.getRuntime().addShutdownHook(new Thread(saveTimer)); // Possibly also save the coverage data every x seconds? //Timer timer = new Timer(true); //timer.schedule(saveTimer, 100); return globalProjectData; }
diff --git a/src/main/java/org/elasticsearch/common/util/concurrent/ThreadLocals.java b/src/main/java/org/elasticsearch/common/util/concurrent/ThreadLocals.java index 996dfe3bbc9..f2c0376d45d 100644 --- a/src/main/java/org/elasticsearch/common/util/concurrent/ThreadLocals.java +++ b/src/main/java/org/elasticsearch/common/util/concurrent/ThreadLocals.java @@ -1,160 +1,160 @@ /* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.util.concurrent; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * */ public class ThreadLocals { private static final ESLogger logger = Loggers.getLogger(ThreadLocals.class); public static void clearReferencesThreadLocals() { try { Thread[] threads = getThreads(); // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); clearThreadLocalMap(threadLocalMap, tableField); // Clear the second map threadLocalMap = inheritableThreadLocalsField.get(threads[i]); clearThreadLocalMap(threadLocalMap, tableField); } } } catch (Exception e) { logger.debug("failed to clean thread locals", e); } } /* * Clears the given thread local map object. Also pass in the field that * points to the internal table to save re-calculating it on every * call to this method. */ private static void clearThreadLocalMap(Object map, Field internalTableField) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException { if (map != null) { Method mapRemove = map.getClass().getDeclaredMethod("remove", ThreadLocal.class); mapRemove.setAccessible(true); Object[] table = (Object[]) internalTableField.get(map); int staleEntriesCount = 0; if (table != null) { for (int j = 0; j < table.length; j++) { Object tableValue = table[j]; if (tableValue != null) { boolean remove = false; // Check the key Object key = ((Reference<?>) tableValue).get(); // Check the value Field valueField = tableValue.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(tableValue); if (value != null) { Object actualValue = value; if (value instanceof SoftReference) { actualValue = ((SoftReference) value).get(); } if (actualValue != null) { String actualValueClassName = actualValue.getClass().getName(); - if (actualValueClassName.startsWith("org.elasticsearch") || actualValueClassName.startsWith("org.lucene")) { + if (actualValueClassName.startsWith("org.elasticsearch") || actualValueClassName.startsWith("org.apache.lucene")) { remove = true; } } } if (remove) { Object[] args = new Object[4]; if (key != null) { args[0] = key.getClass().getCanonicalName(); args[1] = key.toString(); } args[2] = value.getClass().getCanonicalName(); args[3] = value.toString(); if (logger.isTraceEnabled()) { logger.trace("ThreadLocal with key of type [{}] (value [{}]) and a value of type [{}] (value [{}]): The ThreadLocal has been forcibly removed.", args); } if (key == null) { staleEntriesCount++; } else { mapRemove.invoke(map, key); } } } } } if (staleEntriesCount > 0) { Method mapRemoveStale = map.getClass().getDeclaredMethod("expungeStaleEntries"); mapRemoveStale.setAccessible(true); mapRemoveStale.invoke(map); } } } /* * Get the set of current threads as an array. */ private static Thread[] getThreads() { // Get the current thread group ThreadGroup tg = Thread.currentThread().getThreadGroup(); // Find the root thread group while (tg.getParent() != null) { tg = tg.getParent(); } int threadCountGuess = tg.activeCount() + 50; Thread[] threads = new Thread[threadCountGuess]; int threadCountActual = tg.enumerate(threads); // Make sure we don't miss any threads while (threadCountActual == threadCountGuess) { threadCountGuess *= 2; threads = new Thread[threadCountGuess]; // Note tg.enumerate(Thread[]) silently ignores any threads that // can't fit into the array threadCountActual = tg.enumerate(threads); } return threads; } }
true
true
private static void clearThreadLocalMap(Object map, Field internalTableField) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException { if (map != null) { Method mapRemove = map.getClass().getDeclaredMethod("remove", ThreadLocal.class); mapRemove.setAccessible(true); Object[] table = (Object[]) internalTableField.get(map); int staleEntriesCount = 0; if (table != null) { for (int j = 0; j < table.length; j++) { Object tableValue = table[j]; if (tableValue != null) { boolean remove = false; // Check the key Object key = ((Reference<?>) tableValue).get(); // Check the value Field valueField = tableValue.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(tableValue); if (value != null) { Object actualValue = value; if (value instanceof SoftReference) { actualValue = ((SoftReference) value).get(); } if (actualValue != null) { String actualValueClassName = actualValue.getClass().getName(); if (actualValueClassName.startsWith("org.elasticsearch") || actualValueClassName.startsWith("org.lucene")) { remove = true; } } } if (remove) { Object[] args = new Object[4]; if (key != null) { args[0] = key.getClass().getCanonicalName(); args[1] = key.toString(); } args[2] = value.getClass().getCanonicalName(); args[3] = value.toString(); if (logger.isTraceEnabled()) { logger.trace("ThreadLocal with key of type [{}] (value [{}]) and a value of type [{}] (value [{}]): The ThreadLocal has been forcibly removed.", args); } if (key == null) { staleEntriesCount++; } else { mapRemove.invoke(map, key); } } } } } if (staleEntriesCount > 0) { Method mapRemoveStale = map.getClass().getDeclaredMethod("expungeStaleEntries"); mapRemoveStale.setAccessible(true); mapRemoveStale.invoke(map); } } }
private static void clearThreadLocalMap(Object map, Field internalTableField) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException { if (map != null) { Method mapRemove = map.getClass().getDeclaredMethod("remove", ThreadLocal.class); mapRemove.setAccessible(true); Object[] table = (Object[]) internalTableField.get(map); int staleEntriesCount = 0; if (table != null) { for (int j = 0; j < table.length; j++) { Object tableValue = table[j]; if (tableValue != null) { boolean remove = false; // Check the key Object key = ((Reference<?>) tableValue).get(); // Check the value Field valueField = tableValue.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(tableValue); if (value != null) { Object actualValue = value; if (value instanceof SoftReference) { actualValue = ((SoftReference) value).get(); } if (actualValue != null) { String actualValueClassName = actualValue.getClass().getName(); if (actualValueClassName.startsWith("org.elasticsearch") || actualValueClassName.startsWith("org.apache.lucene")) { remove = true; } } } if (remove) { Object[] args = new Object[4]; if (key != null) { args[0] = key.getClass().getCanonicalName(); args[1] = key.toString(); } args[2] = value.getClass().getCanonicalName(); args[3] = value.toString(); if (logger.isTraceEnabled()) { logger.trace("ThreadLocal with key of type [{}] (value [{}]) and a value of type [{}] (value [{}]): The ThreadLocal has been forcibly removed.", args); } if (key == null) { staleEntriesCount++; } else { mapRemove.invoke(map, key); } } } } } if (staleEntriesCount > 0) { Method mapRemoveStale = map.getClass().getDeclaredMethod("expungeStaleEntries"); mapRemoveStale.setAccessible(true); mapRemoveStale.invoke(map); } } }
diff --git a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java index 9f8e5fe0..3a60d475 100644 --- a/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java +++ b/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java @@ -1,8535 +1,8535 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Hashtable; import java.util.HashSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer; import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo; import org.sakaiproject.assignment.taggable.api.TaggingManager; import org.sakaiproject.assignment.taggable.api.TaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException; import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.user.api.User; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** default sorting */ private static final String SORTED_BY_DEFAULT = "default"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // assignment order for default view private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to reorder assignments */ private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to reorder the default assignments */ private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = null; context.put("tlang", rb); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? context.put("allowUpdateSite", Boolean .valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))); // allow all.groups? boolean allowAllGroups = AssignmentService.allowAllGroups(contextString); context.put("allowAllGroups", Boolean.valueOf(allowAllGroups)); // this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state.getAttribute(STATE_CONTEXT_STRING))); boolean assignmentscheck = (assignments.size() > 0) ? true : false; context.put("assignmentscheck", Boolean.valueOf(assignmentscheck)); // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_LIST_ASSIGNMENTS)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (mode.equals(MODE_LIST_ASSIGNMENTS)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION)) { // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_GRADE)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_reorder_assignment_context(portlet, context, data, state); } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } return template; } // buildNormalContext /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); User user = (User) state.getAttribute(STATE_USER); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment", assignment); AssignmentSubmission s = AssignmentService.getSubmission(assignment.getReference(), user); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING)); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", new Boolean(allowSubmit)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); // get user information User user = (User) state.getAttribute(STATE_USER); context.put("user_name", user.getDisplayName()); context.put("user_id", user.getDisplayId()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment_title", currentAssignment.getTitle()); AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user); if (s != null) { context.put("submission_id", s.getId()); context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getSubmittedAttachments()); } context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(aId); context.put("assignment", assignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("gradeTypeTable", gradeTypeTable()); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { context.put("assignment", AssignmentService.getAssignment(aReference)); context.put("submission", AssignmentService.getSubmission(aReference, user)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); AssignmentSubmission submission = null; try { submission = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID)); context.put("assignment", submission.getAssignment()); context.put("submission", submission); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_get_submission")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && submission != null) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getItemHelperInfo( assignmentActivityProducer.getItem( submission, UserDirectoryService.getCurrentUser() .getId()).getReference()); if (helper != null) { itemHelpers.add(helper); } } addItem(context, submission, UserDirectoryService.getCurrentUser().getId()); addActivity(context, submission.getAssignment()); context.put("itemHelpers", itemHelpers); context.put("taggable", Boolean.valueOf(true)); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); context.put("providers", taggingManager.getProviders()); context.put("taggable", Boolean.valueOf(true)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", new Long(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } List assignments = prepPage(state); context.put("assignments", assignments.iterator()); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = site.getGroups(); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", new Boolean(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("assignment", a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14") + ": " + assignmentId); } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_order", NEW_ASSIGNMENT_ORDER); context.put("name_OpenMonth", NEW_ASSIGNMENT_OPENMONTH); context.put("name_OpenDay", NEW_ASSIGNMENT_OPENDAY); context.put("name_OpenYear", NEW_ASSIGNMENT_OPENYEAR); context.put("name_OpenHour", NEW_ASSIGNMENT_OPENHOUR); context.put("name_OpenMin", NEW_ASSIGNMENT_OPENMIN); context.put("name_OpenAMPM", NEW_ASSIGNMENT_OPENAMPM); context.put("name_DueMonth", NEW_ASSIGNMENT_DUEMONTH); context.put("name_DueDay", NEW_ASSIGNMENT_DUEDAY); context.put("name_DueYear", NEW_ASSIGNMENT_DUEYEAR); context.put("name_DueHour", NEW_ASSIGNMENT_DUEHOUR); context.put("name_DueMin", NEW_ASSIGNMENT_DUEMIN); context.put("name_DueAMPM", NEW_ASSIGNMENT_DUEAMPM); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("name_CloseMonth", NEW_ASSIGNMENT_CLOSEMONTH); context.put("name_CloseDay", NEW_ASSIGNMENT_CLOSEDAY); context.put("name_CloseYear", NEW_ASSIGNMENT_CLOSEYEAR); context.put("name_CloseHour", NEW_ASSIGNMENT_CLOSEHOUR); context.put("name_CloseMin", NEW_ASSIGNMENT_CLOSEMIN); context.put("name_CloseAMPM", NEW_ASSIGNMENT_CLOSEAMPM); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } // gradebook integration context.put("withGradebook", Boolean.valueOf(isGradebookDefined())); // number of resubmissions allowed context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // set the values context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER)); context.put("value_OpenMonth", state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)); context.put("value_OpenDay", state.getAttribute(NEW_ASSIGNMENT_OPENDAY)); context.put("value_OpenYear", state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)); context.put("value_OpenHour", state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)); context.put("value_OpenMin", state.getAttribute(NEW_ASSIGNMENT_OPENMIN)); context.put("value_OpenAMPM", state.getAttribute(NEW_ASSIGNMENT_OPENAMPM)); context.put("value_DueMonth", state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); context.put("value_DueDay", state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); context.put("value_DueYear", state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); context.put("value_DueHour", state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); context.put("value_DueMin", state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); context.put("value_DueAMPM", state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_CloseMonth", state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)); context.put("value_CloseDay", state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)); context.put("value_CloseYear", state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)); context.put("value_CloseHour", state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)); context.put("value_CloseMin", state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)); context.put("value_CloseAMPM", state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // number of resubmissions allowed if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } else { // defaults to 0 context.put("value_allowResubmitNumber", Integer.valueOf(0)); } // get all available assignments from Gradebook tool except for those created from boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); // get all assignments in Gradebook List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new Vector(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); } } context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo); if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (range != null && range.length() != 0) { context.put("range", range); } else { if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc))); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue()) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } } // setAssignmentFormContext /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("name_order", NEW_ASSIGNMENT_ORDER); context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER)); Time openTime = getOpenTime(state); context.put("value_OpenDate", openTime); // due time int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); // get all available assignments from Gradebook tool except for those created from if (isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); context.put("value_assignment_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { Vector assignments = new Vector(); Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < assignmentIds.size(); i++) { try { Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i)); Iterator submissions = AssignmentService.getSubmissions(a); if (submissions.hasNext()) { // if there is submission to the assignment, show the alert addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n"); } assignments.add(a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } context.put("assignments", assignments); context.put("service", AssignmentService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { int gradeType = -1; // assignment Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // assignment submission try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } // get the submission level of close date setting context.put("name_CloseMonth", ALLOW_RESUBMIT_CLOSEMONTH); context.put("name_CloseDay", ALLOW_RESUBMIT_CLOSEDAY); context.put("name_CloseYear", ALLOW_RESUBMIT_CLOSEYEAR); context.put("name_CloseHour", ALLOW_RESUBMIT_CLOSEHOUR); context.put("name_CloseMin", ALLOW_RESUBMIT_CLOSEMIN); context.put("name_CloseAMPM", ALLOW_RESUBMIT_CLOSEAMPM); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); Time time = null; if (closeTimeString != null) { // if there is a local setting time = TimeService.newTime(Long.parseLong(closeTimeString)); } else if (a != null) { // if there is no local setting, default to assignment close time time = a.getCloseTime(); } TimeBreakdown closeTime = time.breakdownLocal(); context.put("value_CloseMonth", new Integer(closeTime.getMonth())); context.put("value_CloseDay", new Integer(closeTime.getDay())); context.put("value_CloseYear", new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { context.put("value_CloseAMPM", "PM"); } else { context.put("value_CloseAMPM", "AM"); } if (closeHour == 0) { // for midnight point, we mark it as 12AM closeHour = 12; } context.put("value_CloseHour", new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); context.put("value_CloseMin", new Integer(closeTime.getMin())); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("gradingAttachments", state.getAttribute(ATTACHMENTS)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // submission try { context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID))); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); context.put("assignment", assignment); state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId()); List userSubmissions = prepPage(state); state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); // ever set the default grade for no-submissions String noSubmissionDefaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (noSubmissionDefaultGrade != null) { context.put("noSubmissionDefaultGrade", noSubmissionDefaultGrade); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID)); context.put("assignment", assignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getActivityHelperInfo( assignmentActivityProducer.getActivity( assignment).getReference()); if (helper != null) { activityHelpers.add(helper); } } addActivity(context, assignment); context.put("activityHelpers", activityHelpers); context.put("taggable", Boolean.valueOf(true)); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("gradeTypeTable", gradeTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context /** * build the instructor view of reordering assignments */ protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); context.put("assignmentsize", assignments.size()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("gradeTypeTable", gradeTypeTable()); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT; } // build_instructor_reorder_assignment_context /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get the realm and its member List studentMembers = new Vector(); String realmId = SiteService.siteReference((String) state.getAttribute(STATE_CONTEXT_STRING)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); Set allowSubmitMembers = realm.getUsersIsAllowed(AssignmentService.SECURE_ADD_ASSIGNMENT_SUBMISSION); for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } catch (GroupNotDefinedException e) { Log.warn("chef", this + " IdUnusedException, not found, or not an AuthzGroup object"); addAlert(state, rb.getString("java.realm") + realmId); } context.put("studentMembers", studentMembers); context.put("assignmentService", AssignmentService.getInstance()); Hashtable showStudentAssignments = new Hashtable(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); showStudentAssignments.put(user, AssignmentService.getAssignmentsForContext(contextString, userId)); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED); context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT); context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE); add2ndToolbarFields(data, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions // Is Gradebook defined for the site? protected boolean isGradebookDefined() { boolean rv = false; try { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager .get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid)) { rv = true; } } catch (Exception e) { Log.debug("chef", this + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage()); } return rv; } // isGradebookDefined() /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool("sakai.assignment.grades"); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * integration with gradebook * * @param state * @param assignmentRef Assignment reference * @param associateGradebookAssignment The title for the associated GB assignment * @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment * @param oldAssignment_title The original assignment title * @param newAssignment_title The updated assignment title * @param newAssignment_maxPoints The maximum point of the assignment * @param newAssignment_dueTime The due time of the assignment * @param submissionRef Any submission grade need to be updated? Do bulk update if null * @param updateRemoveSubmission "update" for update submission;"remove" for remove submission */ protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission) { associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment); // add or remove external grades to gradebook // a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden // b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The // exception are indication that the assessment is already in the Gradebook or there is nothing // to remove. boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { String assignmentToolTitle = getToolTitle(); GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, assignmentRef); boolean isExternalAssociateAssignmentDefined = g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment); if (addUpdateRemoveAssignment != null) { // add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || (addUpdateRemoveAssignment.equals("update") && !isExternalAssignmentDefined)) && associateGradebookAssignment == null) { // add assignment into gradebook try { // add assignment to gradebook g.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); } catch (ConflictingAssignmentNameException e) { // add alert prompting for change assignment title addAlert(state, rb.getString("addtogradebook.nonUniqueTitle")); } catch (ConflictingExternalIdException e) { // this shouldn't happen, as we have already checked for assignment reference before. Log the error Log.warn("chef", this + e.getMessage()); } catch (GradebookNotFoundException e) { // this shouldn't happen, as we have checked for gradebook existence before Log.warn("chef", this + e.getMessage()); } catch (Exception e) { // ignore Log.warn("chef", this + e.getMessage()); } } else if (addUpdateRemoveAssignment.equals("update")) { // is there such record in gradebook? if (isExternalAssignmentDefined && associateGradebookAssignment == null) { try { Assignment a = AssignmentService.getAssignment(assignmentRef); // update attributes for existing assignment g.updateExternalAssessment(gradebookUid, assignmentRef, null, a.getTitle(), a.getContent().getMaxGradePoint()/10.0, new Date(a.getDueTime().getTime())); } catch(Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } else if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined) { try { Assignment a = AssignmentService.getAssignment(associateGradebookAssignment); // update attributes for existing assignment g.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime())); } catch(Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } } // addUpdateRemove != null else if (addUpdateRemoveAssignment.equals("remove")) { // remove assignment and all submission grades if (isExternalAssignmentDefined) { try { g.removeExternalAssessment(gradebookUid, assignmentRef); } catch (Exception e) { Log.warn("chef", "Exception when removing assignment " + assignmentRef + " and its submissions:" + e.getMessage()); } } } } if (updateRemoveSubmission != null) { try { Assignment a = AssignmentService.getAssignment(assignmentRef); if (updateRemoveSubmission.equals("update") && a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null && !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (submissionRef == null) { // bulk add all grades for assignment into gradebook Iterator submissions = AssignmentService.getSubmissions(a); Map m = new HashMap(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); String submitterId = submitters[0].getId(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null; m.put(submitterId, grade); } // need to update only when there is at least one submission if (m.size()>0) { if (associateGradebookAssignment != null) { if (isExternalAssociateAssignmentDefined) { // the associated assignment is externally maintained g.updateExternalAssessmentScores(gradebookUid, associateGradebookAssignment, m); } else if (isAssignmentDefined) { // the associated assignment is internal one, update records one by one submissions = AssignmentService.getSubmissions(a); while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); String submitterId = submitters[0].getId(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null; g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitterId, grade, assignmentToolTitle); } } } else if (isExternalAssignmentDefined) { g.updateExternalAssessmentScores(gradebookUid, assignmentRef, m); } } } else { try { // only update one submission AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService .getSubmission(submissionRef); User[] submitters = aSubmission.getSubmitters(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); if (associateGradebookAssignment != null) { if (g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is externally maintained g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null); } else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is internal one, update records g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null, assignmentToolTitle); } } else { g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null); } } catch (Exception e) { Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage()); } } } else if (updateRemoveSubmission.equals("remove")) { if (submissionRef == null) { // remove all submission grades (when changing the associated entry in Gradebook) Iterator submissions = AssignmentService.getSubmissions(a); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); if (isExternalAssociateAssignmentDefined) { // if the old associated assignment is an external maintained one g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null); } else if (isAssignmentDefined) { g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle); } } } else { // remove only one submission grade try { AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService .getSubmission(submissionRef); User[] submitters = aSubmission.getSubmitters(); g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null); } catch (Exception e) { Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage()); } } } } catch (Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } // updateRemoveSubmission != null } // if gradebook exists } // integrateGradebook /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); try { AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // try } // doView_submission /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // String assignmentId = params.getString(assignmentId); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE)); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the preview edit assignment process */ public void doDone_preview_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the edit assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_edit_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object // resetAssignment (state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the reorder process */ public void doCancel_reorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_reorder /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId); Assignment a = sEdit.getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if (gradeOption.equals("return") || gradeOption.equals("release")) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradeReleased(false); } else { if (typeOfGrade == 1) { sEdit.setGrade("no grade"); sEdit.setGraded(true); } else { if (!grade.equals("")) { if (typeOfGrade == 3) { sEdit.setGrade(grade); } else { sEdit.setGrade(grade); } sEdit.setGraded(true); } } } if (gradeOption.equals("release")) { sEdit.setGradeReleased(true); sEdit.setGraded(true); // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if (gradeOption.equals("return")) { if (StringUtil.trimToNull(grade) != null) { sEdit.setGradeReleased(true); sEdit.setGraded(true); } sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getAllowSubmitCloseTime(state); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } // the instructor comment String feedbackCommentString = StringUtil .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); AssignmentService.commitEdit(sEdit); // update grades in gradebook String aReference = a.getReference(); String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (gradeOption.equals("release") || gradeOption.equals("return")) { // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update"); } else { // remove grade from gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove"); } } catch (IdUnusedException e) { } catch (PermissionException e) { } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } // try if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = "false"; } String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); User u = (User) state.getAttribute(STATE_USER); if (state.getAttribute(STATE_MESSAGE) == null) { try { Assignment a = AssignmentService.getAssignment(aReference); String assignmentId = a.getId(); AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u); if (submission != null) { // the submission already exists, change the text and honor pledge value, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first edit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot12")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state .getAttribute(STATE_CONTEXT_STRING), assignmentId); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot4")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // doSave_submission /** * Action is to post the submission */ public void doPost_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = null; try { a = AssignmentService.getAssignment(aReference); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == 1) { // for the inline only submission if (text.length() == 0) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == 2) { // for the attachment only submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == 3) { // for the inline and attachment submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((text.length() == 0) && ((v == null) || (v.size() == 0))) { addAlert(state, rb.getString("youmust2")); } } } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { try { AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u); if (submission != null) { // the submission already exists, change the text and honor pledge value, post it try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(true); // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. if (sEdit.getReturned()) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (sEdit.getGraded()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtil.split(previousGrades, " "); String newGrades = ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(".") == -1) { // show the grade with decimal point grade = grade.concat(".0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } previousGrades = previousGrades.concat(sEdit.getGradeDisplay() + " "); sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGrade(""); sEdit.setGradeReleased(false); } // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = sEdit.getFeedbackText() + "\n" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = sEdit.getFeedbackComment() + "\n" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); for (int k = 0; k<feedbackAttachments.size();k++) { feedbackAttachmentHistory = ((Reference) feedbackAttachments.get(k)).getReference() + "," + feedbackAttachmentHistory; } sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); // decrease the allow_resubmit_number if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } } } // sEdit.addSubmitter (u); sEdit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(sEdit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("no_permissiion_to_edit_submission")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, post it try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(true); // edit.addSubmitter (u); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); } } // if -else } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // if } // doPost_submission /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot2")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doNew_Assignment /** * Action is to show the reorder assignment screen */ public void doReorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // this insures the default order is loaded into the reordering tool state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot19")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doReorder /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); String order = params.getString(NEW_ASSIGNMENT_ORDER); state.setAttribute(NEW_ASSIGNMENT_ORDER, order); if (title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } // open time int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth)); int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay)); int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear)); int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour)); int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin)); String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); // validate date if (!Validator.checkDate(openDay, openMonth, openYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + "."); } // due time int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth)); int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay)); int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear)); int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour)); int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin)); String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); // validate date if (dueTime.before(TimeService.newTime())) { addAlert(state, rb.getString("assig4")); } if (!Validator.checkDate(dueDay, dueMonth, dueYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + "."); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // close time int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); // validate date if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } if (closeTime.before(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE))); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType)); } // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); // correct inputs // checks on the times if (validify && dueTime.before(openTime)) { addAlert(state, rb.getString("assig3")); } if (validify) { if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of releasing grade, user must specify a grade addAlert(state, rb.getString("plespethe2")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if (range.equals("groups")) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } // allow resubmission numbers String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (nString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } } // setNewAssignmentParameters /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment option */ public void doHide_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option"); } // doHide_assignment_option /** * Action is to show the assignment option */ public void doShow_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); } // doShow_assignment_option /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment postOrSaveAssignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (String key : helperParms.keySet()) { state.setAttribute(key, helperParms.get(key)); } } // doHelp_activity /** * post or save assignment */ private void postOrSaveAssignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && postOrSave.equals("post"); // assignment old title String aOldTitle = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId); // Assignment AssignmentEdit a = getAssignmentEdit(state, assignmentId); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER); // open time Time openTime = getOpenTime(state); // due time Time dueTime = getDueTime(state); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getCloseTime(state); } // sections String s = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; // the attachments List attachments = (List) state.getAttribute(ATTACHMENTS); List attachments1 = EntityManager.newReferenceList(attachments); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new Vector(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); groups.add(site.getGroup(groupId)); } } catch (Exception e) { Log.warn("chef", this + "cannot find site with id "+ siteId); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); // old open time Time oldOpenTime = a.getOpenTime(); // old due time Time oldDueTime = a.getDueTime(); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, title, submissionType, gradeType, gradePoints, description, checkAddHonorPledge, attachments1); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit); // in case of non-electronic submission, create submissions for all students and mark it as submitted if (ac.getTypeOfSubmission()== Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String authzGroupId = SiteService.siteReference(contextString); List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(a.getReference()); try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { if (AssignmentService.getSubmission(a.getReference(), u) == null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(contextString, a.getId()); submission.removeSubmitter(UserDirectoryService.getCurrentUser()); submission.addSubmitter(u); submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } } } catch (Exception e) { Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId); } } // set the Assignment Properties object oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit); // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, s, range, groups); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); } if (post) { // only if user is posting the assignment // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range); } // if } // if } // if } // doPost_assignment private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) { String aReference = a.getReference(); String addUpdateRemoveAssignment = "remove"; if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if integrate with Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups"))) { // if grouped assignment is not allowed to add into Gradebook addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null); } else { if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD; } else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { addUpdateRemoveAssignment = "update"; } if (!addUpdateRemoveAssignment.equals("remove") && gradeType == 3) { try { integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null); // add all existing grades, if any, into Gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update"); // if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment)) { integrateGradebook(state, aReference, oAssociateGradebookAssignment, null, null, null, -1, null, null, "remove"); // if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, oAssociateGradebookAssignment); if (isExternalAssignmentDefined) { // iterate through all assignments currently in the site, see if any is associated with this GB entry Iterator i = AssignmentService.getAssignmentsForContext(siteId); boolean found = false; while (!found && i.hasNext()) { Assignment aI = (Assignment) i.next(); String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (gbEntry != null && gbEntry.equals(oAssociateGradebookAssignment)) { found = true; } } // so if none of the assignment in this site is associated with the entry, remove the entry if (!found) { g.removeExternalAssessment(gradebookUid, oAssociateGradebookAssignment); } } } } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); } } else { integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null); } } } else { // remove assignment entry from Gradebook integrateGradebook(state, aReference, oAssociateGradebookAssignment, "remove", null, null, -1, null, null, "remove"); } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { String openDateAnnounced = a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); // open date has been announced or title has been changed? boolean openDateMessageModified = false; if (openDateAnnounced != null && openDateAnnounced.equalsIgnoreCase(Boolean.TRUE.toString())) { if (oldOpenTime != null && (!oldOpenTime.toStringLocalFull().equals(openTime.toStringLocalFull())) // open time changes || !aOldTitle.equals(title)) // assignment title changes { // need to change message openDateMessageModified = true; } } // add the open date to annoucement if (openDateAnnounced == null // no announcement yet || (openDateAnnounced != null && openDateAnnounced.equalsIgnoreCase(Boolean.TRUE.toString()) && openDateMessageModified)) // announced, but open date or announcement title changes { // announcement channel is in place try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getString("assig6") + " " + title); message.setBody(/* body */rb.getString("opedat") + " " + FormattedText.convertPlaintextToFormattedText(title) + rb.getString("is") + openTime.toStringLocalFull() + ". "); } else { // revised announcement header.setSubject(/* subject */rb.getString("assig5") + " " + title); message.setBody(/* body */rb.getString("newope") + " " + FormattedText.convertPlaintextToFormattedText(title) + rb.getString("is") + openTime.toStringLocalFull() + ". "); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new Vector(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log Log.warn("chef", exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, NotificationService.NOTI_NONE); // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotmak")); } } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { if (state.getAttribute(CALENDAR) != null) { Calendar c = (Calendar) state.getAttribute(CALENDAR); String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null && c != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". "); } catch (PermissionException ee) { Log.warn("chef", "You do not have the permission to view the schedule event id= " + oldEventId + "."); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found) { // remove the founded old event try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { if (c != null) { // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new Vector(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); eGroups.add(site.getGroup(groupRef)); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("due") + " " + title, /* description */rb.getString("assig1") + " " + title + " " + "is due on " + dueTime.toStringLocalFull() + ". ", /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */EntityManager.newReferenceList()); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId()); } } catch (IdUnusedException ee) { Log.warn("chef", ee.getMessage()); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotfin1")); } catch (Exception ee) { Log.warn("chef", ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } // if } // if } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setOpenTime(openTime); a.setDueTime(dueTime); // set the drop dead date as the due date a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } // post the assignment a.setDraft(!post); try { if (range.equals("site")) { a.setAccess(Assignment.AssignmentAccess.SITE); a.clearGroupAccess(); } else if (range.equals("groups")) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } } private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference()); } // allow resubmit number if (allowResubmitNumber != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setTypeOfSubmission(submissionType); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); // add each attachment Iterator it = EntityManager.newReferenceList(attachments1).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); // commit the changes AssignmentService.commitEdit(ac); } /** * reorderAssignments */ private void reorderAssignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List assignments = prepPage(state); Iterator it = assignments.iterator(); // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); while (it.hasNext()) // reads and writes the parameter for default ordering { Assignment a = (Assignment) it.next(); String assignmentid = a.getId(); String assignmentposition = params.getString("position_" + assignmentid); AssignmentEdit ae = getAssignmentEdit(state, assignmentid); ae.setPosition_order(new Long(assignmentposition).intValue()); AssignmentService.commitEdit(ae); } // clear the permission SecurityService.clearAdvisors(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); //resetAssignment(state); } } // reorderAssignments private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId) { AssignmentEdit a = null; if (assignmentId.length() == 0) { // create a new assignment try { a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } } else { try { // edit assignment a = AssignmentService.editAssignment(assignmentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // try-catch } // if-else return a; } private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot3")); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin4")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot15")); } } return ac; } private Time getOpenTime(SessionState state) { int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue(); int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue(); int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue(); int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue(); int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue(); String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); return openTime; } private Time getCloseTime(SessionState state) { Time closeTime; int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } private Time getDueTime(SessionState state) { int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); return dueTime; } private Time getAllowSubmitCloseTime(SessionState state) { int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { postOrSaveAssignment(data, "save"); } // doSave_assignment /** * Action is to reorder assignments */ public void doReorder_assignment(RunData data) { reorderAssignments(data); } // doReorder_assignments /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, false); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); EventTrackingService.post(EventTrackingService.newEvent(AssignmentService.SECURE_ACCESS_ASSIGNMENT, a.getReference(), false)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); Iterator submissions = AssignmentService.getSubmissions(a); if (submissions.hasNext()) { boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted()) { anySubmitted = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum")); } else { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order()); TimeBreakdown openTime = a.getOpenTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear())); int openHour = openTime.getHour(); if (openHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM"); } if (openHour == 0) { // for midnight point, we mark it as 12AM openHour = 12; } state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin())); TimeBreakdown dueTime = a.getDueTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear())); int dueHour = dueTime.getHour(); if (dueHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM"); } if (dueHour == 0) { // for midnight point, we mark it as 12AM dueHour = 12; } state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin())); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); TimeBreakdown closeTime = a.getCloseTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM"); } if (closeHour == 0) { // for the midnight point, we mark it as 12 AM closeHour = 12; } state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin())); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission())); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doEdit_Assignment /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { Vector ids = new Vector(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getString("youarenot9") + " " + id + ". "); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); try { AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove releted event if there is one String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { removeCalendarEvent(state, aEdit, pEdit, title); } // if-else if (!AssignmentService.getSubmissions(aEdit).hasNext()) { // there is no submission to this assignment yet, delete the assignment record completely try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(aEdit)); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // remove the assignment by marking the remove status property true pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString()); AssignmentService.commitEdit(aEdit); } // remove from Gradebook integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot6")); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDelete_Assignment private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException { // remove the associated calender event Calendar c = (Calendar) state.getAttribute(CALENDAR); if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition } catch (PermissionException ee) { } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } // remove the founded old event if (found) { // found the old event delete it try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); try { AssignmentEdit a = AssignmentService.editAssignment(currentId); try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(a)); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". "); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); } catch (IdInvalidException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval")); } catch (IdUnusedException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee")); } catch (Exception e) { } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); // reset the grade assignment id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId")); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId")); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if ((s.getFeedbackText() != null) && (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); ResourceProperties p = s.getProperties(); if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null) { // if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property allowResubmitNumber = "1"; } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doGrade_submission /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); try { // get the assignment Assignment a = AssignmentService.getAssignment(params.getString("assignmentId")); String aReference = a.getReference(); Iterator submissions = AssignmentService.getSubmissions(a); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded()) { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !grade.equals("")) { sEdit.setGradeReleased(true); } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update"); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId")); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // we are changing the view, so start with first page again. resetPaging(state); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE); } // doView_grade /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); String option = (String) params.getString("option"); if (option != null) { if (option.equals("post")) { // post assignment doPost_assignment(data); } else if (option.equals("save")) { // save assignment doSave_assignment(data); } else if (option.equals("reorder")) { // reorder assignments doReorder_assignment(data); } else if (option.equals("preview")) { // preview assignment doPreview_assignment(data); } else if (option.equals("cancel")) { // cancel creating assignment doCancel_new_assignment(data); } else if (option.equals("canceledit")) { // cancel editing assignment doCancel_edit_assignment(data); } else if (option.equals("attach")) { // attachments doAttachments(data); } else if (option.equals("view")) { // view doView(data); } else if (option.equals("permissions")) { // permissions doPermissions(data); } else if (option.equals("returngrade")) { // return grading doReturn_grade_submission(data); } else if (option.equals("savegrade")) { // save grading doSave_grade_submission(data); } else if (option.equals("previewgrade")) { // preview grading doPreview_grade_submission(data); } else if (option.equals("cancelgrade")) { // cancel grading doCancel_grade_submission(data); } else if (option.equals("cancelreorder")) { // cancel reordering doCancel_reorder(data); } else if (option.equals("sortbygrouptitle")) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if (option.equals("sortbygroupdescription")) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if (option.equals("hide_instruction")) { // hide the assignment instruction doHide_submission_assignment_instruction(data); } else if (option.equals("show_instruction")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("sortbygroupdescription")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } } } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String mode = (String) state.getAttribute(STATE_MODE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); } } /** * readGradeForm */ public void readGradeForm(RunData data, SessionState state, String gradeOption) { ParameterParser params = data.getParameters(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = params.getCleanString(GRADE_SUBMISSION_GRADE); if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); Assignment a = AssignmentService.getSubmission(sId).getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // do grade validation only for Assignment with Grade tool if (typeOfGrade == 3) { if ((grade.length() == 0)) { if (gradeOption.equals("release")) { // in case of releasing grade, user must specify a grade addAlert(state, rb.getString("plespethe2")); } } else { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != 1) && gradeOption.equals("release")) { addAlert(state, rb.getString("plespethe2")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // allow resubmit number and due time if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM); state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); // validate date if (closeTime.before(TimeService.newTime())) { addAlert(state, rb.getString("assig4")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } } else { // reset the state attributes state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH); state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY); state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN); state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if /** The calendar service in the State. */ CalendarService cService = (CalendarService) state.getAttribute(STATE_CALENDAR_SERVICE); if (cService == null) { cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { Log.info("chef", "No calendar found for site " + siteId); state.removeAttribute(CALENDAR); } catch (PermissionException e) { Log.info("chef", "No permission to get the calender. "); state.removeAttribute(CALENDAR); } catch (Exception ex) { Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex); state.removeAttribute(CALENDAR); } } } // if /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { Log.warn("chef", "No announcement channel found. "); // the announcement channel is not created yet; go create try { aService.addAnnouncementChannel(channelId); } catch (PermissionException ee) { Log.warn("chef", "Can not create announcement channel. "); } catch (IdUsedException ee) { } catch (IdInvalidException ee) { Log.warn("chef", "The announcement channel could not be created because the Id is invalid. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : announcement exception : " + ex); } } catch (PermissionException e) { Log.warn("chef", "No permission to annoucement channel. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex); } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); } if (state.getAttribute(SORTED_ASC) == null) { state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null) { resetAssignment(state); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, new Boolean(withGrades)); } // whether the choice of emails instructor submission notification is available in the installation if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true))); } // whether or how the instructor receive submission notification emails, none(default)|each|digest if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } } // initState /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * reset the attributes for view submission */ private void resetAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); } // resetNewAssignment /** * construct a Hashtable using integer as the key and three character string of the month as the value */ private Hashtable monthTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("jan")); n.put(new Integer(2), rb.getString("feb")); n.put(new Integer(3), rb.getString("mar")); n.put(new Integer(4), rb.getString("apr")); n.put(new Integer(5), rb.getString("may")); n.put(new Integer(6), rb.getString("jun")); n.put(new Integer(7), rb.getString("jul")); n.put(new Integer(8), rb.getString("aug")); n.put(new Integer(9), rb.getString("sep")); n.put(new Integer(10), rb.getString("oct")); n.put(new Integer(11), rb.getString("nov")); n.put(new Integer(12), rb.getString("dec")); return n; } // monthTable /** * construct a Hashtable using the integer as the key and grade type String as the value */ private Hashtable gradeTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(2), rb.getString("letter")); n.put(new Integer(3), rb.getString("points")); n.put(new Integer(4), rb.getString("pass")); n.put(new Integer(5), rb.getString("check")); n.put(new Integer(1), rb.getString("ungra")); return n; } // gradeTypeTable /** * construct a Hashtable using the integer as the key and submission type String as the value */ private Hashtable submissionTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("inlin")); n.put(new Integer(2), rb.getString("attaonly")); n.put(new Integer(3), rb.getString("inlinatt")); n.put(new Integer(4), rb.getString("nonelec")); return n; } // submissionTypeTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the UserSubmission clas */ public class UserSubmission { /** * the User object */ User m_user = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; public UserSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { m_state = state; m_criteria = criteria; m_asc = asc; } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group rv = rv.concat(site.getGroup((String) k.next()).getTitle()); } } catch (Exception ignore) { } } return rv; } // getAssignmentRange /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { - String lName1 = u1.getUser().getLastName(); - String lName2 = u2.getUser().getLastName(); + String lName1 = u1.getUser().getSortName(); + String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare /** * get the submissin status */ private String getSubmissionStatus(SessionState state, AssignmentSubmission s) { String status = ""; if (s.getReturned()) { if (s.getTimeReturned() != null && s.getTimeSubmitted() != null && s.getTimeReturned().before(s.getTimeSubmitted())) { status = rb.getString("listsub.resubmi"); } else { status = rb.getString("gen.returned"); } } else if (s.getGraded()) { if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { status = rb.getString("grad3"); } else { status = rb.getString("gen.commented"); } } else { status = rb.getString("gen.ung1"); } return status; } // getSubmissionStatus /** * get the status string of assignment */ private String getAssignmentStatus(Assignment a) { String status = ""; Time currentTime = TimeService.newTime(); if (a.getDraft()) status = rb.getString("draft2"); else if (a.getOpenTime().after(currentTime)) status = rb.getString("notope"); else if (a.getDueTime().after(currentTime)) status = rb.getString("ope"); else if ((a.getCloseTime() != null) && (a.getCloseTime().before(currentTime))) status = rb.getString("clos"); else status = rb.getString("due2"); return status; } // getAssignmentStatus /** * get submission status */ private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment) { String status = ""; if (submission != null) if (submission.getSubmitted()) if (submission.getGraded() && submission.getGradeReleased()) status = rb.getString("grad3"); else if (submission.getReturned()) status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull(); else { status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull(); if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late"); } else status = rb.getString("inpro"); else status = rb.getString("notsta"); return status; } // getSubmissionStatus /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("nogra"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass2"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check2"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to Vector */ private Vector iterator_to_vector(Iterator l) { Vector v = new Vector(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_vector /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new Vector(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || !allowAddAssignment) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); try { String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted.equals("")) { // show not deleted assignments Time openTime = a.getOpenTime(); if (openTime != null && currentTime.after(openTime) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && AssignmentService.getSubmission(a.getReference(), (User) state .getAttribute(STATE_USER)) != null) { // and those deleted assignments but the user has made submissions to them returnResources.add(a); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } } } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { Vector submissions = new Vector(); Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING))); if (assignments.size() > 0) { // users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ()); } for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || deleted.equals("")) && (!a.getDraft())) { try { Vector assignmentSubmissions = iterator_to_vector(AssignmentService.getSubmissions(a)); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s .getTimeReturned()))))) { // has been subitted or has been returned and not work on it yet submissions.add(s); } // if-else } } catch (Exception e) { } } } returnResources = submissions; } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); Iterator submissionsIterator = AssignmentService.getSubmissions(a); List submissions = new Vector(); while (submissionsIterator.hasNext()) { submissions.add(submissionsIterator.next()); } // get all active site users String authzGroupId = SiteService.siteReference(contextString); // all users that can submit List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupId); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { boolean found = false; for (int i = 0; !found && i<submissions.size();i++) { AssignmentSubmission s = (AssignmentSubmission) submissions.get(i); if (s.getSubmitterIds().contains(userId)) { returnResources.add(new UserSubmission(u, s)); found = true; } } // add those users who haven't made any submissions if (!found) { // construct fake submissions for grading purpose AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId()); s.removeSubmitter(UserDirectoryService.getCurrentUser()); s.addSubmitter(u); s.setSubmitted(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); returnResources.add(new UserSubmission(u, sub)); } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } } } catch (Exception e) { Log.warn("chef", e.getMessage() + " authGroupId=" + authzGroupId); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && !sort.startsWith("sorted_grade_submission_by")) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && sort.startsWith("sorted_submission_by")) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending)); } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (viewMode.equals(MODE_LIST_ASSIGNMENTS)) { doList_assignments(data); } else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { doView_students_assignment(data); } else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { doReport_submissions(data); } else if (viewMode.equals(MODE_STUDENT_VIEW)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade? */ private void validPointGrade(SessionState state, String grade) { if (grade != null && !grade.equals("")) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { int index = grade.indexOf("."); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!grade.equals(".")) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } else { // grade is "." addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } } } // validPointGrade private void alertInvalidPoint(SessionState state, String grade) { String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, rb.getString("plesuse4") + maxInt + "." + maxDec + "."); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { if (grade.indexOf(".") != -1) { if (grade.startsWith(".")) { grade = "0".concat(grade); } else if (grade.endsWith(".")) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf("."); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if (point.equals("00")) { point = "0"; } } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuffer alertMsg = new StringBuffer(); try { boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } catch (Exception e) { Log.warn("chef", this + ": ", e); return strFromBrowser; } } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuffer buf = new StringBuffer(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors buf = new StringBuffer(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuffer buf = new StringBuffer(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuffer buf = new StringBuffer(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuffer buf = new StringBuffer(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION) || mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("cancel")) { // cancel doCancel_show_submission(data); } else if (option.equals("preview")) { // preview doPreview_submission(data); } else if (option.equals("save")) { // save draft doSave_submission(data); } else if (option.equals("post")) { // post doPost_submission(data); } else if (option.equals("revise")) { // done preview doDone_preview_submission(data); } else if (option.equals("attach")) { // attach doAttachments(data); } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = params.getString("defaultGrade"); String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List userSubmissions = new Vector(); if (state.getAttribute(USER_SUBMISSIONS) != null) { userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS); } // constructor a new UserSubmissions list List userSubmissionsNew = new Vector(); for (int i = 0; i<userSubmissions.size(); i++) { // get the UserSubmission object UserSubmission us = (UserSubmission) userSubmissions.get(i); User u = us.getUser(); AssignmentSubmission submission = us.getSubmission(); // check whether there is a submission associated if (submission == null) { AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId); s.removeSubmitter(UserDirectoryService.getCurrentUser()); s.addSubmitter(u); // submitted by without submit time s.setSubmitted(true); s.setGrade(grade); s.setGraded(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); userSubmissionsNew.add(new UserSubmission(u, sub)); } else if (submission.getTimeSubmitted() == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); sEdit.setAssignment(a); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else { // no change for this user userSubmissionsNew.add(us); } } state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew); } } catch (Exception e) { Log.warn("chef", e.toString()); } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); return providers; } private void addActivity(Context context, Assignment assignment) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("activity", assignmentActivityProducer .getActivity(assignment)); } private void addItem(Context context, AssignmentSubmission submission, String userId) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("item", assignmentActivityProducer .getItem(submission, userId)); } }
true
true
public int compare(Object o1, Object o2) { int result = -1; /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getLastName(); String lName2 = u2.getUser().getLastName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare
public int compare(Object o1, Object o2) { int result = -1; /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { String s1 = getAssignmentStatus((Assignment) o1); String s2 = getAssignmentStatus((Assignment) o2); result = s1.compareToIgnoreCase(s2); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String status1 = getSubmissionStatus(submission1, (Assignment) o1); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String status2 = getSubmissionStatus(submission2, (Assignment) o2); result = status1.compareTo(status2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = grade1.compareTo(grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = factor1.compareToIgnoreCase(factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = factor1.compareToIgnoreCase(factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = lName1.toLowerCase().compareTo(lName2.toLowerCase()); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = getSubmissionStatus(m_state, (AssignmentSubmission) s1); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = getSubmissionStatus(m_state, (AssignmentSubmission) s2); } } result = status1.toLowerCase().compareTo(status2.toLowerCase()); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = released1.compareTo(released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getLastName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getLastName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getLastName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getLastName()); } } result = submitters1.toLowerCase().compareTo(submitters2.toLowerCase()); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status String status1 = getSubmissionStatus(m_state, (AssignmentSubmission) o1); String status2 = getSubmissionStatus(m_state, (AssignmentSubmission) o2); result = status1.compareTo(status2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = (new Integer(grade1)).intValue() > (new Integer(grade2)).intValue() ? 1 : -1; } } else { result = grade1.compareTo(grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = released1.compareTo(released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = title1.toLowerCase().compareTo(title2.toLowerCase()); } // sort ascending or descending if (m_asc.equals(Boolean.FALSE.toString())) { result = -result; } return result; } // compare
diff --git a/src/com/android/browser/OpenDownloadReceiver.java b/src/com/android/browser/OpenDownloadReceiver.java index 3970a5f0..0f0ba705 100644 --- a/src/com/android/browser/OpenDownloadReceiver.java +++ b/src/com/android/browser/OpenDownloadReceiver.java @@ -1,74 +1,74 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.browser; import android.app.DownloadManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; /** * This {@link BroadcastReceiver} handles clicks to notifications that * downloads from the browser are in progress/complete. Clicking on an * in-progress or failed download will open the download manager. Clicking on * a complete, successful download will open the file. */ public class OpenDownloadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) { openDownloadsPage(context); return; } long ids[] = intent.getLongArrayExtra( DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS); if (ids == null || ids.length == 0) { openDownloadsPage(context); return; } long id = ids[0]; DownloadManager manager = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE); Uri uri = manager.getUriForDownloadedFile(id); if (uri == null) { // Open the downloads page openDownloadsPage(context); } else { Intent launchIntent = new Intent(Intent.ACTION_VIEW); - launchIntent.setDataAndType(uri, context.getContentResolver().getType(uri)); + launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(id)); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(launchIntent); } catch (ActivityNotFoundException e) { openDownloadsPage(context); } } } /** * Open the Activity which shows a list of all downloads. * @param context */ private void openDownloadsPage(Context context) { Intent pageView = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS); pageView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(pageView); } }
true
true
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) { openDownloadsPage(context); return; } long ids[] = intent.getLongArrayExtra( DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS); if (ids == null || ids.length == 0) { openDownloadsPage(context); return; } long id = ids[0]; DownloadManager manager = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE); Uri uri = manager.getUriForDownloadedFile(id); if (uri == null) { // Open the downloads page openDownloadsPage(context); } else { Intent launchIntent = new Intent(Intent.ACTION_VIEW); launchIntent.setDataAndType(uri, context.getContentResolver().getType(uri)); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(launchIntent); } catch (ActivityNotFoundException e) { openDownloadsPage(context); } } }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) { openDownloadsPage(context); return; } long ids[] = intent.getLongArrayExtra( DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS); if (ids == null || ids.length == 0) { openDownloadsPage(context); return; } long id = ids[0]; DownloadManager manager = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE); Uri uri = manager.getUriForDownloadedFile(id); if (uri == null) { // Open the downloads page openDownloadsPage(context); } else { Intent launchIntent = new Intent(Intent.ACTION_VIEW); launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(id)); launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(launchIntent); } catch (ActivityNotFoundException e) { openDownloadsPage(context); } } }
diff --git a/src/org/genyris/email/SendFunction.java b/src/org/genyris/email/SendFunction.java index c258136..a111bf0 100644 --- a/src/org/genyris/email/SendFunction.java +++ b/src/org/genyris/email/SendFunction.java @@ -1,87 +1,88 @@ // Copyright 2009 Peter William Birch <[email protected]> // // This software may be used and distributed according to the terms // of the Genyris License, in the file "LICENSE", incorporated herein by reference. // package org.genyris.email; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.genyris.core.Constants; import org.genyris.core.Exp; import org.genyris.core.Pair; import org.genyris.core.StrinG; import org.genyris.exception.AccessException; import org.genyris.exception.GenyrisException; import org.genyris.interp.ApplicableFunction; import org.genyris.interp.Closure; import org.genyris.interp.Environment; import org.genyris.interp.Interpreter; import org.genyris.interp.UnboundException; public class SendFunction extends ApplicableFunction { public SendFunction(Interpreter interp) { super(interp, Constants.PREFIX_EMAIL + "send", true); } public void postMail( Exp recipients, String subject, String message , String from, String server) throws MessagingException, AccessException { boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", server); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length(NIL)]; for (int i = 0; i < addressTo.length; i++) { addressTo[i] = new InternetAddress(recipients.car().toString()); + recipients = recipients.cdr(); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); Transport.send(msg); } public Exp bindAndExecute(Closure proc, Exp[] arguments, Environment envForBindOperations) throws GenyrisException { Class[] types = {Pair.class, StrinG.class, StrinG.class, StrinG.class, StrinG.class}; checkArgumentTypes(types, arguments); try { postMail( arguments[0] , arguments[1].toString(), arguments[2].toString() , arguments[3].toString(), arguments[4].toString()); } catch (MessagingException e) { throw new GenyrisException (e.getMessage()); } return NIL; } public static void bindFunctionsAndMethods(Interpreter interpreter) throws UnboundException, GenyrisException { interpreter.bindGlobalProcedureInstance(new SendFunction(interpreter)); } }
true
true
public void postMail( Exp recipients, String subject, String message , String from, String server) throws MessagingException, AccessException { boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", server); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length(NIL)]; for (int i = 0; i < addressTo.length; i++) { addressTo[i] = new InternetAddress(recipients.car().toString()); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); Transport.send(msg); }
public void postMail( Exp recipients, String subject, String message , String from, String server) throws MessagingException, AccessException { boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", server); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length(NIL)]; for (int i = 0; i < addressTo.length; i++) { addressTo[i] = new InternetAddress(recipients.car().toString()); recipients = recipients.cdr(); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); Transport.send(msg); }
diff --git a/src/java/se/idega/idegaweb/commune/accounting/presentation/RegulationSearchPanel.java b/src/java/se/idega/idegaweb/commune/accounting/presentation/RegulationSearchPanel.java index 25dcfdbb..c8002edc 100644 --- a/src/java/se/idega/idegaweb/commune/accounting/presentation/RegulationSearchPanel.java +++ b/src/java/se/idega/idegaweb/commune/accounting/presentation/RegulationSearchPanel.java @@ -1,473 +1,475 @@ /* * Created on 5.11.2003 * */ package se.idega.idegaweb.commune.accounting.presentation; import java.rmi.RemoteException; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.ejb.FinderException; import se.idega.idegaweb.commune.accounting.posting.business.PostingBusiness; import se.idega.idegaweb.commune.accounting.posting.business.PostingException; import se.idega.idegaweb.commune.accounting.regulations.business.PaymentFlowConstant; import se.idega.idegaweb.commune.accounting.regulations.business.RegulationsBusiness; import se.idega.idegaweb.commune.accounting.regulations.data.Regulation; import se.idega.idegaweb.commune.accounting.regulations.data.RegulationHome; import se.idega.idegaweb.commune.accounting.school.data.Provider; import com.idega.block.school.business.SchoolBusiness; import com.idega.block.school.data.School; import com.idega.block.school.data.SchoolCategory; import com.idega.block.school.data.SchoolHome; import com.idega.block.school.data.SchoolType; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.presentation.IWContext; import com.idega.presentation.PresentationObject; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Parameter; /** * @author Roar * * Search panel for searchin in regulations and postings. * The panel shows a dropdown with providers, a field for regulation name and a field * for date. */ public class RegulationSearchPanel extends AccountingBlock { private static final String KEY_PROVIDER = "provider"; private static final String KEY_PLACING = "placing"; private static final String KEY_VALID_DATE = "valid_date"; private static final String KEY_SEARCH = "search"; private static String PAR_PROVIDER = KEY_PROVIDER; public static final String PAR_PLACING = KEY_PLACING; public static final String PAR_VALID_DATE = KEY_VALID_DATE; private static final String PAR_ENTRY_PK = "PAR_ENTRY_PK"; public static final String SEARCH_REGULATION = "ACTION_SEARCH_REGULATION"; private Regulation _currentRegulation = null; private Collection _searchResult = null; private SchoolCategory _currentSchoolCategory = null; private SchoolType _currentSchoolType = null; private String[] _currentPosting = null; private School _currentSchool = null; private Date _validDate = null; private String _currentPlacing = null; private String _placingErrorMessage = null; private String _dateFormatErrorMessage = null; private PostingException _postingException = null; private boolean _outFlowOnly = false; //Force the request to be processed at once. private RegulationSearchPanel(){ super(); } public RegulationSearchPanel(IWContext iwc){ super(); process(iwc); } public RegulationSearchPanel(IWContext iwc, String providerKey){ super(); PAR_PROVIDER = providerKey; process(iwc); } /* (non-Javadoc) * @see se.idega.idegaweb.commune.accounting.presentation.AccountingBlock#init(com.idega.presentation.IWContext) */ public void init(IWContext iwc) throws Exception { process(iwc); //This should not be necessary, as the request will always be processed by now... maintainParameter(PAR_PLACING); maintainParameter(PAR_PROVIDER); maintainParameter(PAR_VALID_DATE); add(getSearchForm(iwc)); if (_searchResult != null){ add(getResultList(iwc, _searchResult)); } } private boolean processed = false; /** * Processes the request: does the actual search or lookup so that the * enclosing block can use the result to populate fields. * @param iwc */ public void process(IWContext iwc){ if (! processed){ boolean searchAction = iwc.getParameter(SEARCH_REGULATION) != null; //Find selected category, date and provider String vDate = iwc.getParameter(PAR_VALID_DATE); _validDate = parseDate(vDate); if (vDate != null && vDate.length() > 0 && _validDate == null){ _dateFormatErrorMessage = localize("regulation_search_panel.date_format_error", "Error i dateformat"); } else { _currentSchool = null; //First time on this page: PAR_PROVIDER parameter not set if (iwc.getParameter(PAR_PROVIDER) != null){ try{ SchoolHome schoolHome = (SchoolHome) IDOLookup.getHome(School.class); int currentSchoolId = new Integer(iwc.getParameter(PAR_PROVIDER)).intValue(); _currentSchool = schoolHome.findByPrimaryKey("" + currentSchoolId); }catch(RemoteException ex){ ex.printStackTrace(); }catch(FinderException ex){ ex.printStackTrace(); } } //Search regulations if (searchAction){ _searchResult = doSearch(iwc); } //Lookup regulation and postings String regId = iwc.getParameter(PAR_ENTRY_PK); //regId and _currentRegulation will get a value only after choosing a regulation (by clicking a link) if (regId != null){ _currentRegulation = getRegulation(regId); try{ RegulationsBusiness regBiz = (RegulationsBusiness) IBOLookup.getServiceInstance(iwc, RegulationsBusiness.class); PostingBusiness postingBiz = (PostingBusiness) IBOLookup.getServiceInstance(iwc, PostingBusiness.class); - _currentSchoolType = regBiz.getSchoolType(_currentRegulation); - _currentPosting = postingBiz.getPostingStrings(getCurrentSchoolCategory(iwc), _currentSchoolType, ((Integer) _currentRegulation.getRegSpecType().getPrimaryKey()).intValue(), new Provider(_currentSchool), _validDate); + if (_currentRegulation != null){ + _currentSchoolType = regBiz.getSchoolType(_currentRegulation); + _currentPosting = postingBiz.getPostingStrings(getCurrentSchoolCategory(iwc), _currentSchoolType, ((Integer) _currentRegulation.getRegSpecType().getPrimaryKey()).intValue(), new Provider(_currentSchool), _validDate); + } }catch (RemoteException ex){ ex.printStackTrace(); }catch (PostingException ex){ _postingException = ex; } } if (_currentRegulation!= null){ _currentPlacing = _currentRegulation.getName(); } else if (iwc.getParameter(PAR_PLACING) != null){ _currentPlacing = iwc.getParameter(PAR_PLACING); } } processed = true; } } public SchoolCategory getCurrentSchoolCategory(IWContext iwc){ if (_currentSchoolCategory == null){ try { SchoolBusiness schoolBusiness = (SchoolBusiness) IBOLookup.getServiceInstance(iwc.getApplicationContext(), SchoolBusiness.class); String opField = getSession().getOperationalField(); _currentSchoolCategory = schoolBusiness.getSchoolCategoryHome().findByPrimaryKey(opField); } catch (RemoteException e) { e.printStackTrace(); } catch (FinderException e) { e.printStackTrace(); } } return _currentSchoolCategory; } private List _maintainParameters = new ArrayList(); public void maintainParameter(String par){ _maintainParameters.add(par); } public void maintainParameter(String[] parameters){ for(int i = 0; i < parameters.length; i++){ _maintainParameters.add(parameters[i]); } } private List _setParameters = new ArrayList(); public void setParameter(String par, String value){ _setParameters.add(new Parameter(par, value)); } private void maintainParameters(IWContext iwc, Link link){ Iterator i = _maintainParameters.iterator(); while(i.hasNext()){ String par = (String) i.next(); link.maintainParameter(par, iwc); } } private void setParameters(Link link){ Iterator i = _setParameters.iterator(); while(i.hasNext()){ link.addParameter((Parameter) i.next()); } } /** * Formats the search results and returns a Table that displays it * as links, or an approperiate text if none where found * @param iwc * @param results * @return */ private Table getResultList(IWContext iwc, Collection results){ Table table = new Table(); table.setCellspacing(10); int row = 1, col = 0; if (results.size() == 0){ table.add(getErrorText(localize("regulation_search_panel.no_regulations_found", "No regulations found"))); } else { Iterator i = results.iterator(); HiddenInput h = new HiddenInput(PAR_ENTRY_PK, ""); table.add(h); while(i.hasNext()){ Regulation reg = (Regulation) i.next(); if (_outFlowOnly && reg.getPaymentFlowType().getLocalizationKey().equals(PaymentFlowConstant.OUT)) { continue; }else{ Link link = new Link(reg.getName() /* + " ("+formatDate(reg.getPeriodFrom(), 4) + "-" + formatDate(reg.getPeriodTo(), 4)+")"*/ ); link.addParameter(new Parameter(PAR_ENTRY_PK, reg.getPrimaryKey().toString())); maintainParameters(iwc, link); setParameters(link); //THIS doean't work for opera... but it should be neccessary to submit the form anyway... // link.setOnClick("getElementById('"+ pkId +"').value='"+ reg.getPrimaryKey() +"'"); // link.setToFormSubmit(form); if (col >= 3){ col = 1; row++; } else{ col++; } table.add(link, col, row); } } } return table; } /** * Does the search in the regulations and return them as a Collection */ private Collection doSearch(IWContext iwc){ Collection matches = new ArrayList(); String wcName = "%"+iwc.getParameter(PAR_PLACING)+"%"; try{ RegulationHome regHome = (RegulationHome) IDOLookup.getHome(Regulation.class); String catId = getCurrentSchoolCategoryId(iwc); matches = _validDate != null ? regHome.findRegulationsByNameNoCaseDateAndCategory(wcName, _validDate, catId) : regHome.findRegulationsByNameNoCaseAndCategory(wcName, catId); }catch(RemoteException ex){ ex.printStackTrace(); }catch(FinderException ex){ ex.printStackTrace(); } return matches; } /** * Does a lookup to find a regulation. * @param regId * @return the Regulation */ private Regulation getRegulation(String regId){ Regulation reg = null; try{ RegulationHome regHome = (RegulationHome) IDOLookup.getHome(Regulation.class); reg = regHome.findByPrimaryKey(regId); }catch(RemoteException ex){ ex.printStackTrace(); }catch(FinderException ex){ ex.printStackTrace(); } return reg; } /** * * @return the currently chosen Regulation */ public Regulation getRegulation(){ return _currentRegulation; } /** * * @return the currently chosen posting strings as String[] */ public String[] getPosting() throws PostingException{ if (_postingException != null){ throw _postingException; } return _currentPosting; } /** * Returns the search form as an Table * @param iwc * @return */ private Table getSearchForm(IWContext iwc) throws PostingException{ Collection providers = new ArrayList(); try{ SchoolHome home = (SchoolHome) IDOLookup.getHome(School.class); SchoolCategory category = getCurrentSchoolCategory(iwc); if (category != null){ providers = home.findAllByCategory(category); } }catch(RemoteException ex){ ex.printStackTrace(); }catch(FinderException ex){ ex.printStackTrace(); } Table table = new Table(); int row = 1; String currentSchoolId = _currentSchool != null ? "" + _currentSchool.getPrimaryKey() : "0"; addDropDown(table, PAR_PROVIDER, KEY_PROVIDER, providers, currentSchoolId, "getSchoolName", true, 1, row++); // Collection types = null; // try{ // types = _currentSchool != null ? _currentSchool.getSchoolTypes() : new ArrayList(); // }catch(IDORelationshipException ex ){ // ex.printStackTrace(); // } // if (! providers.isEmpty()){ // String currentTypeId = iwc.getParameter(PAR_TYPE) != null ? iwc.getParameter(PAR_TYPE) : "0"; // addDropDown(table, PAR_TYPE, KEY_TYPE, types, currentTypeId, "getName", false, 1, row++); // } if (_placingErrorMessage != null){ table.add(getErrorText(_placingErrorMessage), 2, row); } if (_dateFormatErrorMessage != null){ table.add(getErrorText(_dateFormatErrorMessage), 4, row); } if (_dateFormatErrorMessage != null || _placingErrorMessage != null){ row++; } addField(table, PAR_PLACING, KEY_PLACING, _currentPlacing, 1, row, 300); String date = iwc.getParameter(PAR_VALID_DATE) != null ? iwc.getParameter(PAR_VALID_DATE) : formatDate(new Date(System.currentTimeMillis()), 4); addField(table, PAR_VALID_DATE, KEY_VALID_DATE, date, 3, row, 35); table.add(getLocalizedButton(SEARCH_REGULATION, KEY_SEARCH, "Search"), 5, row++); table.setColumnWidth(1, "" + _leftColMinWidth); return table; } private int _leftColMinWidth = 0; public void setLeftColumnMinWidth(int minWidth){ _leftColMinWidth = minWidth; } private Table addDropDown(Table table, String parameter, String key, Collection options, String selected, String method, boolean setToSubmit, int col, int row) { DropdownMenu dropDown = getDropdownMenu(parameter, options, method); dropDown.setToSubmit(setToSubmit); dropDown.setSelectedElement(selected); return addWidget(table, key, dropDown, col, row); } private Table addField(Table table, String parameter, String key, String value, int col, int row, int width){ return addWidget(table, key, getTextInput(parameter, value, width), col, row); } private Table addWidget(Table table, String key, PresentationObject widget, int col, int row){ table.add(getLocalizedLabel(key, key), col, row); table.add(widget, col + 1, row); return table; } public void setOutFlowOnly(boolean b){ _outFlowOnly = b; } public void setPlacingIfNull(String placing) { if (_currentPlacing == null){ _currentPlacing = placing; } } public void setSchoolIfNull(School school) { if (_currentSchool == null){ _currentSchool = school; } } public void setError(String placingErrorMessage){ _placingErrorMessage = placingErrorMessage; } public School getSchool(){ return _currentSchool; } public String getCurrentSchoolCategoryId(IWContext iwc) throws RemoteException, FinderException{ SchoolBusiness schoolBusiness = (SchoolBusiness) IBOLookup.getServiceInstance(iwc.getApplicationContext(), SchoolBusiness.class); String opField = getSession().getOperationalField(); return schoolBusiness.getSchoolCategoryHome().findByPrimaryKey(opField).getPrimaryKey().toString(); } /** * @return */ public SchoolType getCurrentSchoolType() { return _currentSchoolType; } }
true
true
public void process(IWContext iwc){ if (! processed){ boolean searchAction = iwc.getParameter(SEARCH_REGULATION) != null; //Find selected category, date and provider String vDate = iwc.getParameter(PAR_VALID_DATE); _validDate = parseDate(vDate); if (vDate != null && vDate.length() > 0 && _validDate == null){ _dateFormatErrorMessage = localize("regulation_search_panel.date_format_error", "Error i dateformat"); } else { _currentSchool = null; //First time on this page: PAR_PROVIDER parameter not set if (iwc.getParameter(PAR_PROVIDER) != null){ try{ SchoolHome schoolHome = (SchoolHome) IDOLookup.getHome(School.class); int currentSchoolId = new Integer(iwc.getParameter(PAR_PROVIDER)).intValue(); _currentSchool = schoolHome.findByPrimaryKey("" + currentSchoolId); }catch(RemoteException ex){ ex.printStackTrace(); }catch(FinderException ex){ ex.printStackTrace(); } } //Search regulations if (searchAction){ _searchResult = doSearch(iwc); } //Lookup regulation and postings String regId = iwc.getParameter(PAR_ENTRY_PK); //regId and _currentRegulation will get a value only after choosing a regulation (by clicking a link) if (regId != null){ _currentRegulation = getRegulation(regId); try{ RegulationsBusiness regBiz = (RegulationsBusiness) IBOLookup.getServiceInstance(iwc, RegulationsBusiness.class); PostingBusiness postingBiz = (PostingBusiness) IBOLookup.getServiceInstance(iwc, PostingBusiness.class); _currentSchoolType = regBiz.getSchoolType(_currentRegulation); _currentPosting = postingBiz.getPostingStrings(getCurrentSchoolCategory(iwc), _currentSchoolType, ((Integer) _currentRegulation.getRegSpecType().getPrimaryKey()).intValue(), new Provider(_currentSchool), _validDate); }catch (RemoteException ex){ ex.printStackTrace(); }catch (PostingException ex){ _postingException = ex; } } if (_currentRegulation!= null){ _currentPlacing = _currentRegulation.getName(); } else if (iwc.getParameter(PAR_PLACING) != null){ _currentPlacing = iwc.getParameter(PAR_PLACING); } } processed = true; } }
public void process(IWContext iwc){ if (! processed){ boolean searchAction = iwc.getParameter(SEARCH_REGULATION) != null; //Find selected category, date and provider String vDate = iwc.getParameter(PAR_VALID_DATE); _validDate = parseDate(vDate); if (vDate != null && vDate.length() > 0 && _validDate == null){ _dateFormatErrorMessage = localize("regulation_search_panel.date_format_error", "Error i dateformat"); } else { _currentSchool = null; //First time on this page: PAR_PROVIDER parameter not set if (iwc.getParameter(PAR_PROVIDER) != null){ try{ SchoolHome schoolHome = (SchoolHome) IDOLookup.getHome(School.class); int currentSchoolId = new Integer(iwc.getParameter(PAR_PROVIDER)).intValue(); _currentSchool = schoolHome.findByPrimaryKey("" + currentSchoolId); }catch(RemoteException ex){ ex.printStackTrace(); }catch(FinderException ex){ ex.printStackTrace(); } } //Search regulations if (searchAction){ _searchResult = doSearch(iwc); } //Lookup regulation and postings String regId = iwc.getParameter(PAR_ENTRY_PK); //regId and _currentRegulation will get a value only after choosing a regulation (by clicking a link) if (regId != null){ _currentRegulation = getRegulation(regId); try{ RegulationsBusiness regBiz = (RegulationsBusiness) IBOLookup.getServiceInstance(iwc, RegulationsBusiness.class); PostingBusiness postingBiz = (PostingBusiness) IBOLookup.getServiceInstance(iwc, PostingBusiness.class); if (_currentRegulation != null){ _currentSchoolType = regBiz.getSchoolType(_currentRegulation); _currentPosting = postingBiz.getPostingStrings(getCurrentSchoolCategory(iwc), _currentSchoolType, ((Integer) _currentRegulation.getRegSpecType().getPrimaryKey()).intValue(), new Provider(_currentSchool), _validDate); } }catch (RemoteException ex){ ex.printStackTrace(); }catch (PostingException ex){ _postingException = ex; } } if (_currentRegulation!= null){ _currentPlacing = _currentRegulation.getName(); } else if (iwc.getParameter(PAR_PLACING) != null){ _currentPlacing = iwc.getParameter(PAR_PLACING); } } processed = true; } }
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/LaunchModeTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/LaunchModeTests.java index 1fa54b4eb..aa4635ccb 100644 --- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/LaunchModeTests.java +++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/LaunchModeTests.java @@ -1,111 +1,115 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.debug.tests.core; import junit.framework.AssertionFailedError; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jdt.debug.testplugin.TestModeLaunchDelegate; import org.eclipse.jdt.debug.tests.AbstractDebugTest; /** * LaunchModeTests */ public class LaunchModeTests extends AbstractDebugTest { private ILaunchConfiguration fConfiguration; private String fMode; /** * @param name */ public LaunchModeTests(String name) { super(name); } /** * Called by launch "TestModeLaunchDelegate" delegate when launch method invoked. * * @param configuration * @param mode * @param launch */ public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch) { fConfiguration = configuration; fMode = mode; } /** * Tests that launch delegate for "TEST_MODE" and java apps is invoked when * "TEST_MODE" is used. * * @throws CoreException * @see TestModeLaunchDelegate */ public void testContributedLaunchMode() throws CoreException { + ILaunch launch = null; try { fConfiguration = null; fMode = null; TestModeLaunchDelegate.setTestCase(this); ILaunchConfiguration configuration = getLaunchConfiguration("Breakpoints"); assertNotNull(configuration); - configuration.launch("TEST_MODE", null); + launch = configuration.launch("TEST_MODE", null); assertEquals("Launch delegate not invoked", configuration, fConfiguration); assertEquals("Launch delegate not invoked in correct mode", "TEST_MODE", fMode); } finally { TestModeLaunchDelegate.setTestCase(null); fConfiguration = null; fMode = null; + if (launch != null) { + getLaunchManager().removeLaunch(launch); + } } } /** * Ensure our contributed launch mode exists. */ public void testLaunchModes() { String[] modes = getLaunchManager().getLaunchModes(); assertContains("Missing TEST_MODE", modes, "TEST_MODE"); assertContains("Missing debug mode", modes, ILaunchManager.DEBUG_MODE); assertContains("Missing run mode", modes, ILaunchManager.RUN_MODE); } /** * Asserts that the array contains the given object */ static public void assertContains(String message, Object[] array, Object object) { for (int i = 0; i < array.length; i++) { if (array[i].equals(object)) { return; } } throw new AssertionFailedError(message); } /** * Ensure our contributed mode is supported. * */ public void testSupportsMode() throws CoreException { ILaunchConfiguration configuration = getLaunchConfiguration("Breakpoints"); assertNotNull(configuration); assertTrue("Java application configuration should support TEST_MODE", configuration.supportsMode("TEST_MODE")); assertTrue("Java application type should support TEST_MODE", configuration.getType().supportsMode("TEST_MODE")); assertTrue("Java application configuration should support debug mode", configuration.supportsMode(ILaunchManager.DEBUG_MODE)); assertTrue("Java application type should support debug mode", configuration.getType().supportsMode(ILaunchManager.DEBUG_MODE)); assertTrue("Java application configuration should support run mode", configuration.supportsMode(ILaunchManager.RUN_MODE)); assertTrue("Java application type should support run mode", configuration.getType().supportsMode(ILaunchManager.RUN_MODE)); } }
false
true
public void testContributedLaunchMode() throws CoreException { try { fConfiguration = null; fMode = null; TestModeLaunchDelegate.setTestCase(this); ILaunchConfiguration configuration = getLaunchConfiguration("Breakpoints"); assertNotNull(configuration); configuration.launch("TEST_MODE", null); assertEquals("Launch delegate not invoked", configuration, fConfiguration); assertEquals("Launch delegate not invoked in correct mode", "TEST_MODE", fMode); } finally { TestModeLaunchDelegate.setTestCase(null); fConfiguration = null; fMode = null; } }
public void testContributedLaunchMode() throws CoreException { ILaunch launch = null; try { fConfiguration = null; fMode = null; TestModeLaunchDelegate.setTestCase(this); ILaunchConfiguration configuration = getLaunchConfiguration("Breakpoints"); assertNotNull(configuration); launch = configuration.launch("TEST_MODE", null); assertEquals("Launch delegate not invoked", configuration, fConfiguration); assertEquals("Launch delegate not invoked in correct mode", "TEST_MODE", fMode); } finally { TestModeLaunchDelegate.setTestCase(null); fConfiguration = null; fMode = null; if (launch != null) { getLaunchManager().removeLaunch(launch); } } }
diff --git a/src/cz/muni/stanse/checker/ErrorTrace.java b/src/cz/muni/stanse/checker/ErrorTrace.java index 81b16fe..d46512a 100644 --- a/src/cz/muni/stanse/checker/ErrorTrace.java +++ b/src/cz/muni/stanse/checker/ErrorTrace.java @@ -1,160 +1,160 @@ /** * @brief * */ package cz.muni.stanse.checker; import cz.muni.stanse.parser.CFG; import cz.muni.stanse.parser.CFGNode; import cz.muni.stanse.utils.Trinity; import java.util.List; /** * @brief * * @see */ public final class ErrorTrace { // public section /** * @brief * * @param * @return * @throws * @see */ public ErrorTrace(String shortDesc, String fullDesc, List< Trinity<CFGNode,String,CFG> > trace) { this.shortDesc = shortDesc; this.fullDesc = fullDesc; this.trace = trace; } /** * @brief * * @param * @return * @throws * @see */ public String getShortDescription() { return shortDesc; } /** * @brief * * @param * @return * @throws * @see */ public String getFullDescription() { return fullDesc; } /** * @brief * * @param * @return * @throws * @see */ public List< Trinity<CFGNode,String,CFG> > getErrorTrace() { return trace; } /** * @brief * * @param * @return * @throws * @see java.lang.Object#toString() */ @Override public String toString() { String result = "- ErrorTrace:\n" + " - shortDesc: " + getShortDescription() + '\n'+ " - fullDesc: " + getFullDescription() + '\n' + " - CFGNodes:\n"; for (Trinity<CFGNode,String,CFG> node : getErrorTrace()) result += " - <" + node.getFirst().toString() + "," + node.getSecond() + "," + - node.getSecond().toString() + ">\n"; + node.getThird().toString() + ">\n"; return result; } /** * @brief * * @param * @return * @throws * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((fullDesc == null) ? 0 : fullDesc.hashCode()); result = PRIME * result + ((shortDesc == null) ? 0 : shortDesc.hashCode()); result = PRIME * result + ((trace == null) ? 0 : trace.hashCode()); return result; } /** * @brief * * @param * @return * @throws * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return (obj == null || getClass() != obj.getClass()) ? false : isEqualWith((ErrorTrace)obj); } /** * @brief * * @param * @return * @throws * @see */ public boolean isEqualWith(final ErrorTrace other) { return getShortDescription().equals(other.getShortDescription()) && getFullDescription().equals(other.getFullDescription()) && getErrorTrace().equals(other.getErrorTrace()); } // private section /** * @brief * */ private final String shortDesc; /** * @brief * */ private final String fullDesc; /** * @brief * */ private final List< Trinity<CFGNode,String,CFG> > trace; }
true
true
public String toString() { String result = "- ErrorTrace:\n" + " - shortDesc: " + getShortDescription() + '\n'+ " - fullDesc: " + getFullDescription() + '\n' + " - CFGNodes:\n"; for (Trinity<CFGNode,String,CFG> node : getErrorTrace()) result += " - <" + node.getFirst().toString() + "," + node.getSecond() + "," + node.getSecond().toString() + ">\n"; return result; }
public String toString() { String result = "- ErrorTrace:\n" + " - shortDesc: " + getShortDescription() + '\n'+ " - fullDesc: " + getFullDescription() + '\n' + " - CFGNodes:\n"; for (Trinity<CFGNode,String,CFG> node : getErrorTrace()) result += " - <" + node.getFirst().toString() + "," + node.getSecond() + "," + node.getThird().toString() + ">\n"; return result; }
diff --git a/omod/src/main/java/org/openmrs/module/reporting/web/reports/RunReportFormController.java b/omod/src/main/java/org/openmrs/module/reporting/web/reports/RunReportFormController.java index 7112945e..d5e9d1e3 100644 --- a/omod/src/main/java/org/openmrs/module/reporting/web/reports/RunReportFormController.java +++ b/omod/src/main/java/org/openmrs/module/reporting/web/reports/RunReportFormController.java @@ -1,369 +1,370 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.reporting.web.reports; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.api.context.Context; import org.openmrs.module.htmlwidgets.web.WidgetUtil; import org.openmrs.module.reporting.cohort.definition.CohortDefinition; import org.openmrs.module.reporting.common.ObjectUtil; import org.openmrs.module.reporting.evaluation.EvaluationContext; import org.openmrs.module.reporting.evaluation.EvaluationUtil; import org.openmrs.module.reporting.evaluation.parameter.Mapped; import org.openmrs.module.reporting.evaluation.parameter.Parameter; import org.openmrs.module.reporting.propertyeditor.MappedEditor; import org.openmrs.module.reporting.report.ReportRequest; import org.openmrs.module.reporting.report.ReportRequest.Priority; import org.openmrs.module.reporting.report.definition.ReportDefinition; import org.openmrs.module.reporting.report.definition.service.ReportDefinitionService; import org.openmrs.module.reporting.report.renderer.RenderingMode; import org.openmrs.module.reporting.report.renderer.ReportRenderer; import org.openmrs.module.reporting.report.service.ReportService; import org.openmrs.util.OpenmrsUtil; import org.quartz.CronExpression; import org.springframework.util.StringUtils; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.BaseCommandController; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.servlet.view.RedirectView; /** * This controller runs a report (which must be passed in with the reportId parameter) after * allowing the user to enter parameters (if any) and to choose a ReportRenderer. If the chosen * ReportRenderer is a WebReportRenderer, then the report data is placed in the session and this * page redirects to the WebReportRenderer's specified URL. Otherwise the renderer writes to this * form's response. */ public class RunReportFormController extends SimpleFormController implements Validator { private transient Log log = LogFactory.getLog(this.getClass()); /** * @see BaseCommandController#initBinder(HttpServletRequest, ServletRequestDataBinder) */ protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); binder.registerCustomEditor(Mapped.class, new MappedEditor()); } @SuppressWarnings("rawtypes") public boolean supports(Class c) { return c == CommandObject.class; } public void validate(Object commandObject, Errors errors) { CommandObject command = (CommandObject) commandObject; ValidationUtils.rejectIfEmpty(errors, "reportDefinition", "reporting.Report.run.error.missingReportID"); if (command.getReportDefinition() != null) { ReportDefinition reportDefinition = command.getReportDefinition(); Set<String> requiredParams = new HashSet<String>(); if (reportDefinition.getParameters() != null) { for (Parameter parameter : reportDefinition.getParameters()) { requiredParams.add(parameter.getName()); } } for (Map.Entry<String, Object> e : command.getUserEnteredParams().entrySet()) { if (e.getValue() instanceof Iterable || e.getValue() instanceof Object[]) { Object iterable = e.getValue(); if (e.getValue() instanceof Object[]) { iterable = Arrays.asList((Object[]) e.getValue()); } boolean hasNull = true; for (Object value : (Iterable<Object>) iterable) { hasNull = !ObjectUtil.notNull(value); } if (!hasNull) { requiredParams.remove(e.getKey()); } } else if (ObjectUtil.notNull(e.getValue())) { requiredParams.remove(e.getKey()); } } if (requiredParams.size() > 0) { for (Iterator<String> iterator = requiredParams.iterator(); iterator.hasNext();) { String parameterName = (String) iterator.next(); if (StringUtils.hasText(command.getExpressions().get(parameterName))) { String expression = command.getExpressions().get(parameterName); if (!EvaluationUtil.isExpression(expression)){ errors.rejectValue("expressions[" + parameterName + "]", "reporting.Report.run.error.invalidParamExpression"); } } else { errors.rejectValue("userEnteredParams[" + parameterName + "]", "error.required", new Object[] { "This parameter" }, "{0} is required"); } } } if (reportDefinition.getDataSetDefinitions() == null || reportDefinition.getDataSetDefinitions().size() == 0) { errors.reject("reporting.Report.run.error.definitionNotDeclared"); } if (ObjectUtil.notNull(command.getSchedule())) { if (!CronExpression.isValidExpression(command.getSchedule())) { errors.rejectValue("schedule", "reporting.Report.run.error.invalidCronExpression"); } } } ValidationUtils.rejectIfEmpty(errors, "selectedRenderer", "reporting.Report.run.error.noRendererSelected"); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { CommandObject command = new CommandObject(); if (Context.isAuthenticated()) { ReportDefinitionService rds = Context.getService(ReportDefinitionService.class); ReportService reportService = Context.getService(ReportService.class); if (StringUtils.hasText(request.getParameter("copyRequest"))) { ReportRequest req = reportService.getReportRequestByUuid(request.getParameter("copyRequest")); // avoid lazy init exceptions command.setReportDefinition(rds.getDefinitionByUuid(req.getReportDefinition().getParameterizable().getUuid())); for (Map.Entry<String, Object> param : req.getReportDefinition().getParameterMappings().entrySet()) { command.getUserEnteredParams().put(param.getKey(), param.getValue()); } command.setSelectedRenderer(req.getRenderingMode().getDescriptor()); } else if (StringUtils.hasText(request.getParameter("requestUuid"))) { String reqUuid = request.getParameter("requestUuid"); ReportRequest rr = reportService.getReportRequestByUuid(reqUuid); command.setExistingRequestUuid(reqUuid); command.setReportDefinition(rr.getReportDefinition().getParameterizable()); command.setUserEnteredParams(rr.getReportDefinition().getParameterMappings()); command.setBaseCohort(rr.getBaseCohort()); command.setSelectedRenderer(rr.getRenderingMode().getDescriptor()); command.setSchedule(rr.getSchedule()); } else { String uuid = request.getParameter("reportId"); ReportDefinition reportDefinition = rds.getDefinitionByUuid(uuid); command.setReportDefinition(reportDefinition); } command.setRenderingModes(reportService.getRenderingModes(command.getReportDefinition())); } return command; } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObject, BindException errors) throws Exception { CommandObject command = (CommandObject) commandObject; ReportDefinition reportDefinition = command.getReportDefinition(); ReportService rs = Context.getService(ReportService.class); // Parse the input parameters into appropriate objects and fail validation if any are invalid Map<String, Object> params = new LinkedHashMap<String, Object>(); if (reportDefinition.getParameters() != null && (command.getUserEnteredParams() != null || command.getExpressions() != null)) { for (Parameter parameter : reportDefinition.getParameters()) { Object value = null; String expression = null; if(command.getExpressions() != null && ObjectUtil.notNull(command.getExpressions().get(parameter.getName()))) expression = command.getExpressions().get(parameter.getName()); else value = command.getUserEnteredParams().get(parameter.getName()); if (ObjectUtil.notNull(value) || ObjectUtil.notNull(expression)) { try { if (StringUtils.hasText(expression)) value = expression; else value = WidgetUtil.parseInput(value, parameter.getType(), parameter.getCollectionType()); params.put(parameter.getName(), value); } catch (Exception ex) { errors.rejectValue("userEnteredParams[" + parameter.getName() + "]", ex.getMessage()); } } } } // Ensure that the chosen renderer is valid for this report RenderingMode renderingMode = command.getSelectedMode(); if (!renderingMode.getRenderer().canRender(reportDefinition)) { errors.rejectValue("selectedRenderer", "reporting.Report.run.error.invalidRenderer"); } if (errors.hasErrors()) { return showForm(request, response, errors); } ReportRequest rr = null; if (command.getExistingRequestUuid() != null) { rr = rs.getReportRequestByUuid(command.getExistingRequestUuid()); } else { rr = new ReportRequest(); } rr.setReportDefinition(new Mapped<ReportDefinition>(reportDefinition, params)); rr.setBaseCohort(command.getBaseCohort()); rr.setRenderingMode(command.getSelectedMode()); rr.setPriority(Priority.NORMAL); rr.setSchedule(command.getSchedule()); // TODO: We might want to check here if this exact same report request is already queued and just re-direct if so rr = rs.queueReport(rr); rs.processNextQueuedReports(); return new ModelAndView(new RedirectView("../reports/reportHistoryOpen.form?uuid="+rr.getUuid())); } /** * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest) */ @Override protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); EvaluationContext ec = new EvaluationContext(); Set<String> expSupportedTypes = new HashSet<String>(); for (Object value : ec.getContextValues().values()) { expSupportedTypes.add(value.getClass().getName()); } map.put("expSupportedTypes", expSupportedTypes); return map; } public class CommandObject { private String existingRequestUuid; private ReportDefinition reportDefinition; private Mapped<CohortDefinition> baseCohort; private Map<String, Object> userEnteredParams; private String selectedRenderer; // as RendererClass!Arg private String schedule; private Map<String, String> expressions; private List<RenderingMode> renderingModes; public CommandObject() { userEnteredParams = new LinkedHashMap<String, Object>(); + expressions = new HashMap<String ,String>(); } @SuppressWarnings("unchecked") public RenderingMode getSelectedMode() { if (selectedRenderer != null) { try { String[] temp = selectedRenderer.split("!"); Class<? extends ReportRenderer> rc = (Class<? extends ReportRenderer>) Context.loadClass(temp[0]); String arg = (temp.length > 1 && StringUtils.hasText(temp[1])) ? temp[1] : null; for (RenderingMode mode : renderingModes) { if (mode.getRenderer().getClass().equals(rc) && OpenmrsUtil.nullSafeEquals(mode.getArgument(), arg)) { return mode; } } log.warn("Could not find requested rendering mode: " + selectedRenderer); } catch (Exception e) { log.warn("Could not load requested renderer", e); } } return null; } public String getExistingRequestUuid() { return existingRequestUuid; } public void setExistingRequestUuid(String existingRequestUuid) { this.existingRequestUuid = existingRequestUuid; } public List<RenderingMode> getRenderingModes() { return renderingModes; } public void setRenderingModes(List<RenderingMode> rendereringModes) { this.renderingModes = rendereringModes; } public ReportDefinition getReportDefinition() { return reportDefinition; } public void setReportDefinition(ReportDefinition reportDefinition) { this.reportDefinition = reportDefinition; } public Mapped<CohortDefinition> getBaseCohort() { return baseCohort; } public void setBaseCohort(Mapped<CohortDefinition> baseCohort) { this.baseCohort = baseCohort; } public String getSelectedRenderer() { return selectedRenderer; } public void setSelectedRenderer(String selectedRenderer) { this.selectedRenderer = selectedRenderer; } public Map<String, Object> getUserEnteredParams() { return userEnteredParams; } public void setUserEnteredParams(Map<String, Object> userEnteredParams) { this.userEnteredParams = userEnteredParams; } public String getSchedule() { return schedule; } public void setSchedule(String schedule) { this.schedule = schedule; } /** * @return the expressions */ public Map<String, String> getExpressions() { return expressions; } /** * @param expressions the expressions to set */ public void setExpressions(Map<String, String> expressions) { this.expressions = expressions; } } }
true
true
public void validate(Object commandObject, Errors errors) { CommandObject command = (CommandObject) commandObject; ValidationUtils.rejectIfEmpty(errors, "reportDefinition", "reporting.Report.run.error.missingReportID"); if (command.getReportDefinition() != null) { ReportDefinition reportDefinition = command.getReportDefinition(); Set<String> requiredParams = new HashSet<String>(); if (reportDefinition.getParameters() != null) { for (Parameter parameter : reportDefinition.getParameters()) { requiredParams.add(parameter.getName()); } } for (Map.Entry<String, Object> e : command.getUserEnteredParams().entrySet()) { if (e.getValue() instanceof Iterable || e.getValue() instanceof Object[]) { Object iterable = e.getValue(); if (e.getValue() instanceof Object[]) { iterable = Arrays.asList((Object[]) e.getValue()); } boolean hasNull = true; for (Object value : (Iterable<Object>) iterable) { hasNull = !ObjectUtil.notNull(value); } if (!hasNull) { requiredParams.remove(e.getKey()); } } else if (ObjectUtil.notNull(e.getValue())) { requiredParams.remove(e.getKey()); } } if (requiredParams.size() > 0) { for (Iterator<String> iterator = requiredParams.iterator(); iterator.hasNext();) { String parameterName = (String) iterator.next(); if (StringUtils.hasText(command.getExpressions().get(parameterName))) { String expression = command.getExpressions().get(parameterName); if (!EvaluationUtil.isExpression(expression)){ errors.rejectValue("expressions[" + parameterName + "]", "reporting.Report.run.error.invalidParamExpression"); } } else { errors.rejectValue("userEnteredParams[" + parameterName + "]", "error.required", new Object[] { "This parameter" }, "{0} is required"); } } } if (reportDefinition.getDataSetDefinitions() == null || reportDefinition.getDataSetDefinitions().size() == 0) { errors.reject("reporting.Report.run.error.definitionNotDeclared"); } if (ObjectUtil.notNull(command.getSchedule())) { if (!CronExpression.isValidExpression(command.getSchedule())) { errors.rejectValue("schedule", "reporting.Report.run.error.invalidCronExpression"); } } } ValidationUtils.rejectIfEmpty(errors, "selectedRenderer", "reporting.Report.run.error.noRendererSelected"); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { CommandObject command = new CommandObject(); if (Context.isAuthenticated()) { ReportDefinitionService rds = Context.getService(ReportDefinitionService.class); ReportService reportService = Context.getService(ReportService.class); if (StringUtils.hasText(request.getParameter("copyRequest"))) { ReportRequest req = reportService.getReportRequestByUuid(request.getParameter("copyRequest")); // avoid lazy init exceptions command.setReportDefinition(rds.getDefinitionByUuid(req.getReportDefinition().getParameterizable().getUuid())); for (Map.Entry<String, Object> param : req.getReportDefinition().getParameterMappings().entrySet()) { command.getUserEnteredParams().put(param.getKey(), param.getValue()); } command.setSelectedRenderer(req.getRenderingMode().getDescriptor()); } else if (StringUtils.hasText(request.getParameter("requestUuid"))) { String reqUuid = request.getParameter("requestUuid"); ReportRequest rr = reportService.getReportRequestByUuid(reqUuid); command.setExistingRequestUuid(reqUuid); command.setReportDefinition(rr.getReportDefinition().getParameterizable()); command.setUserEnteredParams(rr.getReportDefinition().getParameterMappings()); command.setBaseCohort(rr.getBaseCohort()); command.setSelectedRenderer(rr.getRenderingMode().getDescriptor()); command.setSchedule(rr.getSchedule()); } else { String uuid = request.getParameter("reportId"); ReportDefinition reportDefinition = rds.getDefinitionByUuid(uuid); command.setReportDefinition(reportDefinition); } command.setRenderingModes(reportService.getRenderingModes(command.getReportDefinition())); } return command; } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObject, BindException errors) throws Exception { CommandObject command = (CommandObject) commandObject; ReportDefinition reportDefinition = command.getReportDefinition(); ReportService rs = Context.getService(ReportService.class); // Parse the input parameters into appropriate objects and fail validation if any are invalid Map<String, Object> params = new LinkedHashMap<String, Object>(); if (reportDefinition.getParameters() != null && (command.getUserEnteredParams() != null || command.getExpressions() != null)) { for (Parameter parameter : reportDefinition.getParameters()) { Object value = null; String expression = null; if(command.getExpressions() != null && ObjectUtil.notNull(command.getExpressions().get(parameter.getName()))) expression = command.getExpressions().get(parameter.getName()); else value = command.getUserEnteredParams().get(parameter.getName()); if (ObjectUtil.notNull(value) || ObjectUtil.notNull(expression)) { try { if (StringUtils.hasText(expression)) value = expression; else value = WidgetUtil.parseInput(value, parameter.getType(), parameter.getCollectionType()); params.put(parameter.getName(), value); } catch (Exception ex) { errors.rejectValue("userEnteredParams[" + parameter.getName() + "]", ex.getMessage()); } } } } // Ensure that the chosen renderer is valid for this report RenderingMode renderingMode = command.getSelectedMode(); if (!renderingMode.getRenderer().canRender(reportDefinition)) { errors.rejectValue("selectedRenderer", "reporting.Report.run.error.invalidRenderer"); } if (errors.hasErrors()) { return showForm(request, response, errors); } ReportRequest rr = null; if (command.getExistingRequestUuid() != null) { rr = rs.getReportRequestByUuid(command.getExistingRequestUuid()); } else { rr = new ReportRequest(); } rr.setReportDefinition(new Mapped<ReportDefinition>(reportDefinition, params)); rr.setBaseCohort(command.getBaseCohort()); rr.setRenderingMode(command.getSelectedMode()); rr.setPriority(Priority.NORMAL); rr.setSchedule(command.getSchedule()); // TODO: We might want to check here if this exact same report request is already queued and just re-direct if so rr = rs.queueReport(rr); rs.processNextQueuedReports(); return new ModelAndView(new RedirectView("../reports/reportHistoryOpen.form?uuid="+rr.getUuid())); } /** * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest) */ @Override protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); EvaluationContext ec = new EvaluationContext(); Set<String> expSupportedTypes = new HashSet<String>(); for (Object value : ec.getContextValues().values()) { expSupportedTypes.add(value.getClass().getName()); } map.put("expSupportedTypes", expSupportedTypes); return map; } public class CommandObject { private String existingRequestUuid; private ReportDefinition reportDefinition; private Mapped<CohortDefinition> baseCohort; private Map<String, Object> userEnteredParams; private String selectedRenderer; // as RendererClass!Arg private String schedule; private Map<String, String> expressions; private List<RenderingMode> renderingModes; public CommandObject() { userEnteredParams = new LinkedHashMap<String, Object>(); } @SuppressWarnings("unchecked") public RenderingMode getSelectedMode() { if (selectedRenderer != null) { try { String[] temp = selectedRenderer.split("!"); Class<? extends ReportRenderer> rc = (Class<? extends ReportRenderer>) Context.loadClass(temp[0]); String arg = (temp.length > 1 && StringUtils.hasText(temp[1])) ? temp[1] : null; for (RenderingMode mode : renderingModes) { if (mode.getRenderer().getClass().equals(rc) && OpenmrsUtil.nullSafeEquals(mode.getArgument(), arg)) { return mode; } } log.warn("Could not find requested rendering mode: " + selectedRenderer); } catch (Exception e) { log.warn("Could not load requested renderer", e); } } return null; } public String getExistingRequestUuid() { return existingRequestUuid; } public void setExistingRequestUuid(String existingRequestUuid) { this.existingRequestUuid = existingRequestUuid; } public List<RenderingMode> getRenderingModes() { return renderingModes; } public void setRenderingModes(List<RenderingMode> rendereringModes) { this.renderingModes = rendereringModes; } public ReportDefinition getReportDefinition() { return reportDefinition; } public void setReportDefinition(ReportDefinition reportDefinition) { this.reportDefinition = reportDefinition; } public Mapped<CohortDefinition> getBaseCohort() { return baseCohort; } public void setBaseCohort(Mapped<CohortDefinition> baseCohort) { this.baseCohort = baseCohort; } public String getSelectedRenderer() { return selectedRenderer; } public void setSelectedRenderer(String selectedRenderer) { this.selectedRenderer = selectedRenderer; } public Map<String, Object> getUserEnteredParams() { return userEnteredParams; } public void setUserEnteredParams(Map<String, Object> userEnteredParams) { this.userEnteredParams = userEnteredParams; } public String getSchedule() { return schedule; } public void setSchedule(String schedule) { this.schedule = schedule; } /** * @return the expressions */ public Map<String, String> getExpressions() { return expressions; } /** * @param expressions the expressions to set */ public void setExpressions(Map<String, String> expressions) { this.expressions = expressions; } } }
public void validate(Object commandObject, Errors errors) { CommandObject command = (CommandObject) commandObject; ValidationUtils.rejectIfEmpty(errors, "reportDefinition", "reporting.Report.run.error.missingReportID"); if (command.getReportDefinition() != null) { ReportDefinition reportDefinition = command.getReportDefinition(); Set<String> requiredParams = new HashSet<String>(); if (reportDefinition.getParameters() != null) { for (Parameter parameter : reportDefinition.getParameters()) { requiredParams.add(parameter.getName()); } } for (Map.Entry<String, Object> e : command.getUserEnteredParams().entrySet()) { if (e.getValue() instanceof Iterable || e.getValue() instanceof Object[]) { Object iterable = e.getValue(); if (e.getValue() instanceof Object[]) { iterable = Arrays.asList((Object[]) e.getValue()); } boolean hasNull = true; for (Object value : (Iterable<Object>) iterable) { hasNull = !ObjectUtil.notNull(value); } if (!hasNull) { requiredParams.remove(e.getKey()); } } else if (ObjectUtil.notNull(e.getValue())) { requiredParams.remove(e.getKey()); } } if (requiredParams.size() > 0) { for (Iterator<String> iterator = requiredParams.iterator(); iterator.hasNext();) { String parameterName = (String) iterator.next(); if (StringUtils.hasText(command.getExpressions().get(parameterName))) { String expression = command.getExpressions().get(parameterName); if (!EvaluationUtil.isExpression(expression)){ errors.rejectValue("expressions[" + parameterName + "]", "reporting.Report.run.error.invalidParamExpression"); } } else { errors.rejectValue("userEnteredParams[" + parameterName + "]", "error.required", new Object[] { "This parameter" }, "{0} is required"); } } } if (reportDefinition.getDataSetDefinitions() == null || reportDefinition.getDataSetDefinitions().size() == 0) { errors.reject("reporting.Report.run.error.definitionNotDeclared"); } if (ObjectUtil.notNull(command.getSchedule())) { if (!CronExpression.isValidExpression(command.getSchedule())) { errors.rejectValue("schedule", "reporting.Report.run.error.invalidCronExpression"); } } } ValidationUtils.rejectIfEmpty(errors, "selectedRenderer", "reporting.Report.run.error.noRendererSelected"); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { CommandObject command = new CommandObject(); if (Context.isAuthenticated()) { ReportDefinitionService rds = Context.getService(ReportDefinitionService.class); ReportService reportService = Context.getService(ReportService.class); if (StringUtils.hasText(request.getParameter("copyRequest"))) { ReportRequest req = reportService.getReportRequestByUuid(request.getParameter("copyRequest")); // avoid lazy init exceptions command.setReportDefinition(rds.getDefinitionByUuid(req.getReportDefinition().getParameterizable().getUuid())); for (Map.Entry<String, Object> param : req.getReportDefinition().getParameterMappings().entrySet()) { command.getUserEnteredParams().put(param.getKey(), param.getValue()); } command.setSelectedRenderer(req.getRenderingMode().getDescriptor()); } else if (StringUtils.hasText(request.getParameter("requestUuid"))) { String reqUuid = request.getParameter("requestUuid"); ReportRequest rr = reportService.getReportRequestByUuid(reqUuid); command.setExistingRequestUuid(reqUuid); command.setReportDefinition(rr.getReportDefinition().getParameterizable()); command.setUserEnteredParams(rr.getReportDefinition().getParameterMappings()); command.setBaseCohort(rr.getBaseCohort()); command.setSelectedRenderer(rr.getRenderingMode().getDescriptor()); command.setSchedule(rr.getSchedule()); } else { String uuid = request.getParameter("reportId"); ReportDefinition reportDefinition = rds.getDefinitionByUuid(uuid); command.setReportDefinition(reportDefinition); } command.setRenderingModes(reportService.getRenderingModes(command.getReportDefinition())); } return command; } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObject, BindException errors) throws Exception { CommandObject command = (CommandObject) commandObject; ReportDefinition reportDefinition = command.getReportDefinition(); ReportService rs = Context.getService(ReportService.class); // Parse the input parameters into appropriate objects and fail validation if any are invalid Map<String, Object> params = new LinkedHashMap<String, Object>(); if (reportDefinition.getParameters() != null && (command.getUserEnteredParams() != null || command.getExpressions() != null)) { for (Parameter parameter : reportDefinition.getParameters()) { Object value = null; String expression = null; if(command.getExpressions() != null && ObjectUtil.notNull(command.getExpressions().get(parameter.getName()))) expression = command.getExpressions().get(parameter.getName()); else value = command.getUserEnteredParams().get(parameter.getName()); if (ObjectUtil.notNull(value) || ObjectUtil.notNull(expression)) { try { if (StringUtils.hasText(expression)) value = expression; else value = WidgetUtil.parseInput(value, parameter.getType(), parameter.getCollectionType()); params.put(parameter.getName(), value); } catch (Exception ex) { errors.rejectValue("userEnteredParams[" + parameter.getName() + "]", ex.getMessage()); } } } } // Ensure that the chosen renderer is valid for this report RenderingMode renderingMode = command.getSelectedMode(); if (!renderingMode.getRenderer().canRender(reportDefinition)) { errors.rejectValue("selectedRenderer", "reporting.Report.run.error.invalidRenderer"); } if (errors.hasErrors()) { return showForm(request, response, errors); } ReportRequest rr = null; if (command.getExistingRequestUuid() != null) { rr = rs.getReportRequestByUuid(command.getExistingRequestUuid()); } else { rr = new ReportRequest(); } rr.setReportDefinition(new Mapped<ReportDefinition>(reportDefinition, params)); rr.setBaseCohort(command.getBaseCohort()); rr.setRenderingMode(command.getSelectedMode()); rr.setPriority(Priority.NORMAL); rr.setSchedule(command.getSchedule()); // TODO: We might want to check here if this exact same report request is already queued and just re-direct if so rr = rs.queueReport(rr); rs.processNextQueuedReports(); return new ModelAndView(new RedirectView("../reports/reportHistoryOpen.form?uuid="+rr.getUuid())); } /** * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest) */ @Override protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); EvaluationContext ec = new EvaluationContext(); Set<String> expSupportedTypes = new HashSet<String>(); for (Object value : ec.getContextValues().values()) { expSupportedTypes.add(value.getClass().getName()); } map.put("expSupportedTypes", expSupportedTypes); return map; } public class CommandObject { private String existingRequestUuid; private ReportDefinition reportDefinition; private Mapped<CohortDefinition> baseCohort; private Map<String, Object> userEnteredParams; private String selectedRenderer; // as RendererClass!Arg private String schedule; private Map<String, String> expressions; private List<RenderingMode> renderingModes; public CommandObject() { userEnteredParams = new LinkedHashMap<String, Object>(); expressions = new HashMap<String ,String>(); } @SuppressWarnings("unchecked") public RenderingMode getSelectedMode() { if (selectedRenderer != null) { try { String[] temp = selectedRenderer.split("!"); Class<? extends ReportRenderer> rc = (Class<? extends ReportRenderer>) Context.loadClass(temp[0]); String arg = (temp.length > 1 && StringUtils.hasText(temp[1])) ? temp[1] : null; for (RenderingMode mode : renderingModes) { if (mode.getRenderer().getClass().equals(rc) && OpenmrsUtil.nullSafeEquals(mode.getArgument(), arg)) { return mode; } } log.warn("Could not find requested rendering mode: " + selectedRenderer); } catch (Exception e) { log.warn("Could not load requested renderer", e); } } return null; } public String getExistingRequestUuid() { return existingRequestUuid; } public void setExistingRequestUuid(String existingRequestUuid) { this.existingRequestUuid = existingRequestUuid; } public List<RenderingMode> getRenderingModes() { return renderingModes; } public void setRenderingModes(List<RenderingMode> rendereringModes) { this.renderingModes = rendereringModes; } public ReportDefinition getReportDefinition() { return reportDefinition; } public void setReportDefinition(ReportDefinition reportDefinition) { this.reportDefinition = reportDefinition; } public Mapped<CohortDefinition> getBaseCohort() { return baseCohort; } public void setBaseCohort(Mapped<CohortDefinition> baseCohort) { this.baseCohort = baseCohort; } public String getSelectedRenderer() { return selectedRenderer; } public void setSelectedRenderer(String selectedRenderer) { this.selectedRenderer = selectedRenderer; } public Map<String, Object> getUserEnteredParams() { return userEnteredParams; } public void setUserEnteredParams(Map<String, Object> userEnteredParams) { this.userEnteredParams = userEnteredParams; } public String getSchedule() { return schedule; } public void setSchedule(String schedule) { this.schedule = schedule; } /** * @return the expressions */ public Map<String, String> getExpressions() { return expressions; } /** * @param expressions the expressions to set */ public void setExpressions(Map<String, String> expressions) { this.expressions = expressions; } } }
diff --git a/src/com/creal/trace/Control.java b/src/com/creal/trace/Control.java index 65eecd4..f9353a9 100644 --- a/src/com/creal/trace/Control.java +++ b/src/com/creal/trace/Control.java @@ -1,112 +1,113 @@ package com.creal.trace; import com.*; import java.util.Vector; import controlP5.Range; import controlP5.Textlabel; /** * Class for control objects. * * @author cmichi */ public class Control { private Main p; /** align all controls to this x */ public final int x = 40; /** current y for placing controls */ public int yOriginal = 40 + 55; public int y = yOriginal; public controlP5.Textfield b; public int i = 0; /** collections for the control elements */ public Vector<Textlabel> els_labels = new Vector<Textlabel>(); public Vector<Range> els_ranges = new Vector<Range>(); public Control(Main main) { this.p = main; b = p.controlP5.addTextfield("", x, y - 40, 150, 20); b.setAutoClear(false); p.controlP5.addButton("Trace", 0, x + 165, y - 40, 80, 19); } public void draw() { @SuppressWarnings("unchecked") Vector<TraceResult> traces_cp = (Vector<TraceResult>) p.traces.clone(); int max = traces_cp.size() - 1; if (max > 10) max = 10; for (int a = max; a >= i; a--) { TraceResult ap = traces_cp.get(a); y += 40; float val = (140 / ap.getAveragePing()) % 255; els_labels.add(p.controlP5.addTextlabel("lbl" + y, ap.hostname, x, y)); els_ranges.add(p.controlP5.addRange("" + ap.getAveragePing(), 0, 255, 0, val, x, y + 15, 200, 12)); i++; } + // if (p.tracer.started && !p.tracer.finished) { if (i == 0 && p.tracer.started) { p.fill(p.WHITE); p.text("loading " + p.tracer.hostname + getLoadingDots(), x - - p.shiftEarthX, y + 10); + - p.shiftEarthX, yOriginal + 10); } } /** * Reset all Control objects. */ public void reset() { y = yOriginal; i = 0; for (int a = 0; a < els_labels.size(); a++) { els_labels.get(a).remove(); els_ranges.get(a).remove(); } els_labels = new Vector<Textlabel>(); els_ranges = new Vector<Range>(); } /** * What we do here is to make the "loading..." label dynamic by adding dots * over time */ private int dots = 0; private int ellapsedFrames = 0; private int newDotEveryFrames = 30; private String getLoadingDots() { String s = ""; if (ellapsedFrames >= newDotEveryFrames) { dots = ++dots % 4; ellapsedFrames = 0; } for (int i = 0; i <= dots; i++) s += ". "; ellapsedFrames++; return s; } }
false
true
public void draw() { @SuppressWarnings("unchecked") Vector<TraceResult> traces_cp = (Vector<TraceResult>) p.traces.clone(); int max = traces_cp.size() - 1; if (max > 10) max = 10; for (int a = max; a >= i; a--) { TraceResult ap = traces_cp.get(a); y += 40; float val = (140 / ap.getAveragePing()) % 255; els_labels.add(p.controlP5.addTextlabel("lbl" + y, ap.hostname, x, y)); els_ranges.add(p.controlP5.addRange("" + ap.getAveragePing(), 0, 255, 0, val, x, y + 15, 200, 12)); i++; } if (i == 0 && p.tracer.started) { p.fill(p.WHITE); p.text("loading " + p.tracer.hostname + getLoadingDots(), x - p.shiftEarthX, y + 10); } }
public void draw() { @SuppressWarnings("unchecked") Vector<TraceResult> traces_cp = (Vector<TraceResult>) p.traces.clone(); int max = traces_cp.size() - 1; if (max > 10) max = 10; for (int a = max; a >= i; a--) { TraceResult ap = traces_cp.get(a); y += 40; float val = (140 / ap.getAveragePing()) % 255; els_labels.add(p.controlP5.addTextlabel("lbl" + y, ap.hostname, x, y)); els_ranges.add(p.controlP5.addRange("" + ap.getAveragePing(), 0, 255, 0, val, x, y + 15, 200, 12)); i++; } // if (p.tracer.started && !p.tracer.finished) { if (i == 0 && p.tracer.started) { p.fill(p.WHITE); p.text("loading " + p.tracer.hostname + getLoadingDots(), x - p.shiftEarthX, yOriginal + 10); } }
diff --git a/co/uk/silvania/cities/core/CommonProxy.java b/co/uk/silvania/cities/core/CommonProxy.java index 25eda2c..3d2aaa6 100644 --- a/co/uk/silvania/cities/core/CommonProxy.java +++ b/co/uk/silvania/cities/core/CommonProxy.java @@ -1,563 +1,563 @@ package co.uk.silvania.cities.core; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import co.uk.silvania.cities.core.blocks.*; import co.uk.silvania.cities.core.items.*; import co.uk.silvania.cities.core.npc.EntityBanker; import co.uk.silvania.cities.econ.VillagerTradeHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import cpw.mods.fml.common.registry.VillagerRegistry; public class CommonProxy { @Instance public static FlenixCities_Core instance; public void registerRenderThings() {} public void registerRenderers() {} public boolean banCheck() { return false; } public void entityStuff() { EntityRegistry.registerModEntity(EntityBanker.class, "Banker", 1, FlenixCities_Core.instance, 32, 5, true); } public void registerBlocks() { GameRegistry.registerBlock(CoreBlocks.atmBlock, ItemATMBlock.class, "FlenixCities" + (CoreBlocks.atmBlock.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.floatingShelvesBlock, "floatingShelvesBlock"); GameRegistry.registerBlock(CoreBlocks.npcSpawnerBlock, "npcSpawnerBlock"); GameRegistry.registerBlock(CoreBlocks.skyscraperBlocks, ItemSkyscraperBlocks.class, "FlenixCities" + (CoreBlocks.skyscraperBlocks.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.stainedGlass, ItemStainedGlass.class, "FlenixCities" + (CoreBlocks.stainedGlass.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.stainedGlassLit, ItemStainedGlassLit.class, "FlenixCities" + (CoreBlocks.stainedGlassLit.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.styledGlass, ItemStyledGlass.class, "FlenixCities" + (CoreBlocks.styledGlass.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.styledGlassWhite, ItemStyledGlassLit.class, "FlenixCities" + (CoreBlocks.styledGlassWhite.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.woolCeilingTile, ItemWoolCeilingTile.class, "FlenixCities" + (CoreBlocks.woolCeilingTile.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.woolStone, ItemWoolStone.class, "FlenixCities" + (CoreBlocks.woolStone.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.woolWood, ItemWoolStone.class, "FlenixCities" + (CoreBlocks.woolWood.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.plasticBlock, ItemPlasticBlocks.class, "FlenixCities" + (CoreBlocks.plasticBlock.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.floorBlocks, ItemFloorBlocks.class, "FlenixCities" + (CoreBlocks.floorBlocks.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.oreStorageBlock, ItemOreStorageBlocks.class, "FlenixCities" + (CoreBlocks.oreStorageBlock.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.copperOre, "copperOre"); GameRegistry.registerBlock(CoreBlocks.tinOre, "tinOre"); GameRegistry.registerBlock(CoreBlocks.crystalOre, "crystalOre"); GameRegistry.registerBlock(CoreBlocks.rubyOre, "rubyOre"); GameRegistry.registerBlock(CoreBlocks.silverOre, "silverOre"); GameRegistry.registerBlock(CoreBlocks.tecmoniumOre, "tecmoniumOre"); GameRegistry.registerBlock(CoreBlocks.titaniumOre, "titaniumOre"); GameRegistry.registerBlock(CoreBlocks.rebarBlock, "rebarBlock"); GameRegistry.registerBlock(CoreBlocks.lightingBlocks, ItemLightingBlock.class, "FlenixCities" + (CoreBlocks.lightingBlocks.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.lightingRotateBlocks, ItemLightingBlock.class, "FlenixCities" + (CoreBlocks.lightingRotateBlocks.getUnlocalizedName().substring(5))); GameRegistry.registerBlock(CoreBlocks.drywallWhite, "drywallWhite"); GameRegistry.registerBlock(CoreBlocks.drywallRed, "drywallRed"); GameRegistry.registerBlock(CoreBlocks.drywallBlue, "drywallBlue"); GameRegistry.registerBlock(CoreBlocks.drywallGreen, "drywallGreen"); GameRegistry.registerBlock(CoreBlocks.drywallGrey, "drywallGrey"); //GameRegistry.registerBlock(FlenixCities.verticalPoster1, ItemBlockPosterVertical.class, "FlenixCities" + (FlenixCities.verticalPoster1.getUnlocalizedName().substring(5))); //GameRegistry.registerBlock(FlenixCities.verticalPoster2, ItemBlockPosterVertical.class, "FlenixCities" + (FlenixCities.verticalPoster2.getUnlocalizedName().substring(5))); //GameRegistry.registerBlock(FlenixCities.verticalPoster3, ItemBlockPosterVertical.class, "FlenixCities" + (FlenixCities.verticalPoster3.getUnlocalizedName().substring(5))); //GameRegistry.registerBlock(FlenixCities.verticalPoster4, ItemBlockPosterVertical.class, "FlenixCities" + (FlenixCities.verticalPoster4.getUnlocalizedName().substring(5))); //GameRegistry.registerItem(CoreItems.plasticItem, "plasticItem"); //GameRegistry.registerItem(CoreItems.smallPCB, "smallPCB"); //GameRegistry.registerItem(CoreItems.largePCB, "largePCB"); GameRegistry.registerItem(CoreItems.rubyItem, "rubyItem"); GameRegistry.registerItem(CoreItems.titaniumIngot, "titaniumIngot"); GameRegistry.registerItem(CoreItems.tecmoniumIngot, "tecmoniumIngot"); GameRegistry.registerItem(CoreItems.silverIngot, "silverIngot"); GameRegistry.registerItem(CoreItems.copperIngot, "copperIngot"); GameRegistry.registerItem(CoreItems.tinIngot, "tinIngot"); GameRegistry.registerItem(CoreItems.crystalItem, "crystalItem"); GameRegistry.registerItem(CoreItems.sapphireItem, "sapphireItem"); GameRegistry.registerItem(CoreItems.coin1, "coin1"); GameRegistry.registerItem(CoreItems.coin2, "coin2"); GameRegistry.registerItem(CoreItems.coin5, "coin5"); GameRegistry.registerItem(CoreItems.coin10, "coin10"); GameRegistry.registerItem(CoreItems.coin25, "coin25"); GameRegistry.registerItem(CoreItems.coin50, "coin50"); GameRegistry.registerItem(CoreItems.coin100, "coin100"); GameRegistry.registerItem(CoreItems.note100, "note100"); GameRegistry.registerItem(CoreItems.note500, "note500"); GameRegistry.registerItem(CoreItems.note1000, "note1000"); GameRegistry.registerItem(CoreItems.note2000, "note2000"); GameRegistry.registerItem(CoreItems.note5000, "note5000"); GameRegistry.registerItem(CoreItems.note10000, "note10000"); GameRegistry.registerItem(CoreItems.debitCard, "debitCard"); GameRegistry.registerItem(CoreItems.debitCardNew, "debitCardNew"); GameRegistry.registerItem(CoreItems.bankerSpawner, "bankerSpawner"); /*GameRegistry.registerItem(CoreItems.ringItem, "ringItem"); GameRegistry.registerItem(CoreItems.diamondRing, "diamondRing"); GameRegistry.registerItem(CoreItems.necklaceItem, "necklaceItem"); GameRegistry.registerItem(CoreItems.rubyNecklace, "rubyNecklace");*/ } public void addNames() { LanguageRegistry.addName(CoreBlocks.copperOre, "Copper Ore"); LanguageRegistry.addName(CoreBlocks.tinOre, "Tin Ore"); LanguageRegistry.addName(CoreBlocks.rubyOre, "Ruby Ore"); LanguageRegistry.addName(CoreBlocks.tecmoniumOre, "Tecmonium Ore"); LanguageRegistry.addName(CoreBlocks.crystalOre, "Crystal Ore"); LanguageRegistry.addName(CoreBlocks.titaniumOre, "Titanium Ore"); LanguageRegistry.addName(CoreBlocks.silverOre, "Silver Ore"); LanguageRegistry.addName(CoreBlocks.rebarBlock, "Rebar"); LanguageRegistry.addName(CoreBlocks.drywallWhite, "White Drywall"); LanguageRegistry.addName(CoreBlocks.drywallRed, "Red Drywall"); LanguageRegistry.addName(CoreBlocks.drywallBlue, "Blue Drywall"); LanguageRegistry.addName(CoreBlocks.drywallGreen, "Green Drywall"); LanguageRegistry.addName(CoreBlocks.drywallGrey, "Grey Drywall"); LanguageRegistry.addName(CoreBlocks.floatingShelvesBlock, "Floating Shelves"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 0), "ATM Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 4), "ATM Stone Brick"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 8), "ATM City White"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 12), "ATM City Grey"); LanguageRegistry.addName(CoreItems.rubyItem, "Ruby"); LanguageRegistry.addName(CoreItems.titaniumIngot, "Titanium Ingot"); LanguageRegistry.addName(CoreItems.tecmoniumIngot, "Tecmonium Ore"); LanguageRegistry.addName(CoreItems.silverIngot, "Silver Ingot"); LanguageRegistry.addName(CoreItems.copperIngot, "Copper Ingot"); LanguageRegistry.addName(CoreItems.tinIngot, "Tin Ingot"); LanguageRegistry.addName(CoreItems.crystalItem, "Crystal"); LanguageRegistry.addName(CoreItems.sapphireItem, "Sapphire"); /*LanguageRegistry.addName(CoreItems.plasticItem, "Plastic"); LanguageRegistry.addName(CoreItems.smallPCB, "Small PCB"); LanguageRegistry.addName(CoreItems.largePCB, "Large PCB"); LanguageRegistry.addName(CoreItems.ringItem, "Ring"); LanguageRegistry.addName(CoreItems.diamondRing, "Diamond Ring"); LanguageRegistry.addName(CoreItems.necklaceItem, "Necklace"); LanguageRegistry.addName(CoreItems.rubyNecklace, "Ruby Necklace");*/ LanguageRegistry.addName(CoreItems.coin1, "1 " + CityConfig.currencySmall); LanguageRegistry.addName(CoreItems.coin2, "2 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin5, "5 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin10, "10 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin25, "25 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin50, "50 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin100, "1 " + CityConfig.currencyLarge + " Coin"); LanguageRegistry.addName(CoreItems.note100, "1 " + CityConfig.currencyLarge); LanguageRegistry.addName(CoreItems.note200, "2 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note500, "5 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note1000, "10 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note2000, "20 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note5000, "50 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note10000, "100 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.debitCard, "Debit Card (Broken)"); LanguageRegistry.addName(CoreItems.debitCardNew, "Debit Card"); LanguageRegistry.addName(CoreItems.bankerSpawner, "Banker Spawner"); LanguageRegistry.addName(CoreItems.idCard, "ID Card"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 0), "White Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 1), "Light Grey Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 2), "Dark Grey Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 3), "Black Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 4), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 5), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 6), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 7), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 8), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 9), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 10), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 11), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 12), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 13), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 14), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 15), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 0), "White Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 1), "Orange Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 2), "Magenta Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 3), "Light Blue Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 4), "Yellow Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 5), "Lime Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 6), "Pink Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 7), "Grey Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 8), "Light Grey Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 9), "Cyan Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 10), "Purple Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 11), "Blue Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 12), "Brown Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 13), "Green Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 14), "Red Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 15), "Black Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 0), "White Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 1), "Orange Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 2), "Magenta Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 3), "Light Blue Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 4), "Yellow Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 5), "Lime Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 6), "Pink Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 7), "Grey Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 8), "Light Grey Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 9), "Cyan Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 10), "Purple Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 11), "Blue Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 12), "Brown Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 13), "Green Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 14), "Red Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 15), "Black Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 0), "Blue White-framed Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 1), "Blue Horizontal Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 2), "Blue Vertical Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 3), "Blue Framed Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 4), "Blue Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 5), "Blue Framed Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 6), "Blue Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 7), "Blue Framed Vertical Line"); - LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 8), "blue Vertical Line"); + LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 8), "Blue Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 9), "Blue Small Squares"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 10), "Blue Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 11), "Blue Supercross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 12), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 13), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 14), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 15), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 0), "Clear White-framed Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 1), "Clear Horizontal Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 2), "Clear Vertical Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 3), "Clear Framed Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 4), "Clear Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 5), "Clear Framed Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 6), "Clear Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 7), "Clear Framed Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 8), "Clear Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 9), "Clear Small Squares"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 10), "Clear Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 11), "Clear Supercross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 12), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 13), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 14), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 15), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 0), "White Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 1), "Orange Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 2), "Magenta Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 3), "Light Blue Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 4), "Yellow Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 5), "Lime Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 6), "Pink Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 7), "Grey Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 8), "Light Grey Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 9), "Cyan Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 10), "Purple Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 11), "Blue Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 12), "Brown Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 13), "Green Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 14), "Red Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 15), "Black Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 0), "White Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 1), "Orange Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 2), "Magenta Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 3), "Light Blue Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 4), "Yellow Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 5), "Lime Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 6), "Pink Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 7), "Grey Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 8), "Light Grey Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 9), "Cyan Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 10), "Purple Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 11), "Blue Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 12), "Brown Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 13), "Green Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 14), "Red Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 15), "Black Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 0), "White Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 1), "Orange Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 2), "Magenta Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 3), "Light Blue Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 4), "Yellow Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 5), "Lime Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 6), "Pink Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 7), "Grey Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 8), "Light Grey Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 9), "Cyan Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 10), "Purple Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 11), "Blue Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 12), "Brown Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 13), "Green Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 14), "Red Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 15), "Black Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 0), "White Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 1), "Orange Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 2), "Magenta Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 3), "Light Blue Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 4), "Yellow Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 5), "Lime Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 6), "Pink Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 7), "Grey Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 8), "Light Grey Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 9), "Cyan Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 10), "Purple Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 11), "Blue Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 12), "Brown Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 13), "Green Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 14), "Red Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 15), "Black Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 0), "Bathroom Tiles"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 1), "Kitchen Tiles"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 2), "Generic Tiles 1"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 3), "Generic Tiles 2"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 4), "Oak Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 5), "Spruce Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 6), "Birch Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 7), "Jungle Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 8), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 9), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 10), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 11), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 12), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 13), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 14), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 15), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingBlocks, 1, 1), "Light Panel"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingBlocks, 1, 2), "Ceiling Light"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 0), "Vertical Light Strip"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 4), "Vertical Light Strip (Short)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 8), "Vertical Light Panel"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 12), "Vertical Light Panel (Small)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 0), "Copper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 1), "Tin Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 2), "Ruby Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 3), "Sapphire Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 4), "Tecmonium Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 5), "Crystal Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 6), "Silver Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 7), "Titanium Block"); /*LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 0), "Silvania VA"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 4), "Remula"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 8), "9"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 12), "13"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 0), "17"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 4), "21"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 8), "25"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 12), "29"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 0), "DoanVPS Poster"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 4), "Ad Slot 2"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 8), "Ad Slot 3"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 12), "Ad Slot 4"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 0), "Ad Slot 5"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 4), "Ad Slot 6"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 8), "Ad Slot 7"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 12), "Ad Slot 8");*/ } public void setVillagerTrades() { VillagerRegistry.instance().registerVillageTradeHandler(3, new VillagerTradeHandler()); } public void addRecipes() { ItemStack copperIngot = new ItemStack(CoreItems.copperIngot); ItemStack tinIngot = new ItemStack(CoreItems.tinIngot); ItemStack silverIngot = new ItemStack(CoreItems.silverIngot); ItemStack titaniumIngot = new ItemStack(CoreItems.titaniumIngot); ItemStack tecmoniumIngot = new ItemStack(CoreItems.tecmoniumIngot); ItemStack crystalItem = new ItemStack(CoreItems.crystalItem); ItemStack rubyItem = new ItemStack(CoreItems.rubyItem); ItemStack sapphireItem = new ItemStack(CoreItems.sapphireItem); ItemStack copperOre = new ItemStack(CoreBlocks.copperOre); ItemStack tinOre = new ItemStack(CoreBlocks.tinOre); ItemStack silverOre = new ItemStack(CoreBlocks.silverOre); ItemStack titaniumOre = new ItemStack(CoreBlocks.titaniumOre); ItemStack tecmoniumOre = new ItemStack(CoreBlocks.tecmoniumOre); ItemStack crystalOre = new ItemStack(CoreBlocks.crystalOre); ItemStack rubyOre = new ItemStack(CoreBlocks.rubyOre); ItemStack sapphireOre = new ItemStack(CoreBlocks.sapphireOre); ItemStack copperBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 0); ItemStack tinBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 1); ItemStack rubyBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 2); ItemStack sapphireBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 3); ItemStack tecmoniumBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 4); ItemStack crystalBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 5); ItemStack silverBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 6); ItemStack titaniumBlock = new ItemStack(CoreBlocks.oreStorageBlock, 1, 7); ItemStack stoneBlock = new ItemStack(Block.stone); ItemStack quartzItem = new ItemStack(Item.netherQuartz); ItemStack skyscraperAny = new ItemStack(CoreBlocks.skyscraperBlocks); ItemStack skyscraperWhite = new ItemStack(CoreBlocks.skyscraperBlocks, 1, 0); ItemStack skyscraperLightGrey = new ItemStack(CoreBlocks.skyscraperBlocks, 1, 1); ItemStack skyscraperDarkGrey = new ItemStack(CoreBlocks.skyscraperBlocks, 1, 2); ItemStack skyscraperBlack = new ItemStack(CoreBlocks.skyscraperBlocks, 1, 3); ItemStack rebarBlock = new ItemStack(CoreBlocks.rebarBlock); ItemStack blackDye = new ItemStack(Item.dyePowder, 1, 0); ItemStack redDye = new ItemStack(Item.dyePowder, 1, 1); ItemStack greenDye = new ItemStack(Item.dyePowder, 1, 2); ItemStack brownDye = new ItemStack(Item.dyePowder, 1, 3); ItemStack blueDye = new ItemStack(Item.dyePowder, 1, 4); ItemStack purpleDye = new ItemStack(Item.dyePowder, 1, 5); ItemStack tealDye = new ItemStack(Item.dyePowder, 1, 6); ItemStack lightGreyDye = new ItemStack(Item.dyePowder, 1, 7); ItemStack darkGreyDye = new ItemStack(Item.dyePowder, 1, 8); ItemStack pinkDye = new ItemStack(Item.dyePowder, 1, 9); ItemStack limeGreenDye = new ItemStack(Item.dyePowder, 1, 10); ItemStack yellowDye = new ItemStack(Item.dyePowder, 1, 11); ItemStack lightBlueDye = new ItemStack(Item.dyePowder, 1, 12); ItemStack magentaDye = new ItemStack(Item.dyePowder, 1, 13); ItemStack orangeDye = new ItemStack(Item.dyePowder, 1, 14); ItemStack whiteDye = new ItemStack(Item.dyePowder, 1, 15); ItemStack blackWool = new ItemStack(Block.cloth, 1, 15); ItemStack redWool = new ItemStack(Block.cloth, 1, 14); ItemStack greenWool = new ItemStack(Block.cloth, 1, 13); ItemStack brownWool = new ItemStack(Block.cloth, 1, 12); ItemStack blueWool = new ItemStack(Block.cloth, 1, 11); ItemStack purpleWool = new ItemStack(Block.cloth, 1, 10); ItemStack tealWool = new ItemStack(Block.cloth, 1, 9); ItemStack lightGreyWool = new ItemStack(Block.cloth, 1, 8); ItemStack darkGreyWool = new ItemStack(Block.cloth, 1, 7); ItemStack pinkWool = new ItemStack(Block.cloth, 1, 6); ItemStack limeGreenWool = new ItemStack(Block.cloth, 1, 5); ItemStack yellowWool = new ItemStack(Block.cloth, 1, 4); ItemStack lightBlueWool = new ItemStack(Block.cloth, 1, 3); ItemStack magentaWool = new ItemStack(Block.cloth, 1, 2); ItemStack orangeWool = new ItemStack(Block.cloth, 1, 1); ItemStack whiteWool = new ItemStack(Block.cloth, 1, 0); ItemStack ceilingTile = new ItemStack(CoreBlocks.floorBlocks, 1, 9); ItemStack woodBlock = new ItemStack(Block.planks); GameRegistry.addRecipe(copperBlock, "iii", "iii", "iii", 'i', copperIngot); GameRegistry.addRecipe(tinBlock, "iii", "iii", "iii", 'i', tinIngot); GameRegistry.addRecipe(rubyBlock, "iii", "iii", "iii", 'i', rubyItem); GameRegistry.addRecipe(sapphireBlock, "iii", "iii", "iii", 'i', sapphireItem); GameRegistry.addRecipe(tecmoniumBlock, "iii", "iii", "iii", 'i', tecmoniumIngot); GameRegistry.addRecipe(crystalBlock, "iii", "iii", "iii", 'i', crystalItem); GameRegistry.addRecipe(silverBlock, "iii", "iii", "iii", 'i', silverIngot); GameRegistry.addRecipe(titaniumBlock, "iii", "iii", "iii", 'i', titaniumIngot); GameRegistry.addRecipe(new ItemStack(CoreBlocks.rebarBlock, 9, 0), " t ", " t ", " t ", 't', titaniumIngot); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.floorBlocks, 1, 9), stoneBlock, quartzItem); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 4), " s ", "dsd", " s ", 's', skyscraperWhite, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 5), " s ", "dsd", " s ", 's', skyscraperLightGrey, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 6), " s ", "dsd", " s ", 's', skyscraperDarkGrey, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 7), " s ", "dsd", " s ", 's', skyscraperBlack, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 8), " d ", "sss", " d ", 's', skyscraperWhite, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 9), " d ", "sss", " d ", 's', skyscraperLightGrey, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 10), " d ", "sss", " d ", 's', skyscraperDarkGrey, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 3, 11), " d ", "sss", " d ", 's', skyscraperBlack, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 12), " d ", "dsd", " d ", 's', skyscraperWhite, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 13), " d ", "dsd", " d ", 's', skyscraperLightGrey, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 14), " d ", "dsd", " d ", 's', skyscraperDarkGrey, 'd', blackDye); GameRegistry.addRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 15), " d ", "dsd", " d ", 's', skyscraperBlack, 'd', blackDye); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.copperIngot, 9, 0), copperBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.tinIngot, 9, 0), tinBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.rubyItem, 9, 0), rubyBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.sapphireItem, 9, 0), sapphireBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.tecmoniumIngot, 9, 0), tecmoniumBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.crystalItem, 9, 0), crystalBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.silverIngot, 9, 0), silverBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreItems.titaniumIngot, 9, 0), titaniumBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.copperOre), copperOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.tinOre), tinOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.silverOre), silverOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.titaniumOre), titaniumOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.tecmoniumOre), tecmoniumOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.crystalOre), crystalOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.rubyOre), rubyOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.sapphireOre), sapphireOre); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 2, 0), stoneBlock, rebarBlock); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 0), skyscraperAny, whiteDye); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 1), skyscraperAny, lightGreyDye); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 2), skyscraperAny, darkGreyDye); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 3), skyscraperAny, blackDye); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 0), ceilingTile, whiteWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 1), ceilingTile, orangeWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 2), ceilingTile, magentaWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 3), ceilingTile, lightBlueWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 4), ceilingTile, yellowWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 5), ceilingTile, limeGreenWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 6), ceilingTile, pinkWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 7), ceilingTile, darkGreyWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 8), ceilingTile, lightGreyWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 9), ceilingTile, tealWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 10), ceilingTile, purpleWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 11), ceilingTile, blueWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 12), ceilingTile, brownWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 13), ceilingTile, greenWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 14), ceilingTile, redWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolCeilingTile, 1, 15), ceilingTile, blackWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 0), stoneBlock, whiteWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 1), stoneBlock, orangeWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 2), stoneBlock, magentaWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 3), stoneBlock, lightBlueWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 4), stoneBlock, yellowWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 5), stoneBlock, limeGreenWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 6), stoneBlock, pinkWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 7), stoneBlock, darkGreyWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 8), stoneBlock, lightGreyWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 9), stoneBlock, tealWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 10), stoneBlock, purpleWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 11), stoneBlock, blueWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 12), stoneBlock, brownWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 13), stoneBlock, greenWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 14), stoneBlock, redWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolStone, 1, 15), stoneBlock, blackWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 0), woodBlock, whiteWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 1), woodBlock, orangeWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 2), woodBlock, magentaWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 3), woodBlock, lightBlueWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 4), woodBlock, yellowWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 5), woodBlock, limeGreenWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 6), woodBlock, pinkWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 7), woodBlock, darkGreyWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 8), woodBlock, lightGreyWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 9), woodBlock, tealWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 10), woodBlock, purpleWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 11), woodBlock, blueWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 12), woodBlock, brownWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 13), woodBlock, greenWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 14), woodBlock, redWool); GameRegistry.addShapelessRecipe(new ItemStack(CoreBlocks.woolWood, 1, 15), woodBlock, blackWool); GameRegistry.addSmelting(CoreBlocks.copperOre.blockID, copperIngot, 0.5F); GameRegistry.addSmelting(CoreBlocks.tinOre.blockID, tinIngot, 0.5F); GameRegistry.addSmelting(CoreBlocks.silverOre.blockID, silverIngot, 0.8F); GameRegistry.addSmelting(CoreBlocks.titaniumOre.blockID, titaniumIngot, 1.0F); GameRegistry.addSmelting(CoreBlocks.tecmoniumOre.blockID, tecmoniumIngot, 1.2F); } }
true
true
public void addNames() { LanguageRegistry.addName(CoreBlocks.copperOre, "Copper Ore"); LanguageRegistry.addName(CoreBlocks.tinOre, "Tin Ore"); LanguageRegistry.addName(CoreBlocks.rubyOre, "Ruby Ore"); LanguageRegistry.addName(CoreBlocks.tecmoniumOre, "Tecmonium Ore"); LanguageRegistry.addName(CoreBlocks.crystalOre, "Crystal Ore"); LanguageRegistry.addName(CoreBlocks.titaniumOre, "Titanium Ore"); LanguageRegistry.addName(CoreBlocks.silverOre, "Silver Ore"); LanguageRegistry.addName(CoreBlocks.rebarBlock, "Rebar"); LanguageRegistry.addName(CoreBlocks.drywallWhite, "White Drywall"); LanguageRegistry.addName(CoreBlocks.drywallRed, "Red Drywall"); LanguageRegistry.addName(CoreBlocks.drywallBlue, "Blue Drywall"); LanguageRegistry.addName(CoreBlocks.drywallGreen, "Green Drywall"); LanguageRegistry.addName(CoreBlocks.drywallGrey, "Grey Drywall"); LanguageRegistry.addName(CoreBlocks.floatingShelvesBlock, "Floating Shelves"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 0), "ATM Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 4), "ATM Stone Brick"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 8), "ATM City White"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 12), "ATM City Grey"); LanguageRegistry.addName(CoreItems.rubyItem, "Ruby"); LanguageRegistry.addName(CoreItems.titaniumIngot, "Titanium Ingot"); LanguageRegistry.addName(CoreItems.tecmoniumIngot, "Tecmonium Ore"); LanguageRegistry.addName(CoreItems.silverIngot, "Silver Ingot"); LanguageRegistry.addName(CoreItems.copperIngot, "Copper Ingot"); LanguageRegistry.addName(CoreItems.tinIngot, "Tin Ingot"); LanguageRegistry.addName(CoreItems.crystalItem, "Crystal"); LanguageRegistry.addName(CoreItems.sapphireItem, "Sapphire"); /*LanguageRegistry.addName(CoreItems.plasticItem, "Plastic"); LanguageRegistry.addName(CoreItems.smallPCB, "Small PCB"); LanguageRegistry.addName(CoreItems.largePCB, "Large PCB"); LanguageRegistry.addName(CoreItems.ringItem, "Ring"); LanguageRegistry.addName(CoreItems.diamondRing, "Diamond Ring"); LanguageRegistry.addName(CoreItems.necklaceItem, "Necklace"); LanguageRegistry.addName(CoreItems.rubyNecklace, "Ruby Necklace");*/ LanguageRegistry.addName(CoreItems.coin1, "1 " + CityConfig.currencySmall); LanguageRegistry.addName(CoreItems.coin2, "2 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin5, "5 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin10, "10 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin25, "25 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin50, "50 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin100, "1 " + CityConfig.currencyLarge + " Coin"); LanguageRegistry.addName(CoreItems.note100, "1 " + CityConfig.currencyLarge); LanguageRegistry.addName(CoreItems.note200, "2 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note500, "5 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note1000, "10 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note2000, "20 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note5000, "50 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note10000, "100 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.debitCard, "Debit Card (Broken)"); LanguageRegistry.addName(CoreItems.debitCardNew, "Debit Card"); LanguageRegistry.addName(CoreItems.bankerSpawner, "Banker Spawner"); LanguageRegistry.addName(CoreItems.idCard, "ID Card"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 0), "White Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 1), "Light Grey Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 2), "Dark Grey Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 3), "Black Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 4), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 5), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 6), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 7), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 8), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 9), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 10), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 11), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 12), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 13), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 14), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 15), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 0), "White Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 1), "Orange Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 2), "Magenta Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 3), "Light Blue Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 4), "Yellow Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 5), "Lime Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 6), "Pink Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 7), "Grey Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 8), "Light Grey Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 9), "Cyan Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 10), "Purple Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 11), "Blue Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 12), "Brown Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 13), "Green Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 14), "Red Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 15), "Black Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 0), "White Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 1), "Orange Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 2), "Magenta Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 3), "Light Blue Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 4), "Yellow Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 5), "Lime Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 6), "Pink Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 7), "Grey Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 8), "Light Grey Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 9), "Cyan Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 10), "Purple Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 11), "Blue Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 12), "Brown Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 13), "Green Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 14), "Red Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 15), "Black Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 0), "Blue White-framed Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 1), "Blue Horizontal Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 2), "Blue Vertical Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 3), "Blue Framed Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 4), "Blue Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 5), "Blue Framed Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 6), "Blue Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 7), "Blue Framed Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 8), "blue Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 9), "Blue Small Squares"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 10), "Blue Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 11), "Blue Supercross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 12), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 13), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 14), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 15), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 0), "Clear White-framed Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 1), "Clear Horizontal Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 2), "Clear Vertical Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 3), "Clear Framed Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 4), "Clear Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 5), "Clear Framed Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 6), "Clear Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 7), "Clear Framed Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 8), "Clear Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 9), "Clear Small Squares"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 10), "Clear Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 11), "Clear Supercross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 12), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 13), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 14), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 15), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 0), "White Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 1), "Orange Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 2), "Magenta Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 3), "Light Blue Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 4), "Yellow Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 5), "Lime Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 6), "Pink Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 7), "Grey Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 8), "Light Grey Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 9), "Cyan Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 10), "Purple Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 11), "Blue Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 12), "Brown Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 13), "Green Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 14), "Red Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 15), "Black Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 0), "White Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 1), "Orange Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 2), "Magenta Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 3), "Light Blue Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 4), "Yellow Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 5), "Lime Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 6), "Pink Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 7), "Grey Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 8), "Light Grey Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 9), "Cyan Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 10), "Purple Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 11), "Blue Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 12), "Brown Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 13), "Green Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 14), "Red Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 15), "Black Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 0), "White Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 1), "Orange Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 2), "Magenta Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 3), "Light Blue Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 4), "Yellow Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 5), "Lime Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 6), "Pink Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 7), "Grey Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 8), "Light Grey Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 9), "Cyan Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 10), "Purple Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 11), "Blue Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 12), "Brown Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 13), "Green Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 14), "Red Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 15), "Black Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 0), "White Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 1), "Orange Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 2), "Magenta Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 3), "Light Blue Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 4), "Yellow Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 5), "Lime Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 6), "Pink Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 7), "Grey Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 8), "Light Grey Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 9), "Cyan Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 10), "Purple Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 11), "Blue Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 12), "Brown Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 13), "Green Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 14), "Red Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 15), "Black Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 0), "Bathroom Tiles"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 1), "Kitchen Tiles"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 2), "Generic Tiles 1"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 3), "Generic Tiles 2"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 4), "Oak Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 5), "Spruce Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 6), "Birch Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 7), "Jungle Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 8), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 9), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 10), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 11), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 12), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 13), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 14), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 15), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingBlocks, 1, 1), "Light Panel"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingBlocks, 1, 2), "Ceiling Light"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 0), "Vertical Light Strip"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 4), "Vertical Light Strip (Short)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 8), "Vertical Light Panel"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 12), "Vertical Light Panel (Small)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 0), "Copper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 1), "Tin Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 2), "Ruby Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 3), "Sapphire Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 4), "Tecmonium Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 5), "Crystal Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 6), "Silver Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 7), "Titanium Block"); /*LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 0), "Silvania VA"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 4), "Remula"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 8), "9"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 12), "13"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 0), "17"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 4), "21"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 8), "25"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 12), "29"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 0), "DoanVPS Poster"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 4), "Ad Slot 2"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 8), "Ad Slot 3"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 12), "Ad Slot 4"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 0), "Ad Slot 5"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 4), "Ad Slot 6"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 8), "Ad Slot 7"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 12), "Ad Slot 8");*/ }
public void addNames() { LanguageRegistry.addName(CoreBlocks.copperOre, "Copper Ore"); LanguageRegistry.addName(CoreBlocks.tinOre, "Tin Ore"); LanguageRegistry.addName(CoreBlocks.rubyOre, "Ruby Ore"); LanguageRegistry.addName(CoreBlocks.tecmoniumOre, "Tecmonium Ore"); LanguageRegistry.addName(CoreBlocks.crystalOre, "Crystal Ore"); LanguageRegistry.addName(CoreBlocks.titaniumOre, "Titanium Ore"); LanguageRegistry.addName(CoreBlocks.silverOre, "Silver Ore"); LanguageRegistry.addName(CoreBlocks.rebarBlock, "Rebar"); LanguageRegistry.addName(CoreBlocks.drywallWhite, "White Drywall"); LanguageRegistry.addName(CoreBlocks.drywallRed, "Red Drywall"); LanguageRegistry.addName(CoreBlocks.drywallBlue, "Blue Drywall"); LanguageRegistry.addName(CoreBlocks.drywallGreen, "Green Drywall"); LanguageRegistry.addName(CoreBlocks.drywallGrey, "Grey Drywall"); LanguageRegistry.addName(CoreBlocks.floatingShelvesBlock, "Floating Shelves"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 0), "ATM Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 4), "ATM Stone Brick"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 8), "ATM City White"); LanguageRegistry.addName(new ItemStack(CoreBlocks.atmBlock, 1, 12), "ATM City Grey"); LanguageRegistry.addName(CoreItems.rubyItem, "Ruby"); LanguageRegistry.addName(CoreItems.titaniumIngot, "Titanium Ingot"); LanguageRegistry.addName(CoreItems.tecmoniumIngot, "Tecmonium Ore"); LanguageRegistry.addName(CoreItems.silverIngot, "Silver Ingot"); LanguageRegistry.addName(CoreItems.copperIngot, "Copper Ingot"); LanguageRegistry.addName(CoreItems.tinIngot, "Tin Ingot"); LanguageRegistry.addName(CoreItems.crystalItem, "Crystal"); LanguageRegistry.addName(CoreItems.sapphireItem, "Sapphire"); /*LanguageRegistry.addName(CoreItems.plasticItem, "Plastic"); LanguageRegistry.addName(CoreItems.smallPCB, "Small PCB"); LanguageRegistry.addName(CoreItems.largePCB, "Large PCB"); LanguageRegistry.addName(CoreItems.ringItem, "Ring"); LanguageRegistry.addName(CoreItems.diamondRing, "Diamond Ring"); LanguageRegistry.addName(CoreItems.necklaceItem, "Necklace"); LanguageRegistry.addName(CoreItems.rubyNecklace, "Ruby Necklace");*/ LanguageRegistry.addName(CoreItems.coin1, "1 " + CityConfig.currencySmall); LanguageRegistry.addName(CoreItems.coin2, "2 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin5, "5 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin10, "10 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin25, "25 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin50, "50 " + CityConfig.currencySmallPlural); LanguageRegistry.addName(CoreItems.coin100, "1 " + CityConfig.currencyLarge + " Coin"); LanguageRegistry.addName(CoreItems.note100, "1 " + CityConfig.currencyLarge); LanguageRegistry.addName(CoreItems.note200, "2 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note500, "5 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note1000, "10 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note2000, "20 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note5000, "50 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.note10000, "100 " + CityConfig.currencyLargePlural); LanguageRegistry.addName(CoreItems.debitCard, "Debit Card (Broken)"); LanguageRegistry.addName(CoreItems.debitCardNew, "Debit Card"); LanguageRegistry.addName(CoreItems.bankerSpawner, "Banker Spawner"); LanguageRegistry.addName(CoreItems.idCard, "ID Card"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 0), "White Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 1), "Light Grey Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 2), "Dark Grey Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 3), "Black Skyscraper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 4), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 5), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 6), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 7), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 8), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 9), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 10), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 11), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 12), "White Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 13), "Light Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 14), "Dark Grey Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.skyscraperBlocks, 1, 15), "Black Skyscraper Block (Framed)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 0), "White Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 1), "Orange Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 2), "Magenta Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 3), "Light Blue Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 4), "Yellow Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 5), "Lime Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 6), "Pink Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 7), "Grey Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 8), "Light Grey Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 9), "Cyan Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 10), "Purple Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 11), "Blue Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 12), "Brown Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 13), "Green Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 14), "Red Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlass, 1, 15), "Black Stained Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 0), "White Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 1), "Orange Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 2), "Magenta Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 3), "Light Blue Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 4), "Yellow Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 5), "Lime Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 6), "Pink Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 7), "Grey Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 8), "Light Grey Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 9), "Cyan Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 10), "Purple Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 11), "Blue Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 12), "Brown Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 13), "Green Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 14), "Red Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.stainedGlassLit, 1, 15), "Black Stained Glass (Lit)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 0), "Blue White-framed Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 1), "Blue Horizontal Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 2), "Blue Vertical Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 3), "Blue Framed Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 4), "Blue Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 5), "Blue Framed Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 6), "Blue Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 7), "Blue Framed Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 8), "Blue Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 9), "Blue Small Squares"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 10), "Blue Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 11), "Blue Supercross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 12), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 13), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 14), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlass, 1, 15), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 0), "Clear White-framed Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 1), "Clear Horizontal Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 2), "Clear Vertical Forked Glass"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 3), "Clear Framed Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 4), "Clear Aligned Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 5), "Clear Framed Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 6), "Clear Horizontal Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 7), "Clear Framed Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 8), "Clear Vertical Line"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 9), "Clear Small Squares"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 10), "Clear Cross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 11), "Clear Supercross"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 12), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 13), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 14), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.styledGlassWhite, 1, 15), "Suggest!"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 0), "White Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 1), "Orange Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 2), "Magenta Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 3), "Light Blue Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 4), "Yellow Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 5), "Lime Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 6), "Pink Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 7), "Grey Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 8), "Light Grey Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 9), "Cyan Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 10), "Purple Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 11), "Blue Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 12), "Brown Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 13), "Green Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 14), "Red Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolCeilingTile, 1, 15), "Black Wool-Topped Ceiling Tile"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 0), "White Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 1), "Orange Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 2), "Magenta Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 3), "Light Blue Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 4), "Yellow Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 5), "Lime Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 6), "Pink Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 7), "Grey Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 8), "Light Grey Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 9), "Cyan Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 10), "Purple Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 11), "Blue Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 12), "Brown Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 13), "Green Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 14), "Red Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolStone, 1, 15), "Black Wool-Topped Stone"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 0), "White Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 1), "Orange Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 2), "Magenta Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 3), "Light Blue Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 4), "Yellow Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 5), "Lime Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 6), "Pink Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 7), "Grey Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 8), "Light Grey Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 9), "Cyan Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 10), "Purple Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 11), "Blue Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 12), "Brown Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 13), "Green Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 14), "Red Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.woolWood, 1, 15), "Black Wool-Topped Wood"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 0), "White Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 1), "Orange Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 2), "Magenta Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 3), "Light Blue Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 4), "Yellow Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 5), "Lime Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 6), "Pink Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 7), "Grey Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 8), "Light Grey Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 9), "Cyan Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 10), "Purple Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 11), "Blue Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 12), "Brown Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 13), "Green Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 14), "Red Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.plasticBlock, 1, 15), "Black Plastic Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 0), "Bathroom Tiles"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 1), "Kitchen Tiles"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 2), "Generic Tiles 1"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 3), "Generic Tiles 2"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 4), "Oak Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 5), "Spruce Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 6), "Birch Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 7), "Jungle Wood Laminate"); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 8), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 9), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 10), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 11), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 12), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 13), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 14), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.floorBlocks, 1, 15), ""); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingBlocks, 1, 1), "Light Panel"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingBlocks, 1, 2), "Ceiling Light"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 0), "Vertical Light Strip"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 4), "Vertical Light Strip (Short)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 8), "Vertical Light Panel"); LanguageRegistry.addName(new ItemStack(CoreBlocks.lightingRotateBlocks, 1, 12), "Vertical Light Panel (Small)"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 0), "Copper Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 1), "Tin Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 2), "Ruby Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 3), "Sapphire Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 4), "Tecmonium Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 5), "Crystal Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 6), "Silver Block"); LanguageRegistry.addName(new ItemStack(CoreBlocks.oreStorageBlock, 1, 7), "Titanium Block"); /*LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 0), "Silvania VA"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 4), "Remula"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 8), "9"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster1, 1, 12), "13"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 0), "17"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 4), "21"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 8), "25"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster2, 1, 12), "29"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 0), "DoanVPS Poster"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 4), "Ad Slot 2"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 8), "Ad Slot 3"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster3, 1, 12), "Ad Slot 4"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 0), "Ad Slot 5"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 4), "Ad Slot 6"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 8), "Ad Slot 7"); LanguageRegistry.addName(new ItemStack(FlenixCities.verticalPoster4, 1, 12), "Ad Slot 8");*/ }
diff --git a/src/test/java/au/net/netstorm/boost/test/parallel/DefaultTestLifecycleRunner.java b/src/test/java/au/net/netstorm/boost/test/parallel/DefaultTestLifecycleRunner.java index ba0ab43ab..4858e5d8b 100644 --- a/src/test/java/au/net/netstorm/boost/test/parallel/DefaultTestLifecycleRunner.java +++ b/src/test/java/au/net/netstorm/boost/test/parallel/DefaultTestLifecycleRunner.java @@ -1,31 +1,31 @@ package au.net.netstorm.boost.test.parallel; import java.util.ArrayList; import java.util.List; import au.net.netstorm.boost.test.lifecycle.LifecycleTest; import au.net.netstorm.boost.test.lifecycle.TestLifecycle; public class DefaultTestLifecycleRunner implements TestLifecycleRunner { private final TestExceptionHandler handler = new DefaultTestExceptionHandler(); private final TestEngine engine = new DefaultTestEngine(); public void run(LifecycleTest test) throws Throwable { List exceptions = runTest(test); handler.checkExceptions(exceptions); } private List runTest(LifecycleTest test) { - // FIX (Nov 27, 2007) TESTING 83271 Change this to 'Errors'. + // FIX (Nov 27, 2007) TESTING 83271 Change this to ThrowableArray. List exceptions = new ArrayList(); TestLifecycle lifecycle = test.lifecycle(); try { engine.runTest(test, lifecycle); } catch (Throwable t) { Throwable throwable = engine.error(test, t); exceptions.add(throwable); } finally { engine.tryCleanup(lifecycle); } return exceptions; } }
true
true
private List runTest(LifecycleTest test) { // FIX (Nov 27, 2007) TESTING 83271 Change this to 'Errors'. List exceptions = new ArrayList(); TestLifecycle lifecycle = test.lifecycle(); try { engine.runTest(test, lifecycle); } catch (Throwable t) { Throwable throwable = engine.error(test, t); exceptions.add(throwable); } finally { engine.tryCleanup(lifecycle); } return exceptions; }
private List runTest(LifecycleTest test) { // FIX (Nov 27, 2007) TESTING 83271 Change this to ThrowableArray. List exceptions = new ArrayList(); TestLifecycle lifecycle = test.lifecycle(); try { engine.runTest(test, lifecycle); } catch (Throwable t) { Throwable throwable = engine.error(test, t); exceptions.add(throwable); } finally { engine.tryCleanup(lifecycle); } return exceptions; }
diff --git a/src/musician101/emergencywhitelist/runnables/KickPlayers.java b/src/musician101/emergencywhitelist/runnables/KickPlayers.java index 9290c07..a165379 100644 --- a/src/musician101/emergencywhitelist/runnables/KickPlayers.java +++ b/src/musician101/emergencywhitelist/runnables/KickPlayers.java @@ -1,36 +1,36 @@ package musician101.emergencywhitelist.runnables; import musician101.emergencywhitelist.EmergencyWhitelist; import musician101.emergencywhitelist.lib.Constants; import org.bukkit.Bukkit; import org.bukkit.entity.Player; /** * Checks player permissions and kicks those who lack them. * * @author Musician101 */ public class KickPlayers implements Runnable { EmergencyWhitelist plugin; /** * @param plugin Reference the plugin's main class. */ public KickPlayers(EmergencyWhitelist plugin) { this.plugin = plugin; } @Override public void run() { Player[] players = Bukkit.getOnlinePlayers(); for (Player player : players) { if (!player.hasPermission(Constants.PERMISSION_WHITELIST)) - player.kickPlayer("Server Whitelist has been enabled."); + player.kickPlayer("Server whitelist has been enabled."); } } }
true
true
public void run() { Player[] players = Bukkit.getOnlinePlayers(); for (Player player : players) { if (!player.hasPermission(Constants.PERMISSION_WHITELIST)) player.kickPlayer("Server Whitelist has been enabled."); } }
public void run() { Player[] players = Bukkit.getOnlinePlayers(); for (Player player : players) { if (!player.hasPermission(Constants.PERMISSION_WHITELIST)) player.kickPlayer("Server whitelist has been enabled."); } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/SelectRepositoryConnectorPage.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/SelectRepositoryConnectorPage.java index 9ebb957a2..581fefc22 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/SelectRepositoryConnectorPage.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/wizards/SelectRepositoryConnectorPage.java @@ -1,192 +1,192 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.core.commands.Command; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.expressions.EvaluationContext; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.mylyn.commons.core.StatusHandler; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.internal.tasks.ui.views.TaskRepositoriesSorter; import org.eclipse.mylyn.internal.tasks.ui.views.TaskRepositoryLabelProvider; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.handlers.IHandlerService; /** * @author Mik Kersten * @author David Green */ public class SelectRepositoryConnectorPage extends WizardPage { private TableViewer viewer; private AbstractRepositoryConnector connector; static class RepositoryContentProvider implements IStructuredContentProvider { public void inputChanged(Viewer v, Object oldInput, Object newInput) { } public void dispose() { } public Object[] getElements(Object parent) { List<AbstractRepositoryConnector> userManagedRepositories = new ArrayList<AbstractRepositoryConnector>(); for (AbstractRepositoryConnector connector : TasksUi.getRepositoryManager().getRepositoryConnectors()) { if (connector.isUserManaged()) { userManagedRepositories.add(connector); } } return userManagedRepositories.toArray(); } } public SelectRepositoryConnectorPage() { super(Messages.SelectRepositoryConnectorPage_Select_a_task_repository_type); setTitle(Messages.SelectRepositoryConnectorPage_Select_a_task_repository_type); setDescription(Messages.SelectRepositoryConnectorPage_You_can_connect_to_an_existing_account_using_one_of_the_installed_connectors); } @Override public boolean canFlipToNextPage() { return connector != null; } public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); - GridLayoutFactory.fillDefaults().numColumns(1).applyTo(container); + GridLayoutFactory.fillDefaults().numColumns(1).spacing(0, 3).applyTo(container); viewer = new TableViewer(container, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new RepositoryContentProvider()); viewer.setSorter(new TaskRepositoriesSorter()); viewer.setLabelProvider(new TaskRepositoryLabelProvider()); viewer.setInput(TasksUi.getRepositoryManager().getRepositoryConnectors()); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.getFirstElement() instanceof AbstractRepositoryConnector) { connector = (AbstractRepositoryConnector) selection.getFirstElement(); setPageComplete(true); } } }); viewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { getContainer().showPage(getNextPage()); } }); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getControl()); // add a hyperlink for connector discovery if it's available and enabled. ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (service != null && handlerService != null) { // we integrate with discovery via a well-known command, which when invoked launches the discovery wizard final Command discoveryWizardCommand = service.getCommand("org.eclipse.mylyn.discovery.ui.discoveryWizardCommand"); //$NON-NLS-1$ if (discoveryWizardCommand != null) { // update enabled state in case something has changed (ProxyHandler caches state) // XXX remove reflection when we no longer support 3.3 try { Command.class.getDeclaredMethod("setEnabled", Object.class).invoke(discoveryWizardCommand, //$NON-NLS-1$ createEvaluationContext(handlerService)); } catch (InvocationTargetException e1) { Throwable cause = e1.getCause(); StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "unexpected exception", cause)); //$NON-NLS-1$ } catch (Exception e1) { // expected on Eclipse 3.3 } if (discoveryWizardCommand.isEnabled()) { Button discoveryButton = new Button(container, SWT.PUSH); GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(discoveryButton); discoveryButton.setText(Messages.SelectRepositoryConnectorPage_activateDiscovery); discoveryButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { widgetDefaultSelected(event); } @Override public void widgetDefaultSelected(SelectionEvent event) { IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService( IHandlerService.class); try { discoveryWizardCommand.executeWithChecks(createExecutionEvent(discoveryWizardCommand, handlerService)); } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, NLS.bind( Messages.SelectRepositoryConnectorPage_discoveryProblemMessage, new Object[] { e.getMessage() }), e); TasksUiInternal.logAndDisplayStatus( Messages.SelectRepositoryConnectorPage_discoveryProblemTitle, status); } } }); } } } Dialog.applyDialogFont(container); setControl(container); } private ExecutionEvent createExecutionEvent(Command command, IHandlerService handlerService) { return new ExecutionEvent(command, Collections.emptyMap(), null, createEvaluationContext(handlerService)); } private EvaluationContext createEvaluationContext(IHandlerService handlerService) { EvaluationContext evaluationContext = new EvaluationContext(handlerService.getCurrentState(), Platform.class); // must specify this variable otherwise the PlatformPropertyTester won't work evaluationContext.addVariable("platform", Platform.class); //$NON-NLS-1$ return evaluationContext; } public AbstractRepositoryConnector getConnector() { return connector; } }
true
true
public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); GridLayoutFactory.fillDefaults().numColumns(1).applyTo(container); viewer = new TableViewer(container, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new RepositoryContentProvider()); viewer.setSorter(new TaskRepositoriesSorter()); viewer.setLabelProvider(new TaskRepositoryLabelProvider()); viewer.setInput(TasksUi.getRepositoryManager().getRepositoryConnectors()); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.getFirstElement() instanceof AbstractRepositoryConnector) { connector = (AbstractRepositoryConnector) selection.getFirstElement(); setPageComplete(true); } } }); viewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { getContainer().showPage(getNextPage()); } }); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getControl()); // add a hyperlink for connector discovery if it's available and enabled. ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (service != null && handlerService != null) { // we integrate with discovery via a well-known command, which when invoked launches the discovery wizard final Command discoveryWizardCommand = service.getCommand("org.eclipse.mylyn.discovery.ui.discoveryWizardCommand"); //$NON-NLS-1$ if (discoveryWizardCommand != null) { // update enabled state in case something has changed (ProxyHandler caches state) // XXX remove reflection when we no longer support 3.3 try { Command.class.getDeclaredMethod("setEnabled", Object.class).invoke(discoveryWizardCommand, //$NON-NLS-1$ createEvaluationContext(handlerService)); } catch (InvocationTargetException e1) { Throwable cause = e1.getCause(); StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "unexpected exception", cause)); //$NON-NLS-1$ } catch (Exception e1) { // expected on Eclipse 3.3 } if (discoveryWizardCommand.isEnabled()) { Button discoveryButton = new Button(container, SWT.PUSH); GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(discoveryButton); discoveryButton.setText(Messages.SelectRepositoryConnectorPage_activateDiscovery); discoveryButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { widgetDefaultSelected(event); } @Override public void widgetDefaultSelected(SelectionEvent event) { IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService( IHandlerService.class); try { discoveryWizardCommand.executeWithChecks(createExecutionEvent(discoveryWizardCommand, handlerService)); } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, NLS.bind( Messages.SelectRepositoryConnectorPage_discoveryProblemMessage, new Object[] { e.getMessage() }), e); TasksUiInternal.logAndDisplayStatus( Messages.SelectRepositoryConnectorPage_discoveryProblemTitle, status); } } }); } } } Dialog.applyDialogFont(container); setControl(container); }
public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); GridLayoutFactory.fillDefaults().numColumns(1).spacing(0, 3).applyTo(container); viewer = new TableViewer(container, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new RepositoryContentProvider()); viewer.setSorter(new TaskRepositoriesSorter()); viewer.setLabelProvider(new TaskRepositoryLabelProvider()); viewer.setInput(TasksUi.getRepositoryManager().getRepositoryConnectors()); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.getFirstElement() instanceof AbstractRepositoryConnector) { connector = (AbstractRepositoryConnector) selection.getFirstElement(); setPageComplete(true); } } }); viewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { getContainer().showPage(getNextPage()); } }); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getControl()); // add a hyperlink for connector discovery if it's available and enabled. ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class); IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (service != null && handlerService != null) { // we integrate with discovery via a well-known command, which when invoked launches the discovery wizard final Command discoveryWizardCommand = service.getCommand("org.eclipse.mylyn.discovery.ui.discoveryWizardCommand"); //$NON-NLS-1$ if (discoveryWizardCommand != null) { // update enabled state in case something has changed (ProxyHandler caches state) // XXX remove reflection when we no longer support 3.3 try { Command.class.getDeclaredMethod("setEnabled", Object.class).invoke(discoveryWizardCommand, //$NON-NLS-1$ createEvaluationContext(handlerService)); } catch (InvocationTargetException e1) { Throwable cause = e1.getCause(); StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "unexpected exception", cause)); //$NON-NLS-1$ } catch (Exception e1) { // expected on Eclipse 3.3 } if (discoveryWizardCommand.isEnabled()) { Button discoveryButton = new Button(container, SWT.PUSH); GridDataFactory.swtDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(discoveryButton); discoveryButton.setText(Messages.SelectRepositoryConnectorPage_activateDiscovery); discoveryButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { widgetDefaultSelected(event); } @Override public void widgetDefaultSelected(SelectionEvent event) { IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService( IHandlerService.class); try { discoveryWizardCommand.executeWithChecks(createExecutionEvent(discoveryWizardCommand, handlerService)); } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, NLS.bind( Messages.SelectRepositoryConnectorPage_discoveryProblemMessage, new Object[] { e.getMessage() }), e); TasksUiInternal.logAndDisplayStatus( Messages.SelectRepositoryConnectorPage_discoveryProblemTitle, status); } } }); } } } Dialog.applyDialogFont(container); setControl(container); }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableUsageInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableUsageInfo.java index 360a9d89..2cd6db33 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableUsageInfo.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableUsageInfo.java @@ -1,140 +1,139 @@ package jp.ac.osaka_u.ist.sel.metricstool.main.data.target; import java.util.Collections; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; /** * �ϐ��g�p��\�����ۃN���X * * @author higo * @param <T> �g�p����Ă���ϐ� */ public abstract class VariableUsageInfo<T extends VariableInfo<? extends UnitInfo>> extends ExpressionInfo { /** * * @param usedVariable �g�p����Ă���ϐ� * @param reference �Q�Ƃ��ǂ��� * @param ownerMethod �I�[�i�[���\�b�h * @param fromLine �J�n�s * @param fromColumn �J�n�� * @param toLine �I���s * @param toColumn �I���� */ VariableUsageInfo(final T usedVariable, final boolean reference, final CallableUnitInfo ownerMethod, final int fromLine, final int fromColumn, final int toLine, final int toColumn) { super(ownerMethod, fromLine, fromColumn, toLine, toColumn); this.usedVariable = usedVariable; this.reference = reference; } /** * �g�p����Ă���ϐ���Ԃ� * * @return �g�p����Ă���ϐ� */ public final T getUsedVariable() { return this.usedVariable; } /** * �Q�Ƃ��������Ԃ� * * @return �Q�Ƃł���ꍇ�� true�C����ł���ꍇ�� false */ public final boolean isReference() { return this.reference; } /** * ���̃t�B�[���h�g�p������ł��邩�ǂ�����Ԃ� * * @return ����ł���ꍇ�� true�C�Q�Ƃł���ꍇ�� false */ public final boolean isAssignment() { return !this.reference; } @Override public SortedSet<VariableUsageInfo<?>> getVariableUsages() { final SortedSet<VariableUsageInfo<?>> variableUsage = new TreeSet<VariableUsageInfo<?>>(); variableUsage.add(this); return Collections.unmodifiableSortedSet(variableUsage); } /** * ���̕ϐ��g�p�̃e�L�X�g�\���i�^�j��Ԃ� * * @return ���̕ϐ��g�p�̃e�L�X�g�\���i�^�j */ @Override public final String getText() { final T variable = this.getUsedVariable(); return variable.getName(); } /** * ���̃t�B�[���h�g�p�̌^��Ԃ� * * @return ���̃t�B�[���h�g�p�̌^ */ @Override public TypeInfo getType() { final T usedVariable = this.getUsedVariable(); final TypeInfo definitionType = usedVariable.getType(); // ��`�̕Ԃ�l���^�p�����[�^�łȂ���΂��̂܂ܕԂ��� if (!(definitionType instanceof TypeParameterInfo)) { return definitionType; } // �^�p�����[�^����C���ۂɎg�p����Ă���^���擾���Ԃ� // ���\�b�h�̌^�p�����[�^���ǂ��� - final StatementInfo ownerStatement = this.getOwnerStatement(); - final CallableUnitInfo ownerMethod = ownerStatement.getOwnerMethod(); + final CallableUnitInfo ownerMethod = this.getOwnerMethod(); for (final TypeParameterInfo typeParameter : ownerMethod.getTypeParameters()) { if (typeParameter.equals(definitionType)) { return ((TypeParameterInfo) definitionType).getExtendsType(); } } //�@�N���X�̌^�p�����[�^���ǂ��� final ClassInfo ownerClass = ownerMethod.getOwnerClass(); for (final TypeParameterInfo typeParameter : ownerClass.getTypeParameters()) { if (typeParameter.equals(definitionType)) { return ((TypeParameterInfo) definitionType).getExtendsType(); } } //�@�e�N���X�Œ�`���ꂽ�^�p�����[�^�� final Map<TypeParameterInfo, TypeInfo> typeParameterUsages = ownerClass .getTypeParameterUsages(); for (final TypeParameterInfo typeParameter : typeParameterUsages.keySet()) { if (typeParameter.equals(definitionType)) { return typeParameterUsages.get(typeParameter); } } throw new IllegalStateException(); } private final T usedVariable; private final boolean reference; /** * ��̕ϐ����p��Set��\�� */ public static final SortedSet<VariableUsageInfo<?>> EmptySet = Collections .unmodifiableSortedSet(new TreeSet<VariableUsageInfo<?>>()); }
true
true
public TypeInfo getType() { final T usedVariable = this.getUsedVariable(); final TypeInfo definitionType = usedVariable.getType(); // ��`�̕Ԃ�l���^�p�����[�^�łȂ���΂��̂܂ܕԂ��� if (!(definitionType instanceof TypeParameterInfo)) { return definitionType; } // �^�p�����[�^����C���ۂɎg�p����Ă���^���擾���Ԃ� // ���\�b�h�̌^�p�����[�^���ǂ��� final StatementInfo ownerStatement = this.getOwnerStatement(); final CallableUnitInfo ownerMethod = ownerStatement.getOwnerMethod(); for (final TypeParameterInfo typeParameter : ownerMethod.getTypeParameters()) { if (typeParameter.equals(definitionType)) { return ((TypeParameterInfo) definitionType).getExtendsType(); } } //�@�N���X�̌^�p�����[�^���ǂ��� final ClassInfo ownerClass = ownerMethod.getOwnerClass(); for (final TypeParameterInfo typeParameter : ownerClass.getTypeParameters()) { if (typeParameter.equals(definitionType)) { return ((TypeParameterInfo) definitionType).getExtendsType(); } } //�@�e�N���X�Œ�`���ꂽ�^�p�����[�^�� final Map<TypeParameterInfo, TypeInfo> typeParameterUsages = ownerClass .getTypeParameterUsages(); for (final TypeParameterInfo typeParameter : typeParameterUsages.keySet()) { if (typeParameter.equals(definitionType)) { return typeParameterUsages.get(typeParameter); } } throw new IllegalStateException(); }
public TypeInfo getType() { final T usedVariable = this.getUsedVariable(); final TypeInfo definitionType = usedVariable.getType(); // ��`�̕Ԃ�l���^�p�����[�^�łȂ���΂��̂܂ܕԂ��� if (!(definitionType instanceof TypeParameterInfo)) { return definitionType; } // �^�p�����[�^����C���ۂɎg�p����Ă���^���擾���Ԃ� // ���\�b�h�̌^�p�����[�^���ǂ��� final CallableUnitInfo ownerMethod = this.getOwnerMethod(); for (final TypeParameterInfo typeParameter : ownerMethod.getTypeParameters()) { if (typeParameter.equals(definitionType)) { return ((TypeParameterInfo) definitionType).getExtendsType(); } } //�@�N���X�̌^�p�����[�^���ǂ��� final ClassInfo ownerClass = ownerMethod.getOwnerClass(); for (final TypeParameterInfo typeParameter : ownerClass.getTypeParameters()) { if (typeParameter.equals(definitionType)) { return ((TypeParameterInfo) definitionType).getExtendsType(); } } //�@�e�N���X�Œ�`���ꂽ�^�p�����[�^�� final Map<TypeParameterInfo, TypeInfo> typeParameterUsages = ownerClass .getTypeParameterUsages(); for (final TypeParameterInfo typeParameter : typeParameterUsages.keySet()) { if (typeParameter.equals(definitionType)) { return typeParameterUsages.get(typeParameter); } } throw new IllegalStateException(); }
diff --git a/libraries/javalib/java/security/Security.java b/libraries/javalib/java/security/Security.java index bc06fbf10..2e2cd0cfc 100644 --- a/libraries/javalib/java/security/Security.java +++ b/libraries/javalib/java/security/Security.java @@ -1,295 +1,294 @@ /* * Java core library component. * * Copyright (c) 1999 * Archie L. Cobbs. All rights reserved. * Copyright (c) 1999 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. * * Author: Archie L. Cobbs <[email protected]> */ package java.security; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Vector; public final class Security { private static final String PROV_PREFIX = "security.provider."; private static final String DEF_PROV = "kaffe.security.provider.Kaffe"; private static final Properties props = new Properties(); private static final Vector providers = new Vector(); static { // Set default security provider if none specified props.put(PROV_PREFIX + "1", DEF_PROV); // Read in master security properties from "java.security" file readProps: { File file = new File( System.getProperties().getProperty("java.home") + "/jre/lib/security/java.security"); if (file.exists()) { try { props.load( new BufferedInputStream( new FileInputStream(file))); } catch (FileNotFoundException e) { } catch (IOException e) { } } } // Install configured security providers for (Iterator i = props.entrySet().iterator(); i.hasNext(); ) { ClassLoader cl = ClassLoader.getSystemClassLoader(); Map.Entry ent = (Map.Entry)i.next(); String key = (String)ent.getKey(); if (!key.startsWith(PROV_PREFIX)) { continue; } try { insertProviderAt( (Provider)cl.loadClass( (String)ent.getValue()).newInstance(), Integer.parseInt( key.substring(PROV_PREFIX.length()))); } catch (NumberFormatException e) { } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (IllegalArgumentException e) { } catch (ClassCastException e) { } } // Should also read Policy stuff here... } // This class is not instantiable private Security() { } public static String getAlgorithmProperty(String alg, String prop) { String id = "Alg." + prop + "." + alg; for (int i = 0; i < providers.size(); i++) { Provider p = (Provider)providers.elementAt(i); String val = p.getProperty(id); if (val != null) { return (val); } } return (null); } public static int insertProviderAt(Provider provider, int position) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkSecurityAccess("insertProvider." + provider.getName()); if (--position < 0) { throw new IllegalArgumentException(); } synchronized (providers) { int tempPosition; if ((tempPosition = findProvider(provider.getName())) >= 0) { return tempPosition + 1; } if (position > providers.size()) { position = providers.size(); } providers.insertElementAt(provider, position); } return position + 1; } public static int addProvider(Provider provider) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkSecurityAccess("insertProvider." + provider.getName()); synchronized (providers) { if (findProvider(provider.getName()) >= 0) { return -1; } return insertProviderAt(provider, providers.size() + 1); } } public static void removeProvider(String name) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkSecurityAccess("removeProvider." + name); synchronized (providers) { int posn = findProvider(name); if (posn >= 0) { providers.removeElementAt(posn); } } } public static Provider[] getProviders() { synchronized (providers) { Provider[] pa = new Provider[providers.size()]; System.arraycopy( providers.toArray(), 0, pa, 0, pa.length); return pa; } } public static Provider getProvider(String name) { synchronized (providers) { int position = findProvider(name); return (position >= 0) ? (Provider)providers.elementAt(position) : null; } } public static String getProperty(String key) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new SecurityPermission("getProperty." + key)); synchronized (props) { return (String)props.get(key); } } public static void setProperty(String key, String value) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new SecurityPermission("setProperty." + key)); synchronized (props) { props.put(key, value); } } private static int findProvider(String name) { for (int i = 0; i < providers.size(); i++) { Provider p = (Provider)providers.elementAt(i); if (p.getName().equals(name)) { return i; } } return -1; } static class Engine { final Provider provider; final String algorithm; final Object engine; Engine(Provider provider, String algorithm, Object engine) { this.provider = provider; this.algorithm = algorithm; this.engine = engine; } Provider getProvider() { return this.provider; } String getAlgorithm() { return this.algorithm; } Object getEngine() { return this.engine; } } static Engine getCryptInstance(String engClass) throws NoSuchAlgorithmException { return getCryptInstance(engClass, null); } static Engine getCryptInstance(String engClass, String algorithm) throws NoSuchAlgorithmException { Provider[] providers = getProviders(); for (int i = 0; i < providers.length; i++) { try { return getCryptInstance(engClass, algorithm, providers[i]); } catch (NoSuchAlgorithmException e) { } } throw algorithm == null ? new NoSuchAlgorithmException() : new NoSuchAlgorithmException(algorithm); } static Engine getCryptInstance(String engClass, String alg, String prov) throws NoSuchAlgorithmException, NoSuchProviderException { // Make sure provider is installed Provider p = getProvider(prov); if (p == null) { throw new NoSuchProviderException(prov); } return getCryptInstance(engClass, alg, p); } static Engine getCryptInstance(String engClass, String alg, Provider p) throws NoSuchAlgorithmException { // See if algorithm name is an alias if (alg != null) { String alias = (String)p.get("Alg.Alias." + engClass + "." + alg); if (alias != null) { alg = alias; } } // Find a class that implements the class and algorithm String name = null; if (alg != null) { name = (String)p.get(engClass + "." + alg); } else { String prefix = engClass + "."; for (Iterator i = p.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); String key = (String)e.getKey(); if (key.startsWith(prefix)) { alg = key.substring(prefix.length()); name = (String)e.getValue(); break; } } } if (name == null) { throw new NoSuchAlgorithmException( "\"" + alg + "\" not supported by provider"); } // Instantiate class try { - ClassLoader cl = ClassLoader.getSystemClassLoader(); return new Engine(p, alg, - cl.loadClass(name).newInstance()); + Class.forName(name, true, p.getClass().getClassLoader()).newInstance()); } catch (ClassNotFoundException e) { throw new NoSuchAlgorithmException("class " + name + " not found"); } catch (Exception e) { throw new NoSuchAlgorithmException("can't instantiate" + " class " + name + ": " + e); } } }
false
true
static Engine getCryptInstance(String engClass, String alg, Provider p) throws NoSuchAlgorithmException { // See if algorithm name is an alias if (alg != null) { String alias = (String)p.get("Alg.Alias." + engClass + "." + alg); if (alias != null) { alg = alias; } } // Find a class that implements the class and algorithm String name = null; if (alg != null) { name = (String)p.get(engClass + "." + alg); } else { String prefix = engClass + "."; for (Iterator i = p.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); String key = (String)e.getKey(); if (key.startsWith(prefix)) { alg = key.substring(prefix.length()); name = (String)e.getValue(); break; } } } if (name == null) { throw new NoSuchAlgorithmException( "\"" + alg + "\" not supported by provider"); } // Instantiate class try { ClassLoader cl = ClassLoader.getSystemClassLoader(); return new Engine(p, alg, cl.loadClass(name).newInstance()); } catch (ClassNotFoundException e) { throw new NoSuchAlgorithmException("class " + name + " not found"); } catch (Exception e) { throw new NoSuchAlgorithmException("can't instantiate" + " class " + name + ": " + e); } }
static Engine getCryptInstance(String engClass, String alg, Provider p) throws NoSuchAlgorithmException { // See if algorithm name is an alias if (alg != null) { String alias = (String)p.get("Alg.Alias." + engClass + "." + alg); if (alias != null) { alg = alias; } } // Find a class that implements the class and algorithm String name = null; if (alg != null) { name = (String)p.get(engClass + "." + alg); } else { String prefix = engClass + "."; for (Iterator i = p.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); String key = (String)e.getKey(); if (key.startsWith(prefix)) { alg = key.substring(prefix.length()); name = (String)e.getValue(); break; } } } if (name == null) { throw new NoSuchAlgorithmException( "\"" + alg + "\" not supported by provider"); } // Instantiate class try { return new Engine(p, alg, Class.forName(name, true, p.getClass().getClassLoader()).newInstance()); } catch (ClassNotFoundException e) { throw new NoSuchAlgorithmException("class " + name + " not found"); } catch (Exception e) { throw new NoSuchAlgorithmException("can't instantiate" + " class " + name + ": " + e); } }
diff --git a/java/modules/core/src/org/apache/synapse/config/xml/ProxyServiceFactory.java b/java/modules/core/src/org/apache/synapse/config/xml/ProxyServiceFactory.java index 8d922f15b..02f7283d4 100644 --- a/java/modules/core/src/org/apache/synapse/config/xml/ProxyServiceFactory.java +++ b/java/modules/core/src/org/apache/synapse/config/xml/ProxyServiceFactory.java @@ -1,167 +1,167 @@ /* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.synapse.config.xml; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMElement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.SynapseException; import org.apache.synapse.core.axis2.ProxyService; import javax.xml.namespace.QName; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.StringTokenizer; import java.util.ArrayList; /** * Creates a ProxyService instance using the XML fragment specification * * <proxy name="string" [description="string"] [transports="(http|https|jms)+|all"]> * <target sequence="name" | endpoint="name"/>? // default is main sequence * <wsdl key="string">? * <schema key="string">* * <policy key="string">* * <property name="string" value="string"/>* * <enableRM/>+ * <enableSec/>+ * </proxy> */ public class ProxyServiceFactory { private static final Log log = LogFactory.getLog(ProxyServiceFactory.class); public static ProxyService createProxy(OMElement elem) { ProxyService proxy = new ProxyService(); OMAttribute name = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "name")); if (name == null) { handleException("The 'name' attribute is required for a Proxy service definition"); } else { proxy.setName(name.getAttributeValue()); } OMAttribute trans = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "transports")); if (trans != null) { String transports = trans.getAttributeValue(); if (transports == null || ProxyService.ALL_TRANSPORTS.equals(transports)) { // default to all transports using service name as destination } else { StringTokenizer st = new StringTokenizer(transports, " ,"); ArrayList transportList = new ArrayList(); while(st.hasMoreTokens()) { String token = st.nextToken(); if(token.length() != 0) { transportList.add(token); } } proxy.setTransports(transportList); } } OMAttribute startOnLoad = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "startOnLoad")); if(startOnLoad != null) { - proxy.setStartOnLoad(Boolean.parseBoolean(startOnLoad.getAttributeValue())); + proxy.setStartOnLoad(Boolean.valueOf(startOnLoad.getAttributeValue()).booleanValue()); } else { proxy.setStartOnLoad(true); } // read definition of the target of this proxy service. The target could be an 'endpoint' // or a named sequence. If none of these are specified, the messages would be mediated // by the Synapse main mediator OMElement target = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "target")); if (target != null) { OMAttribute sequence = target.getAttribute(new QName(Constants.NULL_NAMESPACE, "sequence")); if (sequence != null) { proxy.setTargetSequence(sequence.getAttributeValue()); } OMAttribute tgtEndpt = target.getAttribute(new QName(Constants.NULL_NAMESPACE, "endpoint")); if (tgtEndpt != null) { proxy.setTargetEndpoint(tgtEndpt.getAttributeValue()); } } // read the WSDL, Schemas and Policies and set to the proxy service OMElement wsdl = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "wsdl")); if (wsdl != null) { OMAttribute wsdlkey = wsdl.getAttribute(new QName(Constants.NULL_NAMESPACE, "key")); if (wsdlkey == null) { handleException("The 'key' attribute is required for the base WSDL definition"); } else { proxy.setWSDLKey(wsdlkey.getAttributeValue()); } } //OMElement schema = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "schema")); Iterator policies = elem.getChildrenWithName(new QName(Constants.SYNAPSE_NAMESPACE, "policy")); while (policies.hasNext()) { Object o = policies.next(); if (o instanceof OMElement) { OMElement policy = (OMElement) o; OMAttribute key = policy.getAttribute(new QName(Constants.NULL_NAMESPACE, "key")); if (key != null) { proxy.addServiceLevelPoliciy(key.getAttributeValue()); } else { handleException("Policy element does not specify the policy key"); } } else { handleException("Invalid 'policy' element found under element 'policies'"); } } Iterator props = elem.getChildrenWithName(new QName(Constants.SYNAPSE_NAMESPACE, "property")); while (props.hasNext()) { Object o = props.next(); if (o instanceof OMElement) { OMElement prop = (OMElement) o; OMAttribute pname = prop.getAttribute(new QName(Constants.NULL_NAMESPACE, "name")); OMAttribute value = prop.getAttribute(new QName(Constants.NULL_NAMESPACE, "value")); if (pname != null && value != null) { proxy.addProperty(pname.getAttributeValue(), value.getAttributeValue()); } else { handleException("Invalid property specified for proxy service : " + name); } } else { handleException("Invalid property specified for proxy service : " + name); } } if (elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "enableRM")) != null) { proxy.setWsRMEnabled(true); } if (elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "enableSec")) != null) { proxy.setWsSecEnabled(true); } return proxy; } private static void handleException(String msg) { log.error(msg); throw new SynapseException(msg); } private static void handleException(String msg, Exception e) { log.error(msg, e); throw new SynapseException(msg, e); } }
true
true
public static ProxyService createProxy(OMElement elem) { ProxyService proxy = new ProxyService(); OMAttribute name = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "name")); if (name == null) { handleException("The 'name' attribute is required for a Proxy service definition"); } else { proxy.setName(name.getAttributeValue()); } OMAttribute trans = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "transports")); if (trans != null) { String transports = trans.getAttributeValue(); if (transports == null || ProxyService.ALL_TRANSPORTS.equals(transports)) { // default to all transports using service name as destination } else { StringTokenizer st = new StringTokenizer(transports, " ,"); ArrayList transportList = new ArrayList(); while(st.hasMoreTokens()) { String token = st.nextToken(); if(token.length() != 0) { transportList.add(token); } } proxy.setTransports(transportList); } } OMAttribute startOnLoad = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "startOnLoad")); if(startOnLoad != null) { proxy.setStartOnLoad(Boolean.parseBoolean(startOnLoad.getAttributeValue())); } else { proxy.setStartOnLoad(true); } // read definition of the target of this proxy service. The target could be an 'endpoint' // or a named sequence. If none of these are specified, the messages would be mediated // by the Synapse main mediator OMElement target = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "target")); if (target != null) { OMAttribute sequence = target.getAttribute(new QName(Constants.NULL_NAMESPACE, "sequence")); if (sequence != null) { proxy.setTargetSequence(sequence.getAttributeValue()); } OMAttribute tgtEndpt = target.getAttribute(new QName(Constants.NULL_NAMESPACE, "endpoint")); if (tgtEndpt != null) { proxy.setTargetEndpoint(tgtEndpt.getAttributeValue()); } } // read the WSDL, Schemas and Policies and set to the proxy service OMElement wsdl = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "wsdl")); if (wsdl != null) { OMAttribute wsdlkey = wsdl.getAttribute(new QName(Constants.NULL_NAMESPACE, "key")); if (wsdlkey == null) { handleException("The 'key' attribute is required for the base WSDL definition"); } else { proxy.setWSDLKey(wsdlkey.getAttributeValue()); } } //OMElement schema = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "schema")); Iterator policies = elem.getChildrenWithName(new QName(Constants.SYNAPSE_NAMESPACE, "policy")); while (policies.hasNext()) { Object o = policies.next(); if (o instanceof OMElement) { OMElement policy = (OMElement) o; OMAttribute key = policy.getAttribute(new QName(Constants.NULL_NAMESPACE, "key")); if (key != null) { proxy.addServiceLevelPoliciy(key.getAttributeValue()); } else { handleException("Policy element does not specify the policy key"); } } else { handleException("Invalid 'policy' element found under element 'policies'"); } } Iterator props = elem.getChildrenWithName(new QName(Constants.SYNAPSE_NAMESPACE, "property")); while (props.hasNext()) { Object o = props.next(); if (o instanceof OMElement) { OMElement prop = (OMElement) o; OMAttribute pname = prop.getAttribute(new QName(Constants.NULL_NAMESPACE, "name")); OMAttribute value = prop.getAttribute(new QName(Constants.NULL_NAMESPACE, "value")); if (pname != null && value != null) { proxy.addProperty(pname.getAttributeValue(), value.getAttributeValue()); } else { handleException("Invalid property specified for proxy service : " + name); } } else { handleException("Invalid property specified for proxy service : " + name); } } if (elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "enableRM")) != null) { proxy.setWsRMEnabled(true); } if (elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "enableSec")) != null) { proxy.setWsSecEnabled(true); } return proxy; }
public static ProxyService createProxy(OMElement elem) { ProxyService proxy = new ProxyService(); OMAttribute name = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "name")); if (name == null) { handleException("The 'name' attribute is required for a Proxy service definition"); } else { proxy.setName(name.getAttributeValue()); } OMAttribute trans = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "transports")); if (trans != null) { String transports = trans.getAttributeValue(); if (transports == null || ProxyService.ALL_TRANSPORTS.equals(transports)) { // default to all transports using service name as destination } else { StringTokenizer st = new StringTokenizer(transports, " ,"); ArrayList transportList = new ArrayList(); while(st.hasMoreTokens()) { String token = st.nextToken(); if(token.length() != 0) { transportList.add(token); } } proxy.setTransports(transportList); } } OMAttribute startOnLoad = elem.getAttribute(new QName(Constants.NULL_NAMESPACE, "startOnLoad")); if(startOnLoad != null) { proxy.setStartOnLoad(Boolean.valueOf(startOnLoad.getAttributeValue()).booleanValue()); } else { proxy.setStartOnLoad(true); } // read definition of the target of this proxy service. The target could be an 'endpoint' // or a named sequence. If none of these are specified, the messages would be mediated // by the Synapse main mediator OMElement target = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "target")); if (target != null) { OMAttribute sequence = target.getAttribute(new QName(Constants.NULL_NAMESPACE, "sequence")); if (sequence != null) { proxy.setTargetSequence(sequence.getAttributeValue()); } OMAttribute tgtEndpt = target.getAttribute(new QName(Constants.NULL_NAMESPACE, "endpoint")); if (tgtEndpt != null) { proxy.setTargetEndpoint(tgtEndpt.getAttributeValue()); } } // read the WSDL, Schemas and Policies and set to the proxy service OMElement wsdl = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "wsdl")); if (wsdl != null) { OMAttribute wsdlkey = wsdl.getAttribute(new QName(Constants.NULL_NAMESPACE, "key")); if (wsdlkey == null) { handleException("The 'key' attribute is required for the base WSDL definition"); } else { proxy.setWSDLKey(wsdlkey.getAttributeValue()); } } //OMElement schema = elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "schema")); Iterator policies = elem.getChildrenWithName(new QName(Constants.SYNAPSE_NAMESPACE, "policy")); while (policies.hasNext()) { Object o = policies.next(); if (o instanceof OMElement) { OMElement policy = (OMElement) o; OMAttribute key = policy.getAttribute(new QName(Constants.NULL_NAMESPACE, "key")); if (key != null) { proxy.addServiceLevelPoliciy(key.getAttributeValue()); } else { handleException("Policy element does not specify the policy key"); } } else { handleException("Invalid 'policy' element found under element 'policies'"); } } Iterator props = elem.getChildrenWithName(new QName(Constants.SYNAPSE_NAMESPACE, "property")); while (props.hasNext()) { Object o = props.next(); if (o instanceof OMElement) { OMElement prop = (OMElement) o; OMAttribute pname = prop.getAttribute(new QName(Constants.NULL_NAMESPACE, "name")); OMAttribute value = prop.getAttribute(new QName(Constants.NULL_NAMESPACE, "value")); if (pname != null && value != null) { proxy.addProperty(pname.getAttributeValue(), value.getAttributeValue()); } else { handleException("Invalid property specified for proxy service : " + name); } } else { handleException("Invalid property specified for proxy service : " + name); } } if (elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "enableRM")) != null) { proxy.setWsRMEnabled(true); } if (elem.getFirstChildWithName(new QName(Constants.SYNAPSE_NAMESPACE, "enableSec")) != null) { proxy.setWsSecEnabled(true); } return proxy; }
diff --git a/cosmo/src/test/unit/java/org/osaf/cosmo/calendar/RecurrenceExpanderTest.java b/cosmo/src/test/unit/java/org/osaf/cosmo/calendar/RecurrenceExpanderTest.java index c1eb81ec0..8ac53cd7b 100644 --- a/cosmo/src/test/unit/java/org/osaf/cosmo/calendar/RecurrenceExpanderTest.java +++ b/cosmo/src/test/unit/java/org/osaf/cosmo/calendar/RecurrenceExpanderTest.java @@ -1,161 +1,161 @@ /* * Copyright 2007 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osaf.cosmo.calendar; import java.io.FileInputStream; import junit.framework.Assert; import junit.framework.TestCase; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Test RecurrenceExpander. * */ public class RecurrenceExpanderTest extends TestCase { protected String baseDir = "src/test/unit/resources/testdata/expander/"; private static final Log log = LogFactory.getLog(RecurrenceExpanderTest.class); private static final TimeZoneRegistry TIMEZONE_REGISTRY = TimeZoneRegistryFactory.getInstance().createRegistry(); public void testRecurrenceExpanderAllDay() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("allday_recurring1.ics"); Date[] range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101", range[0].toString()); Assert.assertEquals("20070120", range[1].toString()); calendar = getCalendar("allday_recurring2.ics"); range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101", range[0].toString()); Assert.assertNull(range[1]); } public void testRecurrenceExpanderFloating() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("floating_recurring1.ics"); Date[] range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101T100000", range[0].toString()); Assert.assertEquals("20070119T120000", range[1].toString()); calendar = getCalendar("floating_recurring2.ics"); range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101T100000", range[0].toString()); Assert.assertNull(range[1]); } public void testRecurrenceExpanderTimezone() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("tz_recurring1.ics"); Date[] range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101T100000", range[0].toString()); Assert.assertEquals("20070119T120000", range[1].toString()); Assert.assertEquals(((DateTime) range[0]).getTimeZone().getID(), "America/Chicago"); Assert.assertEquals(((DateTime) range[1]).getTimeZone().getID(), "America/Chicago"); calendar = getCalendar("tz_recurring2.ics"); range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101T100000", range[0].toString()); Assert.assertNull(range[1]); Assert.assertEquals(((DateTime) range[0]).getTimeZone().getID(), "America/Chicago"); } public void testRecurrenceExpanderLongEvent() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("tz_recurring3.ics"); Date[] range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20070101T100000", range[0].toString()); Assert.assertEquals("20091231T120000", range[1].toString()); } public void testRecurrenceExpanderRDates() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("floating_recurring3.ics"); Date[] range = expander.calculateRecurrenceRange(calendar); Assert.assertEquals("20061212T100000", range[0].toString()); Assert.assertEquals("20101212T120000", range[1].toString()); } public void testRecurrenceExpanderSingleOccurrence() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("floating_recurring4.ics"); InstanceList instances = expander.getOcurrences(calendar, new DateTime("20080101T100000"), new DateTime("20080101T100001"), null); Assert.assertEquals(1, instances.size()); } public void testIsOccurrence() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("floating_recurring3.ics"); Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000"))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000"))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001"))); // test DATE calendar = getCalendar("allday_recurring3.ics"); Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070101"))); Assert.assertFalse(expander.isOccurrence(calendar, new Date("20070102"))); Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070108"))); // test DATETIME with timezone calendar = getCalendar("tz_recurring3.ics"); - TimeZone ctz = TIMEZONE_REGISTRY.getTimeZone("Americal/Chicago"); + TimeZone ctz = TIMEZONE_REGISTRY.getTimeZone("America/Chicago"); Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000", ctz))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000", ctz))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001", ctz))); } protected Calendar getCalendar(String name) throws Exception { CalendarBuilder cb = new CalendarBuilder(); FileInputStream fis = new FileInputStream(baseDir + name); Calendar calendar = cb.build(fis); return calendar; } }
true
true
public void testIsOccurrence() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("floating_recurring3.ics"); Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000"))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000"))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001"))); // test DATE calendar = getCalendar("allday_recurring3.ics"); Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070101"))); Assert.assertFalse(expander.isOccurrence(calendar, new Date("20070102"))); Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070108"))); // test DATETIME with timezone calendar = getCalendar("tz_recurring3.ics"); TimeZone ctz = TIMEZONE_REGISTRY.getTimeZone("Americal/Chicago"); Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000", ctz))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000", ctz))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001", ctz))); }
public void testIsOccurrence() throws Exception { RecurrenceExpander expander = new RecurrenceExpander(); Calendar calendar = getCalendar("floating_recurring3.ics"); Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000"))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000"))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001"))); // test DATE calendar = getCalendar("allday_recurring3.ics"); Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070101"))); Assert.assertFalse(expander.isOccurrence(calendar, new Date("20070102"))); Assert.assertTrue(expander.isOccurrence(calendar, new Date("20070108"))); // test DATETIME with timezone calendar = getCalendar("tz_recurring3.ics"); TimeZone ctz = TIMEZONE_REGISTRY.getTimeZone("America/Chicago"); Assert.assertTrue(expander.isOccurrence(calendar, new DateTime("20070102T100000", ctz))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T110000", ctz))); Assert.assertFalse(expander.isOccurrence(calendar, new DateTime("20070102T100001", ctz))); }
diff --git a/src/main/java/com/illmeyer/polygraph/template/PolygraphEnvironment.java b/src/main/java/com/illmeyer/polygraph/template/PolygraphEnvironment.java index 90d3311..3c13deb 100644 --- a/src/main/java/com/illmeyer/polygraph/template/PolygraphEnvironment.java +++ b/src/main/java/com/illmeyer/polygraph/template/PolygraphEnvironment.java @@ -1,154 +1,154 @@ /* This file is part of the Polygraph bulk messaging framework Copyright (C) 2013 Wolfgang Illmeyer The Polygraph framework is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.illmeyer.polygraph.template; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import com.illmeyer.polygraph.core.CoreConstants; import com.illmeyer.polygraph.core.data.MessagePart; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.utility.DeepUnwrap; /** * Abstracts away the environment of the template engine and offers an interface more suited to Polygraph's needs * @author escitalopram * */ public class PolygraphEnvironment { private TemplateModel[] loopVars; private TemplateDirectiveBody body; private Environment env; public PolygraphEnvironment(TemplateModel[] loopVars, Environment env, TemplateDirectiveBody body) { this.loopVars=loopVars; this.body=body; this.env=env; } public Object getLoopVar(int index) { try { return DeepUnwrap.unwrap(loopVars[index]) ; } catch (TemplateModelException e) { throw new PolygraphTemplateException(e); } } public void setLoopVar(int index, Object value) { try { loopVars[index]=env.getObjectWrapper().wrap(value); } catch (TemplateModelException e) { throw new PolygraphTemplateException(e); } } public Writer getWriter() { return env.getOut(); } public void executeBody(Writer writer) throws IOException { try { body.render(writer); } catch (TemplateException e) { throw new PolygraphTemplateException(e); } } public TagStack getTagStack() { TagStack ts = (TagStack) env.getCustomAttribute(CoreConstants.ECA_TAGSTACK); if (ts==null) { ts=new TagStack(); env.setCustomAttribute(CoreConstants.ECA_TAGSTACK, ts); } return ts; } public void executeBody() throws IOException { executeBody(getWriter()); } public void registerMessagePart(String name, MessagePart p) throws PolygraphTemplateException { Map<String,MessagePart> parts = getParts(); if (parts.containsKey(name)) throw new PolygraphTemplateException(String.format("Message part '%s' is already registered", name)); parts.put(name, p); } public MessagePart getNamedPart(String name) { Map<String,MessagePart> parts = getParts(); return parts.get(name); } private Map<String,MessagePart> getParts() { @SuppressWarnings("unchecked") Map<String,MessagePart> partMap = (Map<String, MessagePart>) env.getCustomAttribute(CoreConstants.ECA_PARTS); if (partMap==null) { partMap = new HashMap<String, MessagePart>(); env.setCustomAttribute(CoreConstants.ECA_PARTS, partMap); } return partMap; } public <A> A requireParentTag(Class<A> tagClass) { TagStack ts = getTagStack(); if (ts.size()>1) { PolygraphTag tag = ts.get(ts.size()-2); if (tagClass.isInstance(tag)) { @SuppressWarnings("unchecked") A tag2 = (A)tag; return tag2; } } throw new PolygraphTemplateException(String.format("Parent tag of type %s expected but not found.",tagClass.getName())); } public <A> A requireAncestorTag(Class<A> tagClass) { TagStack ts = getTagStack(); if (ts.size()>1) { for (int i=ts.size()-2;i>=0;--i) { PolygraphTag tag=ts.get(i); - if (!tagClass.isInstance(tag)) { + if (tagClass.isInstance(tag)) { @SuppressWarnings("unchecked") A tag2 = (A)tag; return tag2; } } } throw new PolygraphTemplateException(String.format("Ancestor tag of type %s expected but not found.",tagClass.getName())); } public void setCustomAttribute(String key, Object value) { env.setCustomAttribute(key, value); } public Object getCustomAttribute(String key) { return env.getCustomAttribute(key); } public boolean hasBody() { return body!=null; } }
true
true
public <A> A requireAncestorTag(Class<A> tagClass) { TagStack ts = getTagStack(); if (ts.size()>1) { for (int i=ts.size()-2;i>=0;--i) { PolygraphTag tag=ts.get(i); if (!tagClass.isInstance(tag)) { @SuppressWarnings("unchecked") A tag2 = (A)tag; return tag2; } } } throw new PolygraphTemplateException(String.format("Ancestor tag of type %s expected but not found.",tagClass.getName())); }
public <A> A requireAncestorTag(Class<A> tagClass) { TagStack ts = getTagStack(); if (ts.size()>1) { for (int i=ts.size()-2;i>=0;--i) { PolygraphTag tag=ts.get(i); if (tagClass.isInstance(tag)) { @SuppressWarnings("unchecked") A tag2 = (A)tag; return tag2; } } } throw new PolygraphTemplateException(String.format("Ancestor tag of type %s expected but not found.",tagClass.getName())); }
diff --git a/src/org/rascalmpl/interpreter/Typeifier.java b/src/org/rascalmpl/interpreter/Typeifier.java index 1a450fd934..c8381d895d 100644 --- a/src/org/rascalmpl/interpreter/Typeifier.java +++ b/src/org/rascalmpl/interpreter/Typeifier.java @@ -1,244 +1,244 @@ package org.rascalmpl.interpreter; import java.util.LinkedList; import java.util.List; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IMap; import org.eclipse.imp.pdb.facts.IString; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.type.ITypeVisitor; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.rascalmpl.interpreter.asserts.ImplementationError; import org.rascalmpl.interpreter.types.ReifiedType; /** * This class helps transforming reified types back to types and to extract type * declarations from reified types. * * See also {@link TypeReifier}. */ public class Typeifier { private Typeifier(){ super(); } /** * Retrieve the type that is reified by the given value * * @param typeValue a reified type value produced by {@link TypeReifier}. * @return the plain Type that typeValue represented */ public static Type toType(IConstructor typeValue) { Type anonymous = typeValue.getType(); if (anonymous instanceof ReifiedType) { ReifiedType reified = (ReifiedType) anonymous; return reified.getTypeParameters().getFieldType(0); } throw new UnsupportedOperationException("Not a reified type: " + typeValue.getType()); } /** * Locate all declared types in a reified type value, such as abstract data types * constructors and aliases and stores them in the given TypeStore. * * @param typeValue a reified type which is produced by {@link TypeReifier} * @param store a TypeStore to collect declarations in * @return the plain Type that typeValue represented */ public static Type declare(IConstructor typeValue, final TypeStore store) { final List<IConstructor> todo = new LinkedList<IConstructor>(); todo.add(typeValue); while (!todo.isEmpty()) { final IConstructor next = todo.get(0); todo.remove(0); Type type = toType(next); // We dispatch on the real type which is isomorphic to the typeValue. type.accept(new ITypeVisitor<Type>() { private final TypeFactory tf = TypeFactory.getInstance(); public Type visitAbstractData(Type type) { declareADT(next); declareADTParameters(next); declareConstructors(type, next); return type; } public Type visitAlias(Type type) { IConstructor aliased = getAliased(next); todo.add(aliased); // TODO: type parameterized aliases are broken still declareAliasParameters(aliased); return type; } public Type visitBool(Type boolType) { return boolType; } public Type visitConstructor(Type type) { throw new ImplementationError("should not have to typeify this: " + type); } public Type visitExternal(Type externalType) { throw new ImplementationError("should not have to typeify this: " + externalType); } public Type visitInteger(Type type) { return type; } public Type visitNumber(Type type) { return type; } public Type visitList(Type type) { todo.add(getElement(next)); return type; } public Type visitMap(Type type) { todo.add(getKey(next)); todo.add(getValue(next)); return type; } public Type visitNode(Type type) { return type; } public Type visitParameter(Type parameterType) { return parameterType; } public Type visitReal(Type type) { return type; } public Type visitRelationType(Type type) { for (IValue child : next) { todo.add((IConstructor) child); } return type; } public Type visitSet(Type type) { todo.add(getElement(next)); return type; } public Type visitSourceLocation(Type type) { return type; } public Type visitString(Type type) { return type; } public Type visitTuple(Type type) { for (IValue child : (IList) next.get(0)) { todo.add((IConstructor) child); } return type; } public Type visitValue(Type type) { return type; } public Type visitVoid(Type type) { return type; } public Type visitDateTime(Type type) { return type; } private void declareADT(IConstructor next) { IString name = (IString) next.get("name"); - IMap bindings = (IMap) next.get("bindings"); - Type[] parameters = new Type[bindings.size()]; + IList bindings = (IList) next.get("bindings"); + Type[] parameters = new Type[bindings.length()]; int i = 0; for (IValue elem : bindings) { ITuple tuple = (ITuple) elem; parameters[i++] = toType((IConstructor) tuple.get(0)); } tf.abstractDataType(store, name.getValue(), parameters); } private void declareADTParameters(IConstructor next) { - IMap bindings = (IMap) next.get("bindings"); + IList bindings = (IList) next.get("bindings"); for (IValue elem : bindings) { ITuple tuple = (ITuple) elem; declare((IConstructor) tuple.get(1), store); } } private void declareAliasParameters(IConstructor next) { if (next.has("parameters")) { for (IValue p : ((IList) next.get("parameters"))) { todo.add((IConstructor) p); } } } private void declareConstructors(Type adt, IConstructor next) { IList constructors = getConstructors(next); for (IValue c : constructors) { IConstructor cons = (IConstructor) c; IList fields = (IList) cons.get(1); String name = getName(cons); Object[] args = new Object[fields.length() * 2]; int i = 0; for (IValue field : fields) { ITuple tuple = (ITuple) field; IConstructor fieldType = (IConstructor) tuple.get(0); todo.add(fieldType); args[i++] = toType(fieldType); args[i++] = ((IString) tuple.get(1)).getValue(); } tf.constructor(store, adt, name, args); } } private IConstructor getElement(IConstructor next) { return (IConstructor) next.get("element"); } private String getName(final IConstructor next) { return ((IString) next.get("name")).getValue(); } private IConstructor getValue(IConstructor next) { return (IConstructor) next.get("key"); } private IConstructor getAliased(IConstructor next) { return (IConstructor) next.get("aliased"); } private IConstructor getKey(IConstructor next) { return (IConstructor) next.get("value"); } private IList getConstructors(IConstructor next) { return (IList) next.get("constructors"); } }); } return toType(typeValue); } }
false
true
public static Type declare(IConstructor typeValue, final TypeStore store) { final List<IConstructor> todo = new LinkedList<IConstructor>(); todo.add(typeValue); while (!todo.isEmpty()) { final IConstructor next = todo.get(0); todo.remove(0); Type type = toType(next); // We dispatch on the real type which is isomorphic to the typeValue. type.accept(new ITypeVisitor<Type>() { private final TypeFactory tf = TypeFactory.getInstance(); public Type visitAbstractData(Type type) { declareADT(next); declareADTParameters(next); declareConstructors(type, next); return type; } public Type visitAlias(Type type) { IConstructor aliased = getAliased(next); todo.add(aliased); // TODO: type parameterized aliases are broken still declareAliasParameters(aliased); return type; } public Type visitBool(Type boolType) { return boolType; } public Type visitConstructor(Type type) { throw new ImplementationError("should not have to typeify this: " + type); } public Type visitExternal(Type externalType) { throw new ImplementationError("should not have to typeify this: " + externalType); } public Type visitInteger(Type type) { return type; } public Type visitNumber(Type type) { return type; } public Type visitList(Type type) { todo.add(getElement(next)); return type; } public Type visitMap(Type type) { todo.add(getKey(next)); todo.add(getValue(next)); return type; } public Type visitNode(Type type) { return type; } public Type visitParameter(Type parameterType) { return parameterType; } public Type visitReal(Type type) { return type; } public Type visitRelationType(Type type) { for (IValue child : next) { todo.add((IConstructor) child); } return type; } public Type visitSet(Type type) { todo.add(getElement(next)); return type; } public Type visitSourceLocation(Type type) { return type; } public Type visitString(Type type) { return type; } public Type visitTuple(Type type) { for (IValue child : (IList) next.get(0)) { todo.add((IConstructor) child); } return type; } public Type visitValue(Type type) { return type; } public Type visitVoid(Type type) { return type; } public Type visitDateTime(Type type) { return type; } private void declareADT(IConstructor next) { IString name = (IString) next.get("name"); IMap bindings = (IMap) next.get("bindings"); Type[] parameters = new Type[bindings.size()]; int i = 0; for (IValue elem : bindings) { ITuple tuple = (ITuple) elem; parameters[i++] = toType((IConstructor) tuple.get(0)); } tf.abstractDataType(store, name.getValue(), parameters); } private void declareADTParameters(IConstructor next) { IMap bindings = (IMap) next.get("bindings"); for (IValue elem : bindings) { ITuple tuple = (ITuple) elem; declare((IConstructor) tuple.get(1), store); } } private void declareAliasParameters(IConstructor next) { if (next.has("parameters")) { for (IValue p : ((IList) next.get("parameters"))) { todo.add((IConstructor) p); } } } private void declareConstructors(Type adt, IConstructor next) { IList constructors = getConstructors(next); for (IValue c : constructors) { IConstructor cons = (IConstructor) c; IList fields = (IList) cons.get(1); String name = getName(cons); Object[] args = new Object[fields.length() * 2]; int i = 0; for (IValue field : fields) { ITuple tuple = (ITuple) field; IConstructor fieldType = (IConstructor) tuple.get(0); todo.add(fieldType); args[i++] = toType(fieldType); args[i++] = ((IString) tuple.get(1)).getValue(); } tf.constructor(store, adt, name, args); } } private IConstructor getElement(IConstructor next) { return (IConstructor) next.get("element"); } private String getName(final IConstructor next) { return ((IString) next.get("name")).getValue(); } private IConstructor getValue(IConstructor next) { return (IConstructor) next.get("key"); } private IConstructor getAliased(IConstructor next) { return (IConstructor) next.get("aliased"); } private IConstructor getKey(IConstructor next) { return (IConstructor) next.get("value"); } private IList getConstructors(IConstructor next) { return (IList) next.get("constructors"); } }); } return toType(typeValue); }
public static Type declare(IConstructor typeValue, final TypeStore store) { final List<IConstructor> todo = new LinkedList<IConstructor>(); todo.add(typeValue); while (!todo.isEmpty()) { final IConstructor next = todo.get(0); todo.remove(0); Type type = toType(next); // We dispatch on the real type which is isomorphic to the typeValue. type.accept(new ITypeVisitor<Type>() { private final TypeFactory tf = TypeFactory.getInstance(); public Type visitAbstractData(Type type) { declareADT(next); declareADTParameters(next); declareConstructors(type, next); return type; } public Type visitAlias(Type type) { IConstructor aliased = getAliased(next); todo.add(aliased); // TODO: type parameterized aliases are broken still declareAliasParameters(aliased); return type; } public Type visitBool(Type boolType) { return boolType; } public Type visitConstructor(Type type) { throw new ImplementationError("should not have to typeify this: " + type); } public Type visitExternal(Type externalType) { throw new ImplementationError("should not have to typeify this: " + externalType); } public Type visitInteger(Type type) { return type; } public Type visitNumber(Type type) { return type; } public Type visitList(Type type) { todo.add(getElement(next)); return type; } public Type visitMap(Type type) { todo.add(getKey(next)); todo.add(getValue(next)); return type; } public Type visitNode(Type type) { return type; } public Type visitParameter(Type parameterType) { return parameterType; } public Type visitReal(Type type) { return type; } public Type visitRelationType(Type type) { for (IValue child : next) { todo.add((IConstructor) child); } return type; } public Type visitSet(Type type) { todo.add(getElement(next)); return type; } public Type visitSourceLocation(Type type) { return type; } public Type visitString(Type type) { return type; } public Type visitTuple(Type type) { for (IValue child : (IList) next.get(0)) { todo.add((IConstructor) child); } return type; } public Type visitValue(Type type) { return type; } public Type visitVoid(Type type) { return type; } public Type visitDateTime(Type type) { return type; } private void declareADT(IConstructor next) { IString name = (IString) next.get("name"); IList bindings = (IList) next.get("bindings"); Type[] parameters = new Type[bindings.length()]; int i = 0; for (IValue elem : bindings) { ITuple tuple = (ITuple) elem; parameters[i++] = toType((IConstructor) tuple.get(0)); } tf.abstractDataType(store, name.getValue(), parameters); } private void declareADTParameters(IConstructor next) { IList bindings = (IList) next.get("bindings"); for (IValue elem : bindings) { ITuple tuple = (ITuple) elem; declare((IConstructor) tuple.get(1), store); } } private void declareAliasParameters(IConstructor next) { if (next.has("parameters")) { for (IValue p : ((IList) next.get("parameters"))) { todo.add((IConstructor) p); } } } private void declareConstructors(Type adt, IConstructor next) { IList constructors = getConstructors(next); for (IValue c : constructors) { IConstructor cons = (IConstructor) c; IList fields = (IList) cons.get(1); String name = getName(cons); Object[] args = new Object[fields.length() * 2]; int i = 0; for (IValue field : fields) { ITuple tuple = (ITuple) field; IConstructor fieldType = (IConstructor) tuple.get(0); todo.add(fieldType); args[i++] = toType(fieldType); args[i++] = ((IString) tuple.get(1)).getValue(); } tf.constructor(store, adt, name, args); } } private IConstructor getElement(IConstructor next) { return (IConstructor) next.get("element"); } private String getName(final IConstructor next) { return ((IString) next.get("name")).getValue(); } private IConstructor getValue(IConstructor next) { return (IConstructor) next.get("key"); } private IConstructor getAliased(IConstructor next) { return (IConstructor) next.get("aliased"); } private IConstructor getKey(IConstructor next) { return (IConstructor) next.get("value"); } private IList getConstructors(IConstructor next) { return (IList) next.get("constructors"); } }); } return toType(typeValue); }
diff --git a/src/com/ioabsoftware/gameraven/views/MessageView.java b/src/com/ioabsoftware/gameraven/views/MessageView.java index bbec488..3f37832 100644 --- a/src/com/ioabsoftware/gameraven/views/MessageView.java +++ b/src/com/ioabsoftware/gameraven/views/MessageView.java @@ -1,399 +1,400 @@ package com.ioabsoftware.gameraven.views; import java.util.HashMap; import net.margaritov.preference.colorpicker.ColorPickerPreference; import org.apache.commons.lang3.StringEscapeUtils; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Parcel; import android.text.Layout; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.style.BackgroundColorSpan; import android.text.style.CharacterStyle; import android.text.style.ClickableSpan; import android.text.style.QuoteSpan; import android.text.style.StyleSpan; import android.text.style.TypefaceSpan; import android.text.style.UnderlineSpan; import android.util.StateSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.ioabsoftware.gameraven.AllInOneV2; import com.ioabsoftware.gameraven.R; import com.ioabsoftware.gameraven.networking.HandlesNetworkResult.NetDesc; import com.ioabsoftware.gameraven.networking.Session; public class MessageView extends LinearLayout implements View.OnClickListener { private String userContent, messageID, boardID, topicID; private Element messageContent, messageContentNoPoll; private AllInOneV2 aio; private static int quoteBackColor = Color.argb(255, 100, 100, 100); public String getUser() { return userContent; } public String getMessageID() { return messageID; } public String getTopicID() { return topicID; } public String getBoardID() { return boardID; } public String getMessageDetailLink() { return Session.ROOT + "/boards/" + boardID + "/" + topicID + "/" + messageID; } public String getUserDetailLink() { return Session.ROOT + "/users/" + userContent.replace(' ', '+') + "/boards"; } public MessageView(final AllInOneV2 aioIn, String userIn, String userTitles, String postNum, String postTimeIn, Element messageIn, String BID, String TID, String MID, int hlColor) { super(aioIn); aioIn.wtl("starting mv creation"); aio = aioIn; userContent = userIn; messageContent = messageIn; messageID = MID; topicID = TID; boardID = BID; aio.wtl("stored vals"); LayoutInflater inflater = (LayoutInflater) aio.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.msgview, this); aio.wtl("inflated layout"); ((TextView) findViewById(R.id.mvUser)).setText(userContent + userTitles); ((TextView) findViewById(R.id.mvUser)).setTextColor(AllInOneV2.getAccentTextColor()); ((TextView) findViewById(R.id.mvPostNumber)).setText("#" + postNum + ", " + postTimeIn); ((TextView) findViewById(R.id.mvPostNumber)).setTextColor(AllInOneV2.getAccentTextColor()); aio.wtl("set text and color for user and post number"); String html = null; if (messageContent.getElementsByClass("board_poll").isEmpty()) { aio.wtl("no poll"); messageContentNoPoll = messageContent.clone(); html = messageContentNoPoll.html(); } else { aio.wtl("there is a poll"); messageContentNoPoll = messageContent.clone(); messageContentNoPoll.getElementsByClass("board_poll").first().remove(); html = messageContentNoPoll.html(); LinearLayout pollWrapper = (LinearLayout) findViewById(R.id.mvPollWrapper); LinearLayout innerPollWrapper = new LinearLayout(aio); ShapeDrawable s = new ShapeDrawable(); Paint p = s.getPaint(); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(10); p.setColor(Color.parseColor(ColorPickerPreference.convertToARGB(AllInOneV2.getAccentColor()))); pollWrapper.setBackgroundDrawable(s); pollWrapper.addView(new HeaderView(aio, messageContent.getElementsByClass("poll_head").first().text())); pollWrapper.addView(innerPollWrapper); innerPollWrapper.setPadding(15, 0, 15, 15); innerPollWrapper.setOrientation(VERTICAL); if (messageContent.getElementsByTag("form").isEmpty()) { // poll_foot_left TextView t; for (Element e : messageContent.getElementsByClass("table_row")) { Elements c = e.children(); t = new TextView(aio); t.setText(c.get(0).text() + ": " + c.get(1).text() + ", " + c.get(3).text() + " votes"); innerPollWrapper.addView(t); } String foot = messageContent.getElementsByClass("poll_foot_left").text(); if (foot.length() > 0) { t = new TextView(aio); t.setText(foot); innerPollWrapper.addView(t); } } else { final String action = "/boards/" + boardID + "/" + topicID; String key = messageContent.getElementsByAttributeValue("name", "key").attr("value"); int x = 0; for (Element e : messageContent.getElementsByAttributeValue("name", "poll_vote")) { x++; Button b = new Button(aio); b.setText(e.nextElementSibling().text()); final HashMap<String, String> data = new HashMap<String, String>(); data.put("key", key); data.put("poll_vote", Integer.toString(x)); data.put("submit", "Vote"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { aio.getSession().post(NetDesc.TOPIC, action, data); } }); innerPollWrapper.addView(b); } Button b = new Button(aio); b.setText("View Results"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { aio.getSession().get(NetDesc.TOPIC, action + "?results=1", null); } }); innerPollWrapper.addView(b); innerPollWrapper.setVisibility(View.VISIBLE); } } aio.wtl("html var set"); final TextView message = (TextView) findViewById(R.id.mvMessage); // URLImageParser p = new URLImageParser(message, aio); // Spanned htmlSpan = Html.fromHtml(html, p, null); // message.setText(htmlSpan); // message.setText(Html.fromHtml(html, null, null)); SpannableStringBuilder ssb = new SpannableStringBuilder(processContent(false)); addSpan(ssb, "<b>", "</b>", new StyleSpan(Typeface.BOLD)); addSpan(ssb, "<i>", "</i>", new StyleSpan(Typeface.ITALIC)); addSpan(ssb, "<code>", "</code>", new TypefaceSpan("monospace")); addSpan(ssb, "<cite>", "</cite>", new UnderlineSpan(), new StyleSpan(Typeface.ITALIC)); // quotes don't use CharacterStyles, so do it manually while (ssb.toString().contains("<blockquote>")) { int start = ssb.toString().indexOf("<blockquote>"); ssb.replace(start, start + "<blockquote>".length(), "\n"); start++; int stackCount = 1; int closer; int opener; int innerStartPoint = start; do { - opener = ssb.toString().indexOf("<blockquote>", innerStartPoint + "<blockquote>".length()); - closer = ssb.toString().indexOf("</blockquote>", innerStartPoint + "<blockquote>".length()); + opener = ssb.toString().indexOf("<blockquote>", innerStartPoint + 1); + closer = ssb.toString().indexOf("</blockquote>", innerStartPoint + 1); if (opener != -1 && opener < closer) { // found a nested quote stackCount++; innerStartPoint = opener; } else { // this closer is the right one stackCount--; innerStartPoint = closer; } } while (stackCount > 0); ssb.replace(closer, closer + "</blockquote>".length(), "\n"); aio.wtl("quote being added to post " + postNum + ": " + ssb.subSequence(start, closer)); ssb.setSpan(new GRQuoteSpan(), start, closer, 0); } final int defTextColor = message.getTextColors().getDefaultColor(); final int color; if (AllInOneV2.getUsingLightTheme()) color = Color.WHITE; else color = Color.BLACK; // do spoiler tags manually instead of in the method, as the clickablespan needs // to know the start and end points while (ssb.toString().contains("<spoiler>")) { final int start = ssb.toString().indexOf("<spoiler>"); ssb.delete(start, start + 9); final int end = ssb.toString().indexOf("</spoiler>", start); ssb.delete(end, end + 10); ssb.setSpan(new BackgroundColorSpan(defTextColor), start, end, 0); ssb.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { ((Spannable) message.getText()).setSpan(new BackgroundColorSpan(color), start, end, 0); } @Override public void updateDrawState(TextPaint ds) { ds.setColor(defTextColor); ds.setUnderlineText(false); } }, start, end, 0); } + ssb.append('\n'); message.setText(ssb); message.setLinkTextColor(AllInOneV2.getAccentColor()); aio.wtl("set message text, color"); findViewById(R.id.mvTopWrapper).setOnClickListener(this); if (hlColor == 0) findViewById(R.id.mvTopWrapper).setBackgroundDrawable(AllInOneV2.getMsgHeadSelector().getConstantState().newDrawable()); else { float[] hsv = new float[3]; Color.colorToHSV(hlColor, hsv); if (AllInOneV2.getSettingsPref().getBoolean("useWhiteAccentText", false)) { // color is probably dark if (hsv[2] > 0) hsv[2] *= 1.2f; else hsv[2] = 0.2f; } else { // color is probably bright hsv[2] *= 0.8f; } int msgSelectorColor = Color.HSVToColor(hsv); StateListDrawable hlSelector = new StateListDrawable(); hlSelector.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(msgSelectorColor)); hlSelector.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(msgSelectorColor)); hlSelector.addState(StateSet.WILD_CARD, new ColorDrawable(hlColor)); findViewById(R.id.mvTopWrapper).setBackgroundDrawable(hlSelector.getConstantState().newDrawable()); } aio.wtl("set click listener and drawable for top wrapper"); if (AllInOneV2.isAccentLight()) ((ImageView) findViewById(R.id.mvMessageMenuIcon)).setImageResource(R.drawable.ic_info_light); aio.wtl("finishing mv creation"); } private void addSpan(SpannableStringBuilder ssb, String tag, String endTag, CharacterStyle... cs) { while (ssb.toString().contains(tag)) { int start = ssb.toString().indexOf(tag); ssb.delete(start, start + tag.length()); int end = ssb.toString().indexOf(endTag, start); ssb.delete(end, end + endTag.length()); for (CharacterStyle c : cs) ssb.setSpan(CharacterStyle.wrap(c), start, end, 0); } } @Override public void onClick(View v) { aio.messageMenuClicked(MessageView.this); } public String getMessageForQuoting() { return processContent(true); } public String getMessageForEditing() { return processContent(false); } private String processContent(boolean removeSig) { String finalBody = messageContentNoPoll.getElementsByClass("msg_body").first().html(); finalBody = finalBody.replace("<span class=\"fspoiler\">", "<spoiler>").replace("</span>", "</spoiler>"); while (finalBody.contains("<a href")) { int start = finalBody.indexOf("<a href"); int end = finalBody.indexOf(">", start) + 1; finalBody = finalBody.replace(finalBody.substring(start, end), ""); } finalBody = finalBody.replace("</a>", ""); if (finalBody.endsWith("<br />")) finalBody = finalBody.substring(0, finalBody.length() - 6); finalBody = finalBody.replace("\n", ""); finalBody = finalBody.replace("<br />", "\n"); if (removeSig) { int sigStart = finalBody.lastIndexOf("\n---\n"); if (sigStart != -1) finalBody = finalBody.substring(0, sigStart); } finalBody = StringEscapeUtils.unescapeHtml4(finalBody); return finalBody; } private class GRQuoteSpan extends QuoteSpan { private static final int WIDTH = 4; private static final int GAP = 4; private final int COLOR = AllInOneV2.getAccentColor(); public void writeToParcel(Parcel dest, int flags) { dest.writeInt(COLOR); } public int getColor() { return COLOR; } public int getLeadingMargin(boolean first) { return WIDTH + GAP; } @Override public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { Paint.Style style = p.getStyle(); int color = p.getColor(); p.setStyle(Paint.Style.FILL); p.setColor(COLOR); c.drawRect(x, top, x + dir * WIDTH, bottom, p); p.setStyle(style); p.setColor(color); } } }
false
true
public MessageView(final AllInOneV2 aioIn, String userIn, String userTitles, String postNum, String postTimeIn, Element messageIn, String BID, String TID, String MID, int hlColor) { super(aioIn); aioIn.wtl("starting mv creation"); aio = aioIn; userContent = userIn; messageContent = messageIn; messageID = MID; topicID = TID; boardID = BID; aio.wtl("stored vals"); LayoutInflater inflater = (LayoutInflater) aio.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.msgview, this); aio.wtl("inflated layout"); ((TextView) findViewById(R.id.mvUser)).setText(userContent + userTitles); ((TextView) findViewById(R.id.mvUser)).setTextColor(AllInOneV2.getAccentTextColor()); ((TextView) findViewById(R.id.mvPostNumber)).setText("#" + postNum + ", " + postTimeIn); ((TextView) findViewById(R.id.mvPostNumber)).setTextColor(AllInOneV2.getAccentTextColor()); aio.wtl("set text and color for user and post number"); String html = null; if (messageContent.getElementsByClass("board_poll").isEmpty()) { aio.wtl("no poll"); messageContentNoPoll = messageContent.clone(); html = messageContentNoPoll.html(); } else { aio.wtl("there is a poll"); messageContentNoPoll = messageContent.clone(); messageContentNoPoll.getElementsByClass("board_poll").first().remove(); html = messageContentNoPoll.html(); LinearLayout pollWrapper = (LinearLayout) findViewById(R.id.mvPollWrapper); LinearLayout innerPollWrapper = new LinearLayout(aio); ShapeDrawable s = new ShapeDrawable(); Paint p = s.getPaint(); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(10); p.setColor(Color.parseColor(ColorPickerPreference.convertToARGB(AllInOneV2.getAccentColor()))); pollWrapper.setBackgroundDrawable(s); pollWrapper.addView(new HeaderView(aio, messageContent.getElementsByClass("poll_head").first().text())); pollWrapper.addView(innerPollWrapper); innerPollWrapper.setPadding(15, 0, 15, 15); innerPollWrapper.setOrientation(VERTICAL); if (messageContent.getElementsByTag("form").isEmpty()) { // poll_foot_left TextView t; for (Element e : messageContent.getElementsByClass("table_row")) { Elements c = e.children(); t = new TextView(aio); t.setText(c.get(0).text() + ": " + c.get(1).text() + ", " + c.get(3).text() + " votes"); innerPollWrapper.addView(t); } String foot = messageContent.getElementsByClass("poll_foot_left").text(); if (foot.length() > 0) { t = new TextView(aio); t.setText(foot); innerPollWrapper.addView(t); } } else { final String action = "/boards/" + boardID + "/" + topicID; String key = messageContent.getElementsByAttributeValue("name", "key").attr("value"); int x = 0; for (Element e : messageContent.getElementsByAttributeValue("name", "poll_vote")) { x++; Button b = new Button(aio); b.setText(e.nextElementSibling().text()); final HashMap<String, String> data = new HashMap<String, String>(); data.put("key", key); data.put("poll_vote", Integer.toString(x)); data.put("submit", "Vote"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { aio.getSession().post(NetDesc.TOPIC, action, data); } }); innerPollWrapper.addView(b); } Button b = new Button(aio); b.setText("View Results"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { aio.getSession().get(NetDesc.TOPIC, action + "?results=1", null); } }); innerPollWrapper.addView(b); innerPollWrapper.setVisibility(View.VISIBLE); } } aio.wtl("html var set"); final TextView message = (TextView) findViewById(R.id.mvMessage); // URLImageParser p = new URLImageParser(message, aio); // Spanned htmlSpan = Html.fromHtml(html, p, null); // message.setText(htmlSpan); // message.setText(Html.fromHtml(html, null, null)); SpannableStringBuilder ssb = new SpannableStringBuilder(processContent(false)); addSpan(ssb, "<b>", "</b>", new StyleSpan(Typeface.BOLD)); addSpan(ssb, "<i>", "</i>", new StyleSpan(Typeface.ITALIC)); addSpan(ssb, "<code>", "</code>", new TypefaceSpan("monospace")); addSpan(ssb, "<cite>", "</cite>", new UnderlineSpan(), new StyleSpan(Typeface.ITALIC)); // quotes don't use CharacterStyles, so do it manually while (ssb.toString().contains("<blockquote>")) { int start = ssb.toString().indexOf("<blockquote>"); ssb.replace(start, start + "<blockquote>".length(), "\n"); start++; int stackCount = 1; int closer; int opener; int innerStartPoint = start; do { opener = ssb.toString().indexOf("<blockquote>", innerStartPoint + "<blockquote>".length()); closer = ssb.toString().indexOf("</blockquote>", innerStartPoint + "<blockquote>".length()); if (opener != -1 && opener < closer) { // found a nested quote stackCount++; innerStartPoint = opener; } else { // this closer is the right one stackCount--; innerStartPoint = closer; } } while (stackCount > 0); ssb.replace(closer, closer + "</blockquote>".length(), "\n"); aio.wtl("quote being added to post " + postNum + ": " + ssb.subSequence(start, closer)); ssb.setSpan(new GRQuoteSpan(), start, closer, 0); } final int defTextColor = message.getTextColors().getDefaultColor(); final int color; if (AllInOneV2.getUsingLightTheme()) color = Color.WHITE; else color = Color.BLACK; // do spoiler tags manually instead of in the method, as the clickablespan needs // to know the start and end points while (ssb.toString().contains("<spoiler>")) { final int start = ssb.toString().indexOf("<spoiler>"); ssb.delete(start, start + 9); final int end = ssb.toString().indexOf("</spoiler>", start); ssb.delete(end, end + 10); ssb.setSpan(new BackgroundColorSpan(defTextColor), start, end, 0); ssb.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { ((Spannable) message.getText()).setSpan(new BackgroundColorSpan(color), start, end, 0); } @Override public void updateDrawState(TextPaint ds) { ds.setColor(defTextColor); ds.setUnderlineText(false); } }, start, end, 0); } message.setText(ssb); message.setLinkTextColor(AllInOneV2.getAccentColor()); aio.wtl("set message text, color"); findViewById(R.id.mvTopWrapper).setOnClickListener(this); if (hlColor == 0) findViewById(R.id.mvTopWrapper).setBackgroundDrawable(AllInOneV2.getMsgHeadSelector().getConstantState().newDrawable()); else { float[] hsv = new float[3]; Color.colorToHSV(hlColor, hsv); if (AllInOneV2.getSettingsPref().getBoolean("useWhiteAccentText", false)) { // color is probably dark if (hsv[2] > 0) hsv[2] *= 1.2f; else hsv[2] = 0.2f; } else { // color is probably bright hsv[2] *= 0.8f; } int msgSelectorColor = Color.HSVToColor(hsv); StateListDrawable hlSelector = new StateListDrawable(); hlSelector.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(msgSelectorColor)); hlSelector.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(msgSelectorColor)); hlSelector.addState(StateSet.WILD_CARD, new ColorDrawable(hlColor)); findViewById(R.id.mvTopWrapper).setBackgroundDrawable(hlSelector.getConstantState().newDrawable()); } aio.wtl("set click listener and drawable for top wrapper"); if (AllInOneV2.isAccentLight()) ((ImageView) findViewById(R.id.mvMessageMenuIcon)).setImageResource(R.drawable.ic_info_light); aio.wtl("finishing mv creation"); }
public MessageView(final AllInOneV2 aioIn, String userIn, String userTitles, String postNum, String postTimeIn, Element messageIn, String BID, String TID, String MID, int hlColor) { super(aioIn); aioIn.wtl("starting mv creation"); aio = aioIn; userContent = userIn; messageContent = messageIn; messageID = MID; topicID = TID; boardID = BID; aio.wtl("stored vals"); LayoutInflater inflater = (LayoutInflater) aio.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.msgview, this); aio.wtl("inflated layout"); ((TextView) findViewById(R.id.mvUser)).setText(userContent + userTitles); ((TextView) findViewById(R.id.mvUser)).setTextColor(AllInOneV2.getAccentTextColor()); ((TextView) findViewById(R.id.mvPostNumber)).setText("#" + postNum + ", " + postTimeIn); ((TextView) findViewById(R.id.mvPostNumber)).setTextColor(AllInOneV2.getAccentTextColor()); aio.wtl("set text and color for user and post number"); String html = null; if (messageContent.getElementsByClass("board_poll").isEmpty()) { aio.wtl("no poll"); messageContentNoPoll = messageContent.clone(); html = messageContentNoPoll.html(); } else { aio.wtl("there is a poll"); messageContentNoPoll = messageContent.clone(); messageContentNoPoll.getElementsByClass("board_poll").first().remove(); html = messageContentNoPoll.html(); LinearLayout pollWrapper = (LinearLayout) findViewById(R.id.mvPollWrapper); LinearLayout innerPollWrapper = new LinearLayout(aio); ShapeDrawable s = new ShapeDrawable(); Paint p = s.getPaint(); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(10); p.setColor(Color.parseColor(ColorPickerPreference.convertToARGB(AllInOneV2.getAccentColor()))); pollWrapper.setBackgroundDrawable(s); pollWrapper.addView(new HeaderView(aio, messageContent.getElementsByClass("poll_head").first().text())); pollWrapper.addView(innerPollWrapper); innerPollWrapper.setPadding(15, 0, 15, 15); innerPollWrapper.setOrientation(VERTICAL); if (messageContent.getElementsByTag("form").isEmpty()) { // poll_foot_left TextView t; for (Element e : messageContent.getElementsByClass("table_row")) { Elements c = e.children(); t = new TextView(aio); t.setText(c.get(0).text() + ": " + c.get(1).text() + ", " + c.get(3).text() + " votes"); innerPollWrapper.addView(t); } String foot = messageContent.getElementsByClass("poll_foot_left").text(); if (foot.length() > 0) { t = new TextView(aio); t.setText(foot); innerPollWrapper.addView(t); } } else { final String action = "/boards/" + boardID + "/" + topicID; String key = messageContent.getElementsByAttributeValue("name", "key").attr("value"); int x = 0; for (Element e : messageContent.getElementsByAttributeValue("name", "poll_vote")) { x++; Button b = new Button(aio); b.setText(e.nextElementSibling().text()); final HashMap<String, String> data = new HashMap<String, String>(); data.put("key", key); data.put("poll_vote", Integer.toString(x)); data.put("submit", "Vote"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { aio.getSession().post(NetDesc.TOPIC, action, data); } }); innerPollWrapper.addView(b); } Button b = new Button(aio); b.setText("View Results"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { aio.getSession().get(NetDesc.TOPIC, action + "?results=1", null); } }); innerPollWrapper.addView(b); innerPollWrapper.setVisibility(View.VISIBLE); } } aio.wtl("html var set"); final TextView message = (TextView) findViewById(R.id.mvMessage); // URLImageParser p = new URLImageParser(message, aio); // Spanned htmlSpan = Html.fromHtml(html, p, null); // message.setText(htmlSpan); // message.setText(Html.fromHtml(html, null, null)); SpannableStringBuilder ssb = new SpannableStringBuilder(processContent(false)); addSpan(ssb, "<b>", "</b>", new StyleSpan(Typeface.BOLD)); addSpan(ssb, "<i>", "</i>", new StyleSpan(Typeface.ITALIC)); addSpan(ssb, "<code>", "</code>", new TypefaceSpan("monospace")); addSpan(ssb, "<cite>", "</cite>", new UnderlineSpan(), new StyleSpan(Typeface.ITALIC)); // quotes don't use CharacterStyles, so do it manually while (ssb.toString().contains("<blockquote>")) { int start = ssb.toString().indexOf("<blockquote>"); ssb.replace(start, start + "<blockquote>".length(), "\n"); start++; int stackCount = 1; int closer; int opener; int innerStartPoint = start; do { opener = ssb.toString().indexOf("<blockquote>", innerStartPoint + 1); closer = ssb.toString().indexOf("</blockquote>", innerStartPoint + 1); if (opener != -1 && opener < closer) { // found a nested quote stackCount++; innerStartPoint = opener; } else { // this closer is the right one stackCount--; innerStartPoint = closer; } } while (stackCount > 0); ssb.replace(closer, closer + "</blockquote>".length(), "\n"); aio.wtl("quote being added to post " + postNum + ": " + ssb.subSequence(start, closer)); ssb.setSpan(new GRQuoteSpan(), start, closer, 0); } final int defTextColor = message.getTextColors().getDefaultColor(); final int color; if (AllInOneV2.getUsingLightTheme()) color = Color.WHITE; else color = Color.BLACK; // do spoiler tags manually instead of in the method, as the clickablespan needs // to know the start and end points while (ssb.toString().contains("<spoiler>")) { final int start = ssb.toString().indexOf("<spoiler>"); ssb.delete(start, start + 9); final int end = ssb.toString().indexOf("</spoiler>", start); ssb.delete(end, end + 10); ssb.setSpan(new BackgroundColorSpan(defTextColor), start, end, 0); ssb.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { ((Spannable) message.getText()).setSpan(new BackgroundColorSpan(color), start, end, 0); } @Override public void updateDrawState(TextPaint ds) { ds.setColor(defTextColor); ds.setUnderlineText(false); } }, start, end, 0); } ssb.append('\n'); message.setText(ssb); message.setLinkTextColor(AllInOneV2.getAccentColor()); aio.wtl("set message text, color"); findViewById(R.id.mvTopWrapper).setOnClickListener(this); if (hlColor == 0) findViewById(R.id.mvTopWrapper).setBackgroundDrawable(AllInOneV2.getMsgHeadSelector().getConstantState().newDrawable()); else { float[] hsv = new float[3]; Color.colorToHSV(hlColor, hsv); if (AllInOneV2.getSettingsPref().getBoolean("useWhiteAccentText", false)) { // color is probably dark if (hsv[2] > 0) hsv[2] *= 1.2f; else hsv[2] = 0.2f; } else { // color is probably bright hsv[2] *= 0.8f; } int msgSelectorColor = Color.HSVToColor(hsv); StateListDrawable hlSelector = new StateListDrawable(); hlSelector.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(msgSelectorColor)); hlSelector.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(msgSelectorColor)); hlSelector.addState(StateSet.WILD_CARD, new ColorDrawable(hlColor)); findViewById(R.id.mvTopWrapper).setBackgroundDrawable(hlSelector.getConstantState().newDrawable()); } aio.wtl("set click listener and drawable for top wrapper"); if (AllInOneV2.isAccentLight()) ((ImageView) findViewById(R.id.mvMessageMenuIcon)).setImageResource(R.drawable.ic_info_light); aio.wtl("finishing mv creation"); }
diff --git a/src/main/java/com/onarandombox/multiverseinventories/group/SimpleWorldGroup.java b/src/main/java/com/onarandombox/multiverseinventories/group/SimpleWorldGroup.java index 4f82402..3a78f77 100644 --- a/src/main/java/com/onarandombox/multiverseinventories/group/SimpleWorldGroup.java +++ b/src/main/java/com/onarandombox/multiverseinventories/group/SimpleWorldGroup.java @@ -1,173 +1,172 @@ package com.onarandombox.multiverseinventories.group; import com.google.common.collect.Lists; import com.onarandombox.multiverseinventories.MultiverseInventories; import com.onarandombox.multiverseinventories.profile.ProfileType; import com.onarandombox.multiverseinventories.profile.WeakProfileContainer; import com.onarandombox.multiverseinventories.share.Shares; import com.onarandombox.multiverseinventories.share.SimpleShares; import com.onarandombox.multiverseinventories.util.DeserializationException; import com.onarandombox.multiverseinventories.util.MVILog; import org.bukkit.Bukkit; import org.bukkit.World; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Implementation of WorldGroup. */ public class SimpleWorldGroup extends WeakProfileContainer implements WorldGroup { private String name = ""; private HashSet<String> worlds = new HashSet<String>(); private Shares shares = new SimpleShares(); //private HashMap<String, ItemBlacklist> itemBlacklist = new HashMap<String, ItemBlacklist>(); public SimpleWorldGroup(MultiverseInventories plugin, String name) { super(plugin, ProfileType.GROUP); this.name = name; } public SimpleWorldGroup(MultiverseInventories plugin, String name, Map<String, Object> dataMap) throws DeserializationException { this(plugin, name); if (!dataMap.containsKey("worlds")) { throw new DeserializationException("No worlds specified for world group: " + name); } Object worldListObj = dataMap.get("worlds"); if (!(worldListObj instanceof List)) { throw new DeserializationException("World list formatted incorrectly for world group: " + name); } for (Object worldNameObj : (List) worldListObj) { + this.addWorld(worldNameObj.toString()); World world = Bukkit.getWorld(worldNameObj.toString()); - if (world != null) { - this.addWorld(world); - } else { - MVILog.warning(""); + if (world == null) { + MVILog.debug("World: " + worldNameObj.toString() + " is not loaded."); } } if (dataMap.containsKey("shares")) { Object sharesListObj = dataMap.get("shares"); if (sharesListObj instanceof List) { this.setShares(new SimpleShares((List) sharesListObj)); } else { MVILog.warning("Shares formatted incorrectly for group: " + name); } } /* if (data.contains("blacklist")) { } */ } /** * {@inheritDoc} */ @Override public Map<String, Object> serialize() { Map<String, Object> results = new LinkedHashMap<String, Object>(); results.put("worlds", Lists.newArrayList(this.getWorlds())); List<String> sharesList = this.getShares().toStringList(); if (!sharesList.isEmpty()) { results.put("shares", sharesList); } /* if (!this.getItemBlacklist().isEmpty()) { } */ return results; } /** * {@inheritDoc} */ @Override public String getName() { return this.name; } /** * {@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** * {@inheritDoc} */ @Override public void addWorld(String worldName) { this.getWorlds().add(worldName); this.getPlugin().getSettings().updateWorldGroup(this); } /** * {@inheritDoc} */ @Override public void addWorld(World world) { this.addWorld(world.getName()); } /** * {@inheritDoc} */ @Override public HashSet<String> getWorlds() { return this.worlds; } /** * {@inheritDoc} */ @Override public void setShares(Shares shares) { this.shares = shares; this.getPlugin().getSettings().updateWorldGroup(this); } /** * {@inheritDoc} */ @Override public Shares getShares() { return this.shares; } /** * {@inheritDoc} */ @Override public boolean containsWorld(String worldName) { return this.getWorlds().contains(worldName); } /** * {@inheritDoc} */ @Override public String getDataName() { return this.getName(); } /* protected HashMap<String, ItemBlacklist> getItemBlacklist() { return this.itemBlacklist; } */ /* @Override public ItemBlacklist getItemBlacklist(String worldName) { return null; } */ }
false
true
public SimpleWorldGroup(MultiverseInventories plugin, String name, Map<String, Object> dataMap) throws DeserializationException { this(plugin, name); if (!dataMap.containsKey("worlds")) { throw new DeserializationException("No worlds specified for world group: " + name); } Object worldListObj = dataMap.get("worlds"); if (!(worldListObj instanceof List)) { throw new DeserializationException("World list formatted incorrectly for world group: " + name); } for (Object worldNameObj : (List) worldListObj) { World world = Bukkit.getWorld(worldNameObj.toString()); if (world != null) { this.addWorld(world); } else { MVILog.warning(""); } } if (dataMap.containsKey("shares")) { Object sharesListObj = dataMap.get("shares"); if (sharesListObj instanceof List) { this.setShares(new SimpleShares((List) sharesListObj)); } else { MVILog.warning("Shares formatted incorrectly for group: " + name); } } /* if (data.contains("blacklist")) { } */ }
public SimpleWorldGroup(MultiverseInventories plugin, String name, Map<String, Object> dataMap) throws DeserializationException { this(plugin, name); if (!dataMap.containsKey("worlds")) { throw new DeserializationException("No worlds specified for world group: " + name); } Object worldListObj = dataMap.get("worlds"); if (!(worldListObj instanceof List)) { throw new DeserializationException("World list formatted incorrectly for world group: " + name); } for (Object worldNameObj : (List) worldListObj) { this.addWorld(worldNameObj.toString()); World world = Bukkit.getWorld(worldNameObj.toString()); if (world == null) { MVILog.debug("World: " + worldNameObj.toString() + " is not loaded."); } } if (dataMap.containsKey("shares")) { Object sharesListObj = dataMap.get("shares"); if (sharesListObj instanceof List) { this.setShares(new SimpleShares((List) sharesListObj)); } else { MVILog.warning("Shares formatted incorrectly for group: " + name); } } /* if (data.contains("blacklist")) { } */ }
diff --git a/src/common/me/nallar/tickprofiler/minecraft/commands/ProfileCommand.java b/src/common/me/nallar/tickprofiler/minecraft/commands/ProfileCommand.java index 8924665..c5f727e 100755 --- a/src/common/me/nallar/tickprofiler/minecraft/commands/ProfileCommand.java +++ b/src/common/me/nallar/tickprofiler/minecraft/commands/ProfileCommand.java @@ -1,88 +1,88 @@ package me.nallar.tickprofiler.minecraft.commands; import java.util.ArrayList; import java.util.Collections; import java.util.List; import me.nallar.tickprofiler.Log; import me.nallar.tickprofiler.minecraft.TickProfiler; import me.nallar.tickprofiler.minecraft.profiling.EntityTickProfiler; import me.nallar.tickprofiler.util.TableFormatter; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; public class ProfileCommand extends Command { public static String name = "profile"; @Override public String getCommandName() { return name; } @Override public boolean requireOp() { return TickProfiler.instance.requireOpForProfileCommand; } @Override public void processCommand(final ICommandSender commandSender, List<String> arguments) { World world = null; int time_ = 30; boolean location = false; Integer x = null; Integer z = null; try { if ("c".equals(arguments.get(0))) { location = true; if (arguments.size() > 2) { x = Integer.valueOf(arguments.remove(1)); z = Integer.valueOf(arguments.remove(1)); } } if (arguments.size() > 1) { time_ = Integer.valueOf(arguments.get(1)); } if (arguments.size() > 2) { world = DimensionManager.getWorld(Integer.valueOf(arguments.get(2))); - } else if (commandSender instanceof Entity) { + } else if (location && commandSender instanceof Entity) { world = ((Entity) commandSender).worldObj; } if (location && x == null) { Entity entity = (Entity) commandSender; x = entity.chunkCoordX; z = entity.chunkCoordZ; } } catch (Exception e) { sendChat(commandSender, "Usage: /profile [e/(c [chunk x] [chunk z])] [time=30] [dimensionid=all]"); return; } final List<World> worlds = new ArrayList<World>(); if (world == null) { Collections.addAll(worlds, DimensionManager.getWorlds()); } else { worlds.add(world); } final int time = time_; final EntityTickProfiler entityTickProfiler = EntityTickProfiler.ENTITY_TICK_PROFILER; if (!entityTickProfiler.startProfiling(new Runnable() { @Override public void run() { sendChat(commandSender, entityTickProfiler.writeData(new TableFormatter(commandSender)).toString()); } }, location ? ProfilingState.CHUNK : ProfilingState.GLOBAL, time, worlds)) { sendChat(commandSender, "Someone else is currently profiling."); } if (location) { entityTickProfiler.setLocation(x, z); } sendChat(commandSender, "Profiling for " + time + " seconds in " + (world == null ? "all worlds " : Log.name(world)) + (location ? " at " + x + ',' + z : "")); } public static enum ProfilingState { NONE, GLOBAL, CHUNK } }
true
true
public void processCommand(final ICommandSender commandSender, List<String> arguments) { World world = null; int time_ = 30; boolean location = false; Integer x = null; Integer z = null; try { if ("c".equals(arguments.get(0))) { location = true; if (arguments.size() > 2) { x = Integer.valueOf(arguments.remove(1)); z = Integer.valueOf(arguments.remove(1)); } } if (arguments.size() > 1) { time_ = Integer.valueOf(arguments.get(1)); } if (arguments.size() > 2) { world = DimensionManager.getWorld(Integer.valueOf(arguments.get(2))); } else if (commandSender instanceof Entity) { world = ((Entity) commandSender).worldObj; } if (location && x == null) { Entity entity = (Entity) commandSender; x = entity.chunkCoordX; z = entity.chunkCoordZ; } } catch (Exception e) { sendChat(commandSender, "Usage: /profile [e/(c [chunk x] [chunk z])] [time=30] [dimensionid=all]"); return; } final List<World> worlds = new ArrayList<World>(); if (world == null) { Collections.addAll(worlds, DimensionManager.getWorlds()); } else { worlds.add(world); } final int time = time_; final EntityTickProfiler entityTickProfiler = EntityTickProfiler.ENTITY_TICK_PROFILER; if (!entityTickProfiler.startProfiling(new Runnable() { @Override public void run() { sendChat(commandSender, entityTickProfiler.writeData(new TableFormatter(commandSender)).toString()); } }, location ? ProfilingState.CHUNK : ProfilingState.GLOBAL, time, worlds)) { sendChat(commandSender, "Someone else is currently profiling."); } if (location) { entityTickProfiler.setLocation(x, z); } sendChat(commandSender, "Profiling for " + time + " seconds in " + (world == null ? "all worlds " : Log.name(world)) + (location ? " at " + x + ',' + z : "")); }
public void processCommand(final ICommandSender commandSender, List<String> arguments) { World world = null; int time_ = 30; boolean location = false; Integer x = null; Integer z = null; try { if ("c".equals(arguments.get(0))) { location = true; if (arguments.size() > 2) { x = Integer.valueOf(arguments.remove(1)); z = Integer.valueOf(arguments.remove(1)); } } if (arguments.size() > 1) { time_ = Integer.valueOf(arguments.get(1)); } if (arguments.size() > 2) { world = DimensionManager.getWorld(Integer.valueOf(arguments.get(2))); } else if (location && commandSender instanceof Entity) { world = ((Entity) commandSender).worldObj; } if (location && x == null) { Entity entity = (Entity) commandSender; x = entity.chunkCoordX; z = entity.chunkCoordZ; } } catch (Exception e) { sendChat(commandSender, "Usage: /profile [e/(c [chunk x] [chunk z])] [time=30] [dimensionid=all]"); return; } final List<World> worlds = new ArrayList<World>(); if (world == null) { Collections.addAll(worlds, DimensionManager.getWorlds()); } else { worlds.add(world); } final int time = time_; final EntityTickProfiler entityTickProfiler = EntityTickProfiler.ENTITY_TICK_PROFILER; if (!entityTickProfiler.startProfiling(new Runnable() { @Override public void run() { sendChat(commandSender, entityTickProfiler.writeData(new TableFormatter(commandSender)).toString()); } }, location ? ProfilingState.CHUNK : ProfilingState.GLOBAL, time, worlds)) { sendChat(commandSender, "Someone else is currently profiling."); } if (location) { entityTickProfiler.setLocation(x, z); } sendChat(commandSender, "Profiling for " + time + " seconds in " + (world == null ? "all worlds " : Log.name(world)) + (location ? " at " + x + ',' + z : "")); }
diff --git a/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java b/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java index 6ac31738d..5e47345e5 100644 --- a/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java +++ b/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java @@ -1,653 +1,653 @@ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved */ package com.sun.sgs.benchmark.client; import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.sun.sgs.benchmark.shared.CustomTaskType; /* * */ public class ScriptingCommand { /** Constants */ public static final String DELIMITER = "\t"; public static final String EMPTY_STR = ""; public static final int HELP_INDENT_LEN = 20; public static final String HELP_INDENT_STR; public static final String NEWLINE = System.getProperty("line.separator"); static { StringBuilder sb = new StringBuilder(); for (int i=0; i < HELP_INDENT_LEN; i++) sb.append(' '); HELP_INDENT_STR = sb.toString(); } /** Member variablees */ private ScriptingCommandType type; private int count = -1; private int port = -1; private long duration = -1; private long delay = 0; /** optional argument; must default to 0 */ private long period = -1; private int size = -1; private String channelName = null; private String className = null; private String hostname = null; private String objectName = null; private String tagName = null; private String topic = null; private String msg = null; private String printArg = null; private String login = null, password = null; private ScriptingEvent event = null; private CustomTaskType taskType = null; private List<String> recips = new LinkedList<String>(); /** Constructors */ /** use parse() to create instances */ private ScriptingCommand(ScriptingCommandType type) { this.type = type; } /** Public Methods */ public String getChannelNameArg() { return channelName; } public String getClassNameArg() { return className; } public int getCountArg() { return count; } public long getDelayArg() { return delay; } public long getDurationArg() { return duration; } public ScriptingEvent getEventArg() { return event; } public static String getHelpString() { StringBuilder sb = new StringBuilder(); sb.append(" --- Available Commands --- ").append(NEWLINE); for (ScriptingCommandType type : ScriptingCommandType.values()) { sb.append(getUsage(type)).append(NEWLINE); /** Just usage info */ } return sb.toString(); } public static String getHelpString(String cmdType) { if (cmdType.equalsIgnoreCase("events")) { return getEventsHelpString(); } else { ScriptingCommandType type = ScriptingCommandType.parse(cmdType); if (type == null) { return "Unknown help topic. Try 'help' or 'help events'."; } else { return getHelpString(type); } } } public static String getHelpString(ScriptingCommandType type) { StringBuilder sb = new StringBuilder(); String[] aliases = type.getAliases(); sb.append(getUsage(type)).append(NEWLINE); sb.append(HELP_INDENT_STR).append("Aliases: "); for (int i=0; i < aliases.length; i++) { if (i > 0) sb.append(", "); sb.append(aliases[i]); } return sb.toString(); } public String getHostnameArg() { return hostname; } public String getLoginArg() { return login; } public String getMessageArg() { return msg; } public String getObjectNameArg() { return objectName; } public String getPasswordArg() { return password; } public long getPeriodArg() { return period; } public int getPortArg() { return port; } public String getPrintArg() { return printArg; } public List<String> getRecipientArgs() { return Collections.unmodifiableList(recips); } public int getSizeArg() { return size; } public String getTagNameArg() { return tagName; } public CustomTaskType getTaskTypeArg() { return taskType; } public String getTopicArg() { return topic; } public ScriptingCommandType getType() { return type; } public static ScriptingCommand parse(String line) throws ParseException { String[] parts = line.trim().split("\\s+", 2); ScriptingCommandType type = ScriptingCommandType.parse(parts[0]); if (type == null) { throw new ParseException("Unrecognized command: " + parts[0], 0); } ScriptingCommand cmd = new ScriptingCommand(type); String[] args = (parts.length == 2) ? parts[1].split("\\s+") : new String[] { }; cmd.parseArgs(args); return cmd; } /** Private Methods */ private void parseArgs(String[] args) throws ParseException { switch (type) { case CONFIG: if (args.length <= 2) { if (args.length >= 1) { /** Optional argument */ hostname = args[0]; } if (args.length == 2) { /** Optional argument */ try { port = Integer.valueOf(args[1]); if (port <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a valid network port: " + args[1], 0); } } return; } break; case CPU: if (args.length == 1) { try { duration = Long.valueOf(args[0]); if (duration <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case CREATE_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } break; case DATASTORE_CREATE: if (args.length >= 2 && args.length <= 3) { objectName = args[0]; className = args[1]; boolean isArray; try { Class<?> clazz = Class.forName(className); isArray = clazz.isArray(); } catch (ClassNotFoundException e) { isArray = className.startsWith("["); /** guess */ } if (isArray) { /** Note: only single-dimension arrays are supported. */ if (args.length == 3) { try { size = Integer.valueOf(args[2]); if (size < 0) { size = -1; throw new NumberFormatException(); } return; } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, " + " must be a non-negative integer: " + args[2], 0); } } } else { /** Not an array type */ if (args.length == 2) return; } } break; case DATASTORE_READ: if (args.length == 1) { objectName = args[0]; return; } break; case DATASTORE_WRITE: if (args.length == 1) { objectName = args[0]; return; } break; case DISCONNECT: if (args.length == 0) return; /** No arguments */ break; case DO_TAG: if (args.length >= 1 && args.length <= 2) { tagName = args[0]; count = 1; /** default */ if (args.length == 2) { /** Optional argument */ try { count = Integer.valueOf(args[1]); if (count <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[1], 0); } } return; } break; case END_BLOCK: if (args.length == 0) return; /** No arguments */ break; case EXIT: if (args.length == 0) return; /** No arguments */ break; case HELP: if (args.length <= 1) { if (args.length == 1) { /** Optional argument */ topic = args[0]; } return; } break; case JOIN_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } return; case LEAVE_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } return; case LOGIN: if (args.length == 2) { login = args[0]; password = args[1]; return; } break; case LOGOUT: if (args.length == 0) return; /** No arguments */ break; case MALLOC: if (args.length == 1) { try { size = Integer.valueOf(args[0]); if (size <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case ON_EVENT: if (args.length >= 2 && args.length <= 3) { event = ScriptingEvent.parse(args[0]); if (event == null) { throw new ParseException("Invalid ScriptingEvent alias: " + args[0], 0); } tagName = args[1]; count = 1; /** default */ if (args.length == 3) { try { count = Integer.valueOf(args[2]); if (count <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[1], 0); } } return; } break; case PAUSE: if (args.length == 1) { try { duration = Long.valueOf(args[0]); if (duration <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case PRINT: /** Accept whole line as argument, including spaces */ if (args.length == 0) break; printArg = stripQuotes(strJoin(args)); return; case REQ_RESPONSE: if (args.length >= 1 && args.length <= 2) { String sizeArg; if (args.length == 2) { channelName = args[0]; sizeArg = args[1]; } else { sizeArg = args[0]; } try { size = Integer.valueOf(sizeArg); if (size < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, " + " must be a non-negative integer: " + args[0], 0); } return; } break; case SEND_CHANNEL: if (args.length >= 2) { channelName = args[0]; msg = stripQuotes(strJoin(args, 1)); return; } break; case SEND_DIRECT: /** Accept whole line as argument, including spaces */ if (args.length == 0) break; - printArg = stripQuotes(strJoin(args)); + msg = stripQuotes(strJoin(args)); return; case START_BLOCK: if (args.length == 0) return; /** No arguments */ break; case START_TASK: if (args.length >= 2 && args.length <= 4) { tagName = args[0]; try { taskType = Enum.valueOf(CustomTaskType.class, args[1].toUpperCase()); } catch (IllegalArgumentException e) { throw new ParseException("Invalid " + type + " argument, " + " not recognized: " + args[1] + ". Should be one of: " + Arrays.toString(CustomTaskType.values()), 0); } if (args.length >= 3) { try { delay = Long.valueOf(args[2]); if (delay < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, must be a non-negative integer: " + args[2], 0); } } if (args.length >= 4) { try { period = Long.valueOf(args[3]); if (period < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, must be a non-negative integer: " + args[3], 0); } } return; } break; case TAG: if (args.length == 1) { tagName = args[0]; return; } break; case WAIT_FOR: if (args.length == 1) { event = ScriptingEvent.parse(args[0]); if (event == null) { throw new ParseException("Invalid ScriptingEvent alias: " + args[0], 0); } return; } break; default: throw new IllegalStateException("ScriptingCommand.addProperty()" + " switch statement fell through without matching any cases. " + " this=" + this); } /** * If control reaches here, the argument list was invalid (wrong number * of arguments for this particular ScriptingCommand type. */ throw new ParseException("Wrong number of arguments to " + type + " command (" + args.length + "). try 'help " + type + "'.", 0); } private static String stripQuotes(String s) { s = s.trim().toLowerCase(); if ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'"))) { s = s.substring(1, s.length() - 1).trim(); } return s; } private static String getArgList(ScriptingCommandType type) { switch (type) { case CONFIG: return "[hostname [port]]"; case CPU: return "duration_ms"; case CREATE_CHANNEL: return "channel (may not contain spaces)"; case DATASTORE_CREATE: return "object-name class-name - or - " + "object-name array-class-name size"; case DATASTORE_READ: return "object-name"; case DATASTORE_WRITE: return "object-name"; case DISCONNECT: return ""; case DO_TAG: return "tagname [repeat-count]"; case END_BLOCK: return ""; case EXIT: return ""; case HELP: return ""; case JOIN_CHANNEL: return "channel (may not contain spaces)"; case LEAVE_CHANNEL: return "channel (may not contain spaces)"; case LOGIN: return "username password"; case LOGOUT: return ""; case MALLOC: return "size_bytes"; case ON_EVENT: return "event tagname [repeat-count]"; case PAUSE: return "duration_ms"; case PRINT: return "message (may contain spaces)"; case REQ_RESPONSE: return "[channel] size_bytes (channel name may not contain spaces)"; case SEND_CHANNEL: return "channel message (message may contain spaces, but not channel)"; case SEND_DIRECT: return "message (may contain spaces)"; case START_BLOCK: return ""; case START_TASK: return "tag task-type [delay_ms [period_ms]]"; case TAG: return "tagname"; case WAIT_FOR: return "event"; default: return "Error: unknown command-type: " + type; } } private static String getEventsHelpString() { StringBuilder sb = new StringBuilder(); sb.append(" --- Available Events (Triggers) --- ").append(NEWLINE); for (ScriptingEvent evt : ScriptingEvent.values()) { String[] aliases = evt.getAliases(); String desc = evt.toString(); sb.append(desc); for (int i=desc.length(); i < HELP_INDENT_LEN; i++) sb.append(" "); sb.append("Aliases: "); for (int i=0; i < aliases.length; i++) { if (i > 0) sb.append(", "); sb.append(aliases[i]); } sb.append(")").append(NEWLINE); } return sb.toString(); } private static String getUsage(ScriptingCommandType type) { StringBuilder sb = new StringBuilder(); sb.append(type); while (sb.length() < HELP_INDENT_LEN) sb.append(' '); sb.append("Usage: ").append(type.getAlias()).append(" "); /** Arguments */ sb.append(getArgList(type)); return sb.toString(); } private static String strJoin(String[] strs) { return strJoin(strs, 0, strs.length); } private static String strJoin(String[] strs, int offset) { return strJoin(strs, offset, strs.length); } private static String strJoin(String[] strs, int offset, int length) { StringBuilder sb = new StringBuilder(); for (int i=offset; i < length; i++) { sb.append(strs[i]); sb.append(" "); } return sb.toString(); } }
true
true
private void parseArgs(String[] args) throws ParseException { switch (type) { case CONFIG: if (args.length <= 2) { if (args.length >= 1) { /** Optional argument */ hostname = args[0]; } if (args.length == 2) { /** Optional argument */ try { port = Integer.valueOf(args[1]); if (port <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a valid network port: " + args[1], 0); } } return; } break; case CPU: if (args.length == 1) { try { duration = Long.valueOf(args[0]); if (duration <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case CREATE_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } break; case DATASTORE_CREATE: if (args.length >= 2 && args.length <= 3) { objectName = args[0]; className = args[1]; boolean isArray; try { Class<?> clazz = Class.forName(className); isArray = clazz.isArray(); } catch (ClassNotFoundException e) { isArray = className.startsWith("["); /** guess */ } if (isArray) { /** Note: only single-dimension arrays are supported. */ if (args.length == 3) { try { size = Integer.valueOf(args[2]); if (size < 0) { size = -1; throw new NumberFormatException(); } return; } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, " + " must be a non-negative integer: " + args[2], 0); } } } else { /** Not an array type */ if (args.length == 2) return; } } break; case DATASTORE_READ: if (args.length == 1) { objectName = args[0]; return; } break; case DATASTORE_WRITE: if (args.length == 1) { objectName = args[0]; return; } break; case DISCONNECT: if (args.length == 0) return; /** No arguments */ break; case DO_TAG: if (args.length >= 1 && args.length <= 2) { tagName = args[0]; count = 1; /** default */ if (args.length == 2) { /** Optional argument */ try { count = Integer.valueOf(args[1]); if (count <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[1], 0); } } return; } break; case END_BLOCK: if (args.length == 0) return; /** No arguments */ break; case EXIT: if (args.length == 0) return; /** No arguments */ break; case HELP: if (args.length <= 1) { if (args.length == 1) { /** Optional argument */ topic = args[0]; } return; } break; case JOIN_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } return; case LEAVE_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } return; case LOGIN: if (args.length == 2) { login = args[0]; password = args[1]; return; } break; case LOGOUT: if (args.length == 0) return; /** No arguments */ break; case MALLOC: if (args.length == 1) { try { size = Integer.valueOf(args[0]); if (size <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case ON_EVENT: if (args.length >= 2 && args.length <= 3) { event = ScriptingEvent.parse(args[0]); if (event == null) { throw new ParseException("Invalid ScriptingEvent alias: " + args[0], 0); } tagName = args[1]; count = 1; /** default */ if (args.length == 3) { try { count = Integer.valueOf(args[2]); if (count <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[1], 0); } } return; } break; case PAUSE: if (args.length == 1) { try { duration = Long.valueOf(args[0]); if (duration <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case PRINT: /** Accept whole line as argument, including spaces */ if (args.length == 0) break; printArg = stripQuotes(strJoin(args)); return; case REQ_RESPONSE: if (args.length >= 1 && args.length <= 2) { String sizeArg; if (args.length == 2) { channelName = args[0]; sizeArg = args[1]; } else { sizeArg = args[0]; } try { size = Integer.valueOf(sizeArg); if (size < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, " + " must be a non-negative integer: " + args[0], 0); } return; } break; case SEND_CHANNEL: if (args.length >= 2) { channelName = args[0]; msg = stripQuotes(strJoin(args, 1)); return; } break; case SEND_DIRECT: /** Accept whole line as argument, including spaces */ if (args.length == 0) break; printArg = stripQuotes(strJoin(args)); return; case START_BLOCK: if (args.length == 0) return; /** No arguments */ break; case START_TASK: if (args.length >= 2 && args.length <= 4) { tagName = args[0]; try { taskType = Enum.valueOf(CustomTaskType.class, args[1].toUpperCase()); } catch (IllegalArgumentException e) { throw new ParseException("Invalid " + type + " argument, " + " not recognized: " + args[1] + ". Should be one of: " + Arrays.toString(CustomTaskType.values()), 0); } if (args.length >= 3) { try { delay = Long.valueOf(args[2]); if (delay < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, must be a non-negative integer: " + args[2], 0); } } if (args.length >= 4) { try { period = Long.valueOf(args[3]); if (period < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, must be a non-negative integer: " + args[3], 0); } } return; } break; case TAG: if (args.length == 1) { tagName = args[0]; return; } break; case WAIT_FOR: if (args.length == 1) { event = ScriptingEvent.parse(args[0]); if (event == null) { throw new ParseException("Invalid ScriptingEvent alias: " + args[0], 0); } return; } break; default: throw new IllegalStateException("ScriptingCommand.addProperty()" + " switch statement fell through without matching any cases. " + " this=" + this); } /** * If control reaches here, the argument list was invalid (wrong number * of arguments for this particular ScriptingCommand type. */ throw new ParseException("Wrong number of arguments to " + type + " command (" + args.length + "). try 'help " + type + "'.", 0); }
private void parseArgs(String[] args) throws ParseException { switch (type) { case CONFIG: if (args.length <= 2) { if (args.length >= 1) { /** Optional argument */ hostname = args[0]; } if (args.length == 2) { /** Optional argument */ try { port = Integer.valueOf(args[1]); if (port <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a valid network port: " + args[1], 0); } } return; } break; case CPU: if (args.length == 1) { try { duration = Long.valueOf(args[0]); if (duration <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case CREATE_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } break; case DATASTORE_CREATE: if (args.length >= 2 && args.length <= 3) { objectName = args[0]; className = args[1]; boolean isArray; try { Class<?> clazz = Class.forName(className); isArray = clazz.isArray(); } catch (ClassNotFoundException e) { isArray = className.startsWith("["); /** guess */ } if (isArray) { /** Note: only single-dimension arrays are supported. */ if (args.length == 3) { try { size = Integer.valueOf(args[2]); if (size < 0) { size = -1; throw new NumberFormatException(); } return; } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, " + " must be a non-negative integer: " + args[2], 0); } } } else { /** Not an array type */ if (args.length == 2) return; } } break; case DATASTORE_READ: if (args.length == 1) { objectName = args[0]; return; } break; case DATASTORE_WRITE: if (args.length == 1) { objectName = args[0]; return; } break; case DISCONNECT: if (args.length == 0) return; /** No arguments */ break; case DO_TAG: if (args.length >= 1 && args.length <= 2) { tagName = args[0]; count = 1; /** default */ if (args.length == 2) { /** Optional argument */ try { count = Integer.valueOf(args[1]); if (count <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[1], 0); } } return; } break; case END_BLOCK: if (args.length == 0) return; /** No arguments */ break; case EXIT: if (args.length == 0) return; /** No arguments */ break; case HELP: if (args.length <= 1) { if (args.length == 1) { /** Optional argument */ topic = args[0]; } return; } break; case JOIN_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } return; case LEAVE_CHANNEL: if (args.length == 1) { channelName = args[0]; return; } return; case LOGIN: if (args.length == 2) { login = args[0]; password = args[1]; return; } break; case LOGOUT: if (args.length == 0) return; /** No arguments */ break; case MALLOC: if (args.length == 1) { try { size = Integer.valueOf(args[0]); if (size <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case ON_EVENT: if (args.length >= 2 && args.length <= 3) { event = ScriptingEvent.parse(args[0]); if (event == null) { throw new ParseException("Invalid ScriptingEvent alias: " + args[0], 0); } tagName = args[1]; count = 1; /** default */ if (args.length == 3) { try { count = Integer.valueOf(args[2]); if (count <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[1], 0); } } return; } break; case PAUSE: if (args.length == 1) { try { duration = Long.valueOf(args[0]); if (duration <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument," + " must be a positive integer: " + args[0], 0); } return; } break; case PRINT: /** Accept whole line as argument, including spaces */ if (args.length == 0) break; printArg = stripQuotes(strJoin(args)); return; case REQ_RESPONSE: if (args.length >= 1 && args.length <= 2) { String sizeArg; if (args.length == 2) { channelName = args[0]; sizeArg = args[1]; } else { sizeArg = args[0]; } try { size = Integer.valueOf(sizeArg); if (size < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, " + " must be a non-negative integer: " + args[0], 0); } return; } break; case SEND_CHANNEL: if (args.length >= 2) { channelName = args[0]; msg = stripQuotes(strJoin(args, 1)); return; } break; case SEND_DIRECT: /** Accept whole line as argument, including spaces */ if (args.length == 0) break; msg = stripQuotes(strJoin(args)); return; case START_BLOCK: if (args.length == 0) return; /** No arguments */ break; case START_TASK: if (args.length >= 2 && args.length <= 4) { tagName = args[0]; try { taskType = Enum.valueOf(CustomTaskType.class, args[1].toUpperCase()); } catch (IllegalArgumentException e) { throw new ParseException("Invalid " + type + " argument, " + " not recognized: " + args[1] + ". Should be one of: " + Arrays.toString(CustomTaskType.values()), 0); } if (args.length >= 3) { try { delay = Long.valueOf(args[2]); if (delay < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, must be a non-negative integer: " + args[2], 0); } } if (args.length >= 4) { try { period = Long.valueOf(args[3]); if (period < 0) throw new NumberFormatException(); } catch (NumberFormatException e) { throw new ParseException("Invalid " + type + " argument, must be a non-negative integer: " + args[3], 0); } } return; } break; case TAG: if (args.length == 1) { tagName = args[0]; return; } break; case WAIT_FOR: if (args.length == 1) { event = ScriptingEvent.parse(args[0]); if (event == null) { throw new ParseException("Invalid ScriptingEvent alias: " + args[0], 0); } return; } break; default: throw new IllegalStateException("ScriptingCommand.addProperty()" + " switch statement fell through without matching any cases. " + " this=" + this); } /** * If control reaches here, the argument list was invalid (wrong number * of arguments for this particular ScriptingCommand type. */ throw new ParseException("Wrong number of arguments to " + type + " command (" + args.length + "). try 'help " + type + "'.", 0); }
diff --git a/qcadoo-view/src/main/java/com/qcadoo/view/internal/controllers/FileResolverController.java b/qcadoo-view/src/main/java/com/qcadoo/view/internal/controllers/FileResolverController.java index 356909c3e..fde553167 100644 --- a/qcadoo-view/src/main/java/com/qcadoo/view/internal/controllers/FileResolverController.java +++ b/qcadoo-view/src/main/java/com/qcadoo/view/internal/controllers/FileResolverController.java @@ -1,92 +1,92 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo Framework * Version: 1.1.0 * * This file is part of Qcadoo. * * Qcadoo is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.view.internal.controllers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.qcadoo.model.api.file.FileService; import com.qcadoo.tenant.api.MultiTenantUtil; @Controller public class FileResolverController { @Autowired private FileService fileService; @RequestMapping(value = "{tenantId:\\d+}/{firstLevel:\\d+}/{secondLevel:\\d+}/{fileName}", method = RequestMethod.GET) public void resolve(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("tenantId") final String tenantId) { String path = fileService.getPathFromUrl(request.getRequestURI()); boolean removeFileAfterProcessing = request.getParameterMap().containsKey("clean"); if (Integer.valueOf(tenantId) != MultiTenantUtil.getCurrentTenantId()) { try { response.sendRedirect("/error.html?code=404"); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } } InputStream input = null; try { input = fileService.getInputStream(path); if (input == null) { response.sendRedirect("/error.html?code=404"); } else { OutputStream output = response.getOutputStream(); int bytes = IOUtils.copy(input, output); - response.setHeader("Content-disposition", "inline; filename=" + fileService.getName(path)); + response.setHeader("Content-disposition", "attachment; filename=" + fileService.getName(path)); response.setContentType(fileService.getContentType(path)); response.setContentLength(bytes); output.flush(); } } catch (IOException e) { IOUtils.closeQuietly(input); throw new IllegalStateException(e.getMessage(), e); } if (removeFileAfterProcessing) { fileService.remove(path); } } }
true
true
public void resolve(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("tenantId") final String tenantId) { String path = fileService.getPathFromUrl(request.getRequestURI()); boolean removeFileAfterProcessing = request.getParameterMap().containsKey("clean"); if (Integer.valueOf(tenantId) != MultiTenantUtil.getCurrentTenantId()) { try { response.sendRedirect("/error.html?code=404"); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } } InputStream input = null; try { input = fileService.getInputStream(path); if (input == null) { response.sendRedirect("/error.html?code=404"); } else { OutputStream output = response.getOutputStream(); int bytes = IOUtils.copy(input, output); response.setHeader("Content-disposition", "inline; filename=" + fileService.getName(path)); response.setContentType(fileService.getContentType(path)); response.setContentLength(bytes); output.flush(); } } catch (IOException e) { IOUtils.closeQuietly(input); throw new IllegalStateException(e.getMessage(), e); } if (removeFileAfterProcessing) { fileService.remove(path); } }
public void resolve(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("tenantId") final String tenantId) { String path = fileService.getPathFromUrl(request.getRequestURI()); boolean removeFileAfterProcessing = request.getParameterMap().containsKey("clean"); if (Integer.valueOf(tenantId) != MultiTenantUtil.getCurrentTenantId()) { try { response.sendRedirect("/error.html?code=404"); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } } InputStream input = null; try { input = fileService.getInputStream(path); if (input == null) { response.sendRedirect("/error.html?code=404"); } else { OutputStream output = response.getOutputStream(); int bytes = IOUtils.copy(input, output); response.setHeader("Content-disposition", "attachment; filename=" + fileService.getName(path)); response.setContentType(fileService.getContentType(path)); response.setContentLength(bytes); output.flush(); } } catch (IOException e) { IOUtils.closeQuietly(input); throw new IllegalStateException(e.getMessage(), e); } if (removeFileAfterProcessing) { fileService.remove(path); } }
diff --git a/src/com/android/phone/SipCallOptionHandler.java b/src/com/android/phone/SipCallOptionHandler.java index 50d65993..72efe256 100644 --- a/src/com/android/phone/SipCallOptionHandler.java +++ b/src/com/android/phone/SipCallOptionHandler.java @@ -1,384 +1,391 @@ /** * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.phone.sip.SipProfileDb; import com.android.phone.sip.SipSettings; import com.android.phone.sip.SipSharedPreferences; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.sip.SipException; import android.net.sip.SipManager; import android.net.sip.SipProfile; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.telephony.PhoneNumberUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import java.util.List; /** * SipCallOptionHandler select the sip phone based on the call option. */ public class SipCallOptionHandler extends Activity implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, CompoundButton.OnCheckedChangeListener { static final String TAG = "SipCallOptionHandler"; static final int DIALOG_SELECT_PHONE_TYPE = 0; static final int DIALOG_SELECT_OUTGOING_SIP_PHONE = 1; static final int DIALOG_START_SIP_SETTINGS = 2; static final int DIALOG_NO_INTERNET_ERROR = 3; static final int DIALOG_NO_VOIP = 4; static final int DIALOG_SIZE = 5; private Intent mIntent; private List<SipProfile> mProfileList; private String mCallOption; private String mNumber; private SipSharedPreferences mSipSharedPreferences; private SipProfileDb mSipProfileDb; private Dialog[] mDialogs = new Dialog[DIALOG_SIZE]; private SipProfile mOutgoingSipProfile; private TextView mUnsetPriamryHint; private boolean mUseSipPhone = false; private boolean mMakePrimary = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mIntent = (Intent)getIntent().getParcelableExtra (OutgoingCallBroadcaster.EXTRA_NEW_CALL_INTENT); if (mIntent == null) { finish(); return; } // If we're trying to make a SIP call, return a SipPhone if one is // available. // // - If it's a sip: URI, this is definitely a SIP call, regardless // of whether the data is a SIP address or a regular phone // number. // // - If this is a tel: URI but the data contains an "@" character // (see PhoneNumberUtils.isUriNumber()) we consider that to be a // SIP number too. // // TODO: Eventually we may want to disallow that latter case // (e.g. "tel:[email protected]"). // // TODO: We should also consider moving this logic into the // CallManager, where it could be made more generic. // (For example, each "telephony provider" could be allowed // to register the URI scheme(s) that it can handle, and the // CallManager would then find the best match for every // outgoing call.) boolean voipSupported = SipManager.isVoipSupported(this); mSipProfileDb = new SipProfileDb(this); mSipSharedPreferences = new SipSharedPreferences(this); mCallOption = mSipSharedPreferences.getSipCallOption(); Log.v(TAG, "Call option is " + mCallOption); Uri uri = mIntent.getData(); String scheme = uri.getScheme(); mNumber = PhoneNumberUtils.getNumberFromIntent(mIntent, this); if ("sip".equals(scheme) || PhoneNumberUtils.isUriNumber(mNumber)) { mUseSipPhone = true; } else if ("tel".equals(scheme) && ( (mSipProfileDb.getProfilesCount() == 0) - || !uri.toString().contains(mNumber))) { - // Since we are not sure if anyone has touched the number in the - // NEW_OUTGOING_CALL receiver, we just checked if the original uri - // contains the number string. If not, it means someone has changed - // the destination number. We then make the call via regular pstn - // network. + || PhoneUtils.hasPhoneProviderExtras(mIntent))) { + // Since we are not sure if anyone has touched the number during + // the NEW_OUTGOING_CALL broadcast, we just check if the provider + // put their gateway information in the intent. If so, it means + // someone has changed the destination number. We then make the + // call via the default pstn network. However, if one just alters + // the destination directly, then we still let it go through the + // Internet call option process. + // + // TODO: This is just a temporary check, if there is an official + // way to handle the results from other providers, we should have + // a better revision here. setResultAndFinish(); + retrun; } if (!mUseSipPhone && voipSupported && mCallOption.equals(Settings.System.SIP_ASK_ME_EACH_TIME)) { showDialog(DIALOG_SELECT_PHONE_TYPE); return; } if (mCallOption.equals(Settings.System.SIP_ALWAYS)) { mUseSipPhone = true; } if (mUseSipPhone) { if (voipSupported) { startGetPrimarySipPhoneThread(); } else { showDialog(DIALOG_NO_VOIP); } } else { setResultAndFinish(); } } @Override public void onPause() { super.onPause(); if (isFinishing()) return; for (Dialog dialog : mDialogs) { if (dialog != null) dialog.dismiss(); } finish(); } protected Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case DIALOG_SELECT_PHONE_TYPE: dialog = new AlertDialog.Builder(this) .setTitle(R.string.pick_outgoing_call_phone_type) .setIcon(android.R.drawable.ic_dialog_alert) .setSingleChoiceItems(R.array.phone_type_values, -1, this) .setNegativeButton(android.R.string.cancel, this) .setOnCancelListener(this) .create(); break; case DIALOG_SELECT_OUTGOING_SIP_PHONE: dialog = new AlertDialog.Builder(this) .setTitle(R.string.pick_outgoing_sip_phone) .setIcon(android.R.drawable.ic_dialog_alert) .setSingleChoiceItems(getProfileNameArray(), -1, this) .setNegativeButton(android.R.string.cancel, this) .setOnCancelListener(this) .create(); addMakeDefaultCheckBox(dialog); break; case DIALOG_START_SIP_SETTINGS: dialog = new AlertDialog.Builder(this) .setTitle(R.string.no_sip_account_found_title) .setMessage(R.string.no_sip_account_found) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.sip_menu_add, this) .setNegativeButton(android.R.string.cancel, this) .setOnCancelListener(this) .create(); break; case DIALOG_NO_INTERNET_ERROR: boolean wifiOnly = SipManager.isSipWifiOnly(this); dialog = new AlertDialog.Builder(this) .setTitle(wifiOnly ? R.string.no_wifi_available_title : R.string.no_internet_available_title) .setMessage(wifiOnly ? R.string.no_wifi_available : R.string.no_internet_available) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.ok, this) .setOnCancelListener(this) .create(); break; case DIALOG_NO_VOIP: dialog = new AlertDialog.Builder(this) .setTitle(R.string.no_voip) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.ok, this) .setOnCancelListener(this) .create(); break; default: dialog = null; } if (dialog != null) { mDialogs[id] = dialog; } return dialog; } private void addMakeDefaultCheckBox(Dialog dialog) { LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate( com.android.internal.R.layout.always_use_checkbox, null); CheckBox makePrimaryCheckBox = (CheckBox)view.findViewById(com.android.internal.R.id.alwaysUse); makePrimaryCheckBox.setText(R.string.remember_my_choice); makePrimaryCheckBox.setOnCheckedChangeListener(this); mUnsetPriamryHint = (TextView)view.findViewById( com.android.internal.R.id.clearDefaultHint); mUnsetPriamryHint.setText(R.string.reset_my_choice_hint); mUnsetPriamryHint.setVisibility(View.GONE); ((AlertDialog)dialog).setView(view); } private CharSequence[] getProfileNameArray() { CharSequence[] entries = new CharSequence[mProfileList.size()]; int i = 0; for (SipProfile p : mProfileList) { entries[i++] = p.getProfileName(); } return entries; } public void onClick(DialogInterface dialog, int id) { if (id == DialogInterface.BUTTON_NEGATIVE) { // button negative is cancel finish(); return; } else if(dialog == mDialogs[DIALOG_SELECT_PHONE_TYPE]) { String selection = getResources().getStringArray( R.array.phone_type_values)[id]; Log.v(TAG, "User pick phone " + selection); if (selection.equals(getString(R.string.internet_phone))) { mUseSipPhone = true; startGetPrimarySipPhoneThread(); return; } } else if (dialog == mDialogs[DIALOG_SELECT_OUTGOING_SIP_PHONE]) { mOutgoingSipProfile = mProfileList.get(id); } else if ((dialog == mDialogs[DIALOG_NO_INTERNET_ERROR]) || (dialog == mDialogs[DIALOG_NO_VOIP])) { finish(); return; } else { if (id == DialogInterface.BUTTON_POSITIVE) { // Redirect to sip settings and drop the call. Intent newIntent = new Intent(this, SipSettings.class); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(newIntent); } finish(); return; } setResultAndFinish(); } public void onCancel(DialogInterface dialog) { finish(); } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mMakePrimary = isChecked; if (isChecked) { mUnsetPriamryHint.setVisibility(View.VISIBLE); } else { mUnsetPriamryHint.setVisibility(View.INVISIBLE); } } private void createSipPhoneIfNeeded(SipProfile p) { CallManager cm = PhoneApp.getInstance().mCM; if (PhoneUtils.getSipPhoneFromUri(cm, p.getUriString()) != null) return; // Create the phone since we can not find it in CallManager try { SipManager.newInstance(this).open(p); Phone phone = PhoneFactory.makeSipPhone(p.getUriString()); if (phone != null) { cm.registerPhone(phone); } else { Log.e(TAG, "cannot make sipphone profile" + p); } } catch (SipException e) { Log.e(TAG, "cannot open sip profile" + p, e); } } private void setResultAndFinish() { runOnUiThread(new Runnable() { public void run() { if (mOutgoingSipProfile != null) { if (!isNetworkConnected()) { showDialog(DIALOG_NO_INTERNET_ERROR); return; } Log.v(TAG, "primary SIP URI is " + mOutgoingSipProfile.getUriString()); createSipPhoneIfNeeded(mOutgoingSipProfile); mIntent.putExtra(OutgoingCallBroadcaster.EXTRA_SIP_PHONE_URI, mOutgoingSipProfile.getUriString()); if (mMakePrimary) { mSipSharedPreferences.setPrimaryAccount( mOutgoingSipProfile.getUriString()); } } if (mUseSipPhone && mOutgoingSipProfile == null) { showDialog(DIALOG_START_SIP_SETTINGS); return; } else { startActivity(mIntent); } finish(); } }); } private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService( Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo ni = cm.getActiveNetworkInfo(); if ((ni == null) || !ni.isConnected()) return false; return ((ni.getType() == ConnectivityManager.TYPE_WIFI) || !SipManager.isSipWifiOnly(this)); } return false; } private void startGetPrimarySipPhoneThread() { new Thread(new Runnable() { public void run() { getPrimarySipPhone(); } }).start(); } private void getPrimarySipPhone() { String primarySipUri = mSipSharedPreferences.getPrimaryAccount(); mOutgoingSipProfile = getPrimaryFromExistingProfiles(primarySipUri); if (mOutgoingSipProfile == null) { if ((mProfileList != null) && (mProfileList.size() > 0)) { runOnUiThread(new Runnable() { public void run() { showDialog(DIALOG_SELECT_OUTGOING_SIP_PHONE); } }); return; } } setResultAndFinish(); } private SipProfile getPrimaryFromExistingProfiles(String primarySipUri) { mProfileList = mSipProfileDb.retrieveSipProfileList(); if (mProfileList == null) return null; for (SipProfile p : mProfileList) { if (p.getUriString().equals(primarySipUri)) return p; } return null; } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mIntent = (Intent)getIntent().getParcelableExtra (OutgoingCallBroadcaster.EXTRA_NEW_CALL_INTENT); if (mIntent == null) { finish(); return; } // If we're trying to make a SIP call, return a SipPhone if one is // available. // // - If it's a sip: URI, this is definitely a SIP call, regardless // of whether the data is a SIP address or a regular phone // number. // // - If this is a tel: URI but the data contains an "@" character // (see PhoneNumberUtils.isUriNumber()) we consider that to be a // SIP number too. // // TODO: Eventually we may want to disallow that latter case // (e.g. "tel:[email protected]"). // // TODO: We should also consider moving this logic into the // CallManager, where it could be made more generic. // (For example, each "telephony provider" could be allowed // to register the URI scheme(s) that it can handle, and the // CallManager would then find the best match for every // outgoing call.) boolean voipSupported = SipManager.isVoipSupported(this); mSipProfileDb = new SipProfileDb(this); mSipSharedPreferences = new SipSharedPreferences(this); mCallOption = mSipSharedPreferences.getSipCallOption(); Log.v(TAG, "Call option is " + mCallOption); Uri uri = mIntent.getData(); String scheme = uri.getScheme(); mNumber = PhoneNumberUtils.getNumberFromIntent(mIntent, this); if ("sip".equals(scheme) || PhoneNumberUtils.isUriNumber(mNumber)) { mUseSipPhone = true; } else if ("tel".equals(scheme) && ( (mSipProfileDb.getProfilesCount() == 0) || !uri.toString().contains(mNumber))) { // Since we are not sure if anyone has touched the number in the // NEW_OUTGOING_CALL receiver, we just checked if the original uri // contains the number string. If not, it means someone has changed // the destination number. We then make the call via regular pstn // network. setResultAndFinish(); } if (!mUseSipPhone && voipSupported && mCallOption.equals(Settings.System.SIP_ASK_ME_EACH_TIME)) { showDialog(DIALOG_SELECT_PHONE_TYPE); return; } if (mCallOption.equals(Settings.System.SIP_ALWAYS)) { mUseSipPhone = true; } if (mUseSipPhone) { if (voipSupported) { startGetPrimarySipPhoneThread(); } else { showDialog(DIALOG_NO_VOIP); } } else { setResultAndFinish(); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mIntent = (Intent)getIntent().getParcelableExtra (OutgoingCallBroadcaster.EXTRA_NEW_CALL_INTENT); if (mIntent == null) { finish(); return; } // If we're trying to make a SIP call, return a SipPhone if one is // available. // // - If it's a sip: URI, this is definitely a SIP call, regardless // of whether the data is a SIP address or a regular phone // number. // // - If this is a tel: URI but the data contains an "@" character // (see PhoneNumberUtils.isUriNumber()) we consider that to be a // SIP number too. // // TODO: Eventually we may want to disallow that latter case // (e.g. "tel:[email protected]"). // // TODO: We should also consider moving this logic into the // CallManager, where it could be made more generic. // (For example, each "telephony provider" could be allowed // to register the URI scheme(s) that it can handle, and the // CallManager would then find the best match for every // outgoing call.) boolean voipSupported = SipManager.isVoipSupported(this); mSipProfileDb = new SipProfileDb(this); mSipSharedPreferences = new SipSharedPreferences(this); mCallOption = mSipSharedPreferences.getSipCallOption(); Log.v(TAG, "Call option is " + mCallOption); Uri uri = mIntent.getData(); String scheme = uri.getScheme(); mNumber = PhoneNumberUtils.getNumberFromIntent(mIntent, this); if ("sip".equals(scheme) || PhoneNumberUtils.isUriNumber(mNumber)) { mUseSipPhone = true; } else if ("tel".equals(scheme) && ( (mSipProfileDb.getProfilesCount() == 0) || PhoneUtils.hasPhoneProviderExtras(mIntent))) { // Since we are not sure if anyone has touched the number during // the NEW_OUTGOING_CALL broadcast, we just check if the provider // put their gateway information in the intent. If so, it means // someone has changed the destination number. We then make the // call via the default pstn network. However, if one just alters // the destination directly, then we still let it go through the // Internet call option process. // // TODO: This is just a temporary check, if there is an official // way to handle the results from other providers, we should have // a better revision here. setResultAndFinish(); retrun; } if (!mUseSipPhone && voipSupported && mCallOption.equals(Settings.System.SIP_ASK_ME_EACH_TIME)) { showDialog(DIALOG_SELECT_PHONE_TYPE); return; } if (mCallOption.equals(Settings.System.SIP_ALWAYS)) { mUseSipPhone = true; } if (mUseSipPhone) { if (voipSupported) { startGetPrimarySipPhoneThread(); } else { showDialog(DIALOG_NO_VOIP); } } else { setResultAndFinish(); } }
diff --git a/pn-sync/src/main/java/info/papyri/sync/GitWrapper.java b/pn-sync/src/main/java/info/papyri/sync/GitWrapper.java index 43e2a234..14c272c4 100644 --- a/pn-sync/src/main/java/info/papyri/sync/GitWrapper.java +++ b/pn-sync/src/main/java/info/papyri/sync/GitWrapper.java @@ -1,403 +1,403 @@ package info.papyri.sync; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; /** * * @author hcayless */ public class GitWrapper { private static GitWrapper git; private static String graph = "http://papyri.info/graph"; private static String path = "/pi/query"; private static String sparqlserver = "http://localhost:8090"; private static Logger logger = Logger.getLogger("pn-sync"); public static GitWrapper init (String gitDir, String dbUser, String dbPass) { git = new GitWrapper(); git.gitDir = new File(gitDir); git.dbUser = dbUser; git.dbPass = dbPass; try { git.head = getLastSync(); } catch (Exception e) { git.success = false; } return git; } public static GitWrapper get() { if (git != null) { return git; } else { throw new RuntimeException("Uninitialized GitWrapper"); } } private File gitDir; /* * success==false means that the repos could not be synchronized for some * reason, perhaps a conflict, and that human intervention is called for. */ private boolean success = true; private String head = ""; private String dbUser; private String dbPass; private Date gitSync; private Date canonicalSync; public static void executeSync() { try { git.pull("canonical"); git.pull("github"); git.push("canonical"); git.push("github"); } catch (Exception e) { if (git.success) { git.success = false; } logger.error("Sync Failed", e); } // get current HEAD's SHA : git rev-parse HEAD // run local pull from canonical, then git pull from github‚ record time stamps, success :: RESTful: return 200 for success, 500 for failure/conflict // on failure, git reset to previous SHA // get list of files affected by pull: git diff --name-only SHA1 SHA2 // execute indexing on file list } public static String getPreviousSync() throws Exception { String result = null; Connection connect = null; Class.forName("com.mysql.jdbc.Driver"); try { connect = DriverManager.getConnection( "jdbc:mysql://localhost/pn?" + "user=" + git.dbUser + "&password=" + git.dbPass); Statement st = connect.createStatement(); ResultSet rs = st.executeQuery("SELECT hash FROM sync_history ORDER BY date DESC LIMIT 2"); if (rs.next()) { if (!rs.isAfterLast() || !rs.next()) { result = getHead(); } else { result = rs.getString("hash"); } } } finally { connect.close(); } return result; } public static String getLastSync() throws Exception { String result = null; Connection connect = null; Class.forName("com.mysql.jdbc.Driver"); try { connect = DriverManager.getConnection( "jdbc:mysql://localhost/pn?" + "user=" + git.dbUser + "&password=" + git.dbPass); Statement st = connect.createStatement(); ResultSet rs = st.executeQuery("SELECT hash FROM sync_history WHERE date = (SELECT MAX(date) FROM sync_history)"); if (rs.next()) { result = rs.getString("hash"); } } finally { connect.close(); } return result; } private void storeHead() throws Exception { Connection connect = null; Class.forName("com.mysql.jdbc.Driver"); try { connect = DriverManager.getConnection( "jdbc:mysql://localhost/pn?" + "user=" + git.dbUser + "&password=" + git.dbPass); Statement st = connect.createStatement(); st.executeUpdate("INSERT INTO sync_history (hash, date) VALUES ('" + git.head + "', NOW())"); } finally { connect.close(); } } public static String getHead() throws Exception { ProcessBuilder pb = new ProcessBuilder("git", "rev-parse", "HEAD"); pb.directory(git.gitDir); String newhead = null; try { Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { newhead = line; } } catch (Exception e) { git.success = false; throw e; } return newhead; } private void pull(String repo) throws Exception { logger.info("Starting pull on " + repo + "."); try { ProcessBuilder pb = new ProcessBuilder("git", "pull", repo, "master"); pb.directory(git.gitDir); pb.start().waitFor(); git.head = getHead(); if (!git.head.equals(getLastSync())) { storeHead(); } } catch (Exception e) { git.success = false; git.reset(git.head); logger.error("Pull failed", e); throw e; } } private void push(String repo) throws Exception { logger.info("Starting push to " + repo + "."); try { ProcessBuilder pb = new ProcessBuilder("git", "push", repo); pb.directory(git.gitDir); pb.start().waitFor(); } catch (Exception e) { git.success = false; git.reset(git.head); logger.error("Push failed", e); throw e; } } private void reset(String commit) throws Exception { ProcessBuilder pb = new ProcessBuilder("git", "reset", commit); pb.directory(gitDir); pb.start().waitFor(); } public static List<String> getDiffs(String commit) throws Exception { ProcessBuilder pb = new ProcessBuilder("git", "diff", "--name-only", commit, git.head); pb.directory(git.gitDir); List<String> diffs = new ArrayList<String>(); try { Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { diffs.add(line); } } catch (Exception e) { git.success = false; throw e; } List<String> result = new ArrayList<String>(); for (String diff : diffs) { result.add(diff); } return result; } public static List<String> getDiffsSince(String date) throws Exception { Connection connect = null; Class.forName("com.mysql.jdbc.Driver"); try { connect = DriverManager.getConnection( "jdbc:mysql://localhost/pn?" + "user=" + git.dbUser + "&password=" + git.dbPass); PreparedStatement st = connect.prepareStatement("SELECT hash FROM sync_history WHERE date > ? ORDER BY date LIMIT 1"); st.setDate(1, Date.valueOf(date)); ResultSet rs = st.executeQuery(); if (!rs.next()) { return getDiffs(getHead()); } else { return getDiffs(rs.getString("hash")); } } finally { connect.close(); } } public static String filenameToUri(String file) { return filenameToUri(file, false); } public static String filenameToUri(String file, boolean resolve) { StringBuilder result = new StringBuilder(); if (file.contains("DDB")) { StringBuilder sparql = new StringBuilder(); - sparql.append("prefix dc: <http://purl.org/dc/terms/> ") + sparql.append("prefix dc: <http://purl.org/dc/elements/1.1/> ") .append("select ?id ") .append("from <http://papyri.info/graph> ") .append("where { ?id dc:identifier \"") .append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))) .append("\" }"); try { // If the numbers server already knows the id for the filename, use that // because it will be 100% accurate. URL m = new URL(sparqlserver + path + "?query=" + URLEncoder.encode(sparql.toString(), "UTF-8") + "&output=json"); JsonNode root = getJson(m); if (root.path("results").path("bindings").size() > 0) { result.append(root.path("results").path("bindings").path(0).path("id").path("value").asText()); // Otherwise, attempt to infer the identifier from the filename. } else { result.append("http://papyri.info/ddbdp/"); List<String> collections = GitWrapper.loadDDbCollections(); Iterator<String> i = collections.iterator(); boolean match = false; while (i.hasNext()) { String collection = i.next().substring("http://papyri.info/ddbdp/".length()); if (file.substring(file.lastIndexOf("/") + 1).startsWith(collection)) { result.append(collection).append(";"); // name should be of the form bgu.1.2, so lose the "bgu." String rest = file.substring(file.lastIndexOf("/") + collection.length() + 2).replaceAll("\\.xml$", ""); if (rest.contains(".")) { result.append(rest.substring(0, rest.indexOf("."))); result.append(";"); result.append(rest.substring(rest.indexOf(".") + 1)); } else { result.append(";"); result.append(rest); } result.append("/source"); if (result.toString().matches("http://papyri\\.info/ddbdp/(\\w|\\d|\\.)+;(\\w|\\d)*;(\\w|\\d)+/source")) { match = true; break; // Early return } else { throw new Exception("Malformed file name: " + file); } } } // If we made it through the collection list without a match, // something is wrong. if (!match) { throw new Exception("Unknown collection in file: " + file); } } } catch (Exception e) { logger.error("Failed to resolve URI.", e); result.delete(0, result.length()); } } else { result.append("http://papyri.info/"); if (file.contains("HGV_meta")) { result.append("hgv/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/source"); } if (file.contains("APIS")) { result.append("apis/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/source"); } if (file.contains("Biblio")) { result.append("biblio/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/ref"); } } logger.debug(result); if (!resolve || result.toString().contains("/biblio/")) { return result.toString(); } else { // APIS and HGV files might be aggregated with a DDbDP text. String uri = lookupMainId(result.toString()); if (uri != null) { return uri; } else { return result.toString(); } } } public static String lookupMainId(String id) { StringBuilder sparql = new StringBuilder(); sparql.append("prefix dc: <http://purl.org/dc/terms/> ") .append("select ?id ") .append("from <http://papyri.info/graph> ") .append("where { ?id dc:relation <") .append(id) .append("> ") .append("filter regex(str(?id), \"^http://papyri.info/ddbdp/.*\") ") .append("filter not exists {?id dc:isReplacedBy ?b} }"); try { URL m = new URL(sparqlserver + path + "?query=" + URLEncoder.encode(sparql.toString(), "UTF-8") + "&output=json"); JsonNode root = getJson(m); if (root.path("results").path("bindings").size() > 0) { return root.path("results").path("bindings").path(0).path("id").path("value").asText(); } else { if (id.contains("/apis/")) { sparql = new StringBuilder(); sparql.append("prefix dc: <http://purl.org/dc/terms/> ") .append("select ?id ") .append("from <http://papyri.info/graph> ") .append("where { ?id dc:relation <") .append(id) .append("> ") .append("filter regex(str(?id), \"^http://papyri.info/hgv/.*\") }"); m = new URL(sparqlserver + path + "?query=" + URLEncoder.encode(sparql.toString(), "UTF-8") + "&output=json"); root = getJson(m); if (root.path("results").path("bindings").size() > 0) { return root.path("results").path("bindings").path(0).path("id").path("value").asText(); } } } } catch (Exception e) { logger.error("Failed to look up query: \n" + sparql.toString()); } return null; } private static JsonNode getJson(URL q) throws java.io.IOException { HttpURLConnection http = (HttpURLConnection)q.openConnection(); http.setConnectTimeout(2000); ObjectMapper o = new ObjectMapper(); JsonNode result = o.readValue(http.getInputStream(), JsonNode.class); return result; } private static List<String> loadDDbCollections() { List<String> result = new ArrayList<String>(); String sparql = "prefix dc: <http://purl.org/dc/terms/> " + "select ?id " + "from <http://papyri.info/graph> " + "where { <http://papyri.info/ddbdp> dc:hasPart ?id } " + "order by desc(?id)"; try { URL m = new URL(sparqlserver + path + "?query=" + URLEncoder.encode(sparql.toString(), "UTF-8") + "&output=json"); JsonNode root = getJson(m); Iterator<JsonNode> i = root.path("results").path("bindings").getElements(); while (i.hasNext()) { result.add(i.next().path("id").path("value").asText()); } } catch (Exception e) { logger.error("Failed to resolve URI.", e); } return result; } }
true
true
public static String filenameToUri(String file, boolean resolve) { StringBuilder result = new StringBuilder(); if (file.contains("DDB")) { StringBuilder sparql = new StringBuilder(); sparql.append("prefix dc: <http://purl.org/dc/terms/> ") .append("select ?id ") .append("from <http://papyri.info/graph> ") .append("where { ?id dc:identifier \"") .append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))) .append("\" }"); try { // If the numbers server already knows the id for the filename, use that // because it will be 100% accurate. URL m = new URL(sparqlserver + path + "?query=" + URLEncoder.encode(sparql.toString(), "UTF-8") + "&output=json"); JsonNode root = getJson(m); if (root.path("results").path("bindings").size() > 0) { result.append(root.path("results").path("bindings").path(0).path("id").path("value").asText()); // Otherwise, attempt to infer the identifier from the filename. } else { result.append("http://papyri.info/ddbdp/"); List<String> collections = GitWrapper.loadDDbCollections(); Iterator<String> i = collections.iterator(); boolean match = false; while (i.hasNext()) { String collection = i.next().substring("http://papyri.info/ddbdp/".length()); if (file.substring(file.lastIndexOf("/") + 1).startsWith(collection)) { result.append(collection).append(";"); // name should be of the form bgu.1.2, so lose the "bgu." String rest = file.substring(file.lastIndexOf("/") + collection.length() + 2).replaceAll("\\.xml$", ""); if (rest.contains(".")) { result.append(rest.substring(0, rest.indexOf("."))); result.append(";"); result.append(rest.substring(rest.indexOf(".") + 1)); } else { result.append(";"); result.append(rest); } result.append("/source"); if (result.toString().matches("http://papyri\\.info/ddbdp/(\\w|\\d|\\.)+;(\\w|\\d)*;(\\w|\\d)+/source")) { match = true; break; // Early return } else { throw new Exception("Malformed file name: " + file); } } } // If we made it through the collection list without a match, // something is wrong. if (!match) { throw new Exception("Unknown collection in file: " + file); } } } catch (Exception e) { logger.error("Failed to resolve URI.", e); result.delete(0, result.length()); } } else { result.append("http://papyri.info/"); if (file.contains("HGV_meta")) { result.append("hgv/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/source"); } if (file.contains("APIS")) { result.append("apis/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/source"); } if (file.contains("Biblio")) { result.append("biblio/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/ref"); } } logger.debug(result); if (!resolve || result.toString().contains("/biblio/")) { return result.toString(); } else { // APIS and HGV files might be aggregated with a DDbDP text. String uri = lookupMainId(result.toString()); if (uri != null) { return uri; } else { return result.toString(); } } }
public static String filenameToUri(String file, boolean resolve) { StringBuilder result = new StringBuilder(); if (file.contains("DDB")) { StringBuilder sparql = new StringBuilder(); sparql.append("prefix dc: <http://purl.org/dc/elements/1.1/> ") .append("select ?id ") .append("from <http://papyri.info/graph> ") .append("where { ?id dc:identifier \"") .append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))) .append("\" }"); try { // If the numbers server already knows the id for the filename, use that // because it will be 100% accurate. URL m = new URL(sparqlserver + path + "?query=" + URLEncoder.encode(sparql.toString(), "UTF-8") + "&output=json"); JsonNode root = getJson(m); if (root.path("results").path("bindings").size() > 0) { result.append(root.path("results").path("bindings").path(0).path("id").path("value").asText()); // Otherwise, attempt to infer the identifier from the filename. } else { result.append("http://papyri.info/ddbdp/"); List<String> collections = GitWrapper.loadDDbCollections(); Iterator<String> i = collections.iterator(); boolean match = false; while (i.hasNext()) { String collection = i.next().substring("http://papyri.info/ddbdp/".length()); if (file.substring(file.lastIndexOf("/") + 1).startsWith(collection)) { result.append(collection).append(";"); // name should be of the form bgu.1.2, so lose the "bgu." String rest = file.substring(file.lastIndexOf("/") + collection.length() + 2).replaceAll("\\.xml$", ""); if (rest.contains(".")) { result.append(rest.substring(0, rest.indexOf("."))); result.append(";"); result.append(rest.substring(rest.indexOf(".") + 1)); } else { result.append(";"); result.append(rest); } result.append("/source"); if (result.toString().matches("http://papyri\\.info/ddbdp/(\\w|\\d|\\.)+;(\\w|\\d)*;(\\w|\\d)+/source")) { match = true; break; // Early return } else { throw new Exception("Malformed file name: " + file); } } } // If we made it through the collection list without a match, // something is wrong. if (!match) { throw new Exception("Unknown collection in file: " + file); } } } catch (Exception e) { logger.error("Failed to resolve URI.", e); result.delete(0, result.length()); } } else { result.append("http://papyri.info/"); if (file.contains("HGV_meta")) { result.append("hgv/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/source"); } if (file.contains("APIS")) { result.append("apis/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/source"); } if (file.contains("Biblio")) { result.append("biblio/"); result.append(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."))); result.append("/ref"); } } logger.debug(result); if (!resolve || result.toString().contains("/biblio/")) { return result.toString(); } else { // APIS and HGV files might be aggregated with a DDbDP text. String uri = lookupMainId(result.toString()); if (uri != null) { return uri; } else { return result.toString(); } } }
diff --git a/src/main/java/javahive/infrastruktura/DBFiller.java b/src/main/java/javahive/infrastruktura/DBFiller.java index 5d8e198..67eb0c2 100644 --- a/src/main/java/javahive/infrastruktura/DBFiller.java +++ b/src/main/java/javahive/infrastruktura/DBFiller.java @@ -1,65 +1,65 @@ package javahive.infrastruktura; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.fixy.Fixy; import com.fixy.JpaFixyBuilder; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; @Component public class DBFiller implements ApplicationContextAware{ //@PersistenceContext //private EntityManager entityManager; @Inject Finder finder; @PostConstruct public void fill(){ EntityManager entityManager = applicationContext.getBean(EntityManagerFactory.class).createEntityManager(); EntityTransaction t = entityManager.getTransaction(); t.begin(); - Fixy fixtures = new JpaFixyBuilder(entityManager).withDefaultPackage("javafxapplication2").useFieldAccess().build(); + Fixy fixtures = new JpaFixyBuilder(entityManager).withDefaultPackage("h2_TestData").useFieldAccess().build(); //fixtures.load("javafxapplication2/Studenci.yaml","javafxapplication2/Przedmioty.yaml","javafxapplication2/Oceny.yaml"); //fixtures.load("javafxapplication2/Studenci.yaml","pet_types.yaml","pets.yaml"); //fixtures.load("javafxapplication2/Studenci.yaml","javafxapplication2/Przedmioty.yaml","javafxapplication2/Oceny.yaml","pet_types.yaml","pets.yaml"); - fixtures.load("javafxapplication2/Studenci.yaml"); - fixtures.load("javafxapplication2/Przedmioty.yaml"); - fixtures.load("javafxapplication2/Oceny.yaml"); - fixtures.load("javafxapplication2/Indeksy.yaml"); + fixtures.load("h2_TestData/Studenci.yaml"); + fixtures.load("h2_TestData/Przedmioty.yaml"); + fixtures.load("h2_TestData/Oceny.yaml"); + fixtures.load("h2_TestData/Indeksy.yaml"); //System.out.printf("załadowano %d studentów\n",finder.findAll(Student.class).size()); //System.out.printf("załadowano %d ocen\n",finder.findAll(Ocena.class).size()); //for(Student s:finder.findAll(Student.class)){ //System.out.printf("student %s ma %d ocen \n",s.getImie(),s.getOceny().size()); //} //for(Ocena o:finder.findAll(Ocena.class)){ //System.out.printf("ocena %s należy do studenta %s \n",o.getWysokosc(),o.getStudent().getImie()); //} t.commit(); entityManager.close(); System.out.println("----------------------------------------------------------------------"); } private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext=applicationContext; } }
false
true
public void fill(){ EntityManager entityManager = applicationContext.getBean(EntityManagerFactory.class).createEntityManager(); EntityTransaction t = entityManager.getTransaction(); t.begin(); Fixy fixtures = new JpaFixyBuilder(entityManager).withDefaultPackage("javafxapplication2").useFieldAccess().build(); //fixtures.load("javafxapplication2/Studenci.yaml","javafxapplication2/Przedmioty.yaml","javafxapplication2/Oceny.yaml"); //fixtures.load("javafxapplication2/Studenci.yaml","pet_types.yaml","pets.yaml"); //fixtures.load("javafxapplication2/Studenci.yaml","javafxapplication2/Przedmioty.yaml","javafxapplication2/Oceny.yaml","pet_types.yaml","pets.yaml"); fixtures.load("javafxapplication2/Studenci.yaml"); fixtures.load("javafxapplication2/Przedmioty.yaml"); fixtures.load("javafxapplication2/Oceny.yaml"); fixtures.load("javafxapplication2/Indeksy.yaml"); //System.out.printf("załadowano %d studentów\n",finder.findAll(Student.class).size()); //System.out.printf("załadowano %d ocen\n",finder.findAll(Ocena.class).size()); //for(Student s:finder.findAll(Student.class)){ //System.out.printf("student %s ma %d ocen \n",s.getImie(),s.getOceny().size()); //} //for(Ocena o:finder.findAll(Ocena.class)){ //System.out.printf("ocena %s należy do studenta %s \n",o.getWysokosc(),o.getStudent().getImie()); //} t.commit(); entityManager.close(); System.out.println("----------------------------------------------------------------------"); }
public void fill(){ EntityManager entityManager = applicationContext.getBean(EntityManagerFactory.class).createEntityManager(); EntityTransaction t = entityManager.getTransaction(); t.begin(); Fixy fixtures = new JpaFixyBuilder(entityManager).withDefaultPackage("h2_TestData").useFieldAccess().build(); //fixtures.load("javafxapplication2/Studenci.yaml","javafxapplication2/Przedmioty.yaml","javafxapplication2/Oceny.yaml"); //fixtures.load("javafxapplication2/Studenci.yaml","pet_types.yaml","pets.yaml"); //fixtures.load("javafxapplication2/Studenci.yaml","javafxapplication2/Przedmioty.yaml","javafxapplication2/Oceny.yaml","pet_types.yaml","pets.yaml"); fixtures.load("h2_TestData/Studenci.yaml"); fixtures.load("h2_TestData/Przedmioty.yaml"); fixtures.load("h2_TestData/Oceny.yaml"); fixtures.load("h2_TestData/Indeksy.yaml"); //System.out.printf("załadowano %d studentów\n",finder.findAll(Student.class).size()); //System.out.printf("załadowano %d ocen\n",finder.findAll(Ocena.class).size()); //for(Student s:finder.findAll(Student.class)){ //System.out.printf("student %s ma %d ocen \n",s.getImie(),s.getOceny().size()); //} //for(Ocena o:finder.findAll(Ocena.class)){ //System.out.printf("ocena %s należy do studenta %s \n",o.getWysokosc(),o.getStudent().getImie()); //} t.commit(); entityManager.close(); System.out.println("----------------------------------------------------------------------"); }
diff --git a/org.oobium.build.console/src/org/oobium/build/console/commands/export/ClientCommand.java b/org.oobium.build.console/src/org/oobium/build/console/commands/export/ClientCommand.java index 66639797..fb7cbf5c 100644 --- a/org.oobium.build.console/src/org/oobium/build/console/commands/export/ClientCommand.java +++ b/org.oobium.build.console/src/org/oobium/build/console/commands/export/ClientCommand.java @@ -1,133 +1,133 @@ package org.oobium.build.console.commands.export; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.oobium.build.console.BuilderCommand; import org.oobium.build.console.Eclipse; import org.oobium.build.gen.android.GeneratorEvent; import org.oobium.build.gen.android.GeneratorListener; import org.oobium.build.gen.android.ScaffoldingGenerator; import org.oobium.build.workspace.AndroidApp; import org.oobium.build.workspace.ClientExporter; import org.oobium.build.workspace.Module; import org.oobium.build.workspace.Project; import org.oobium.build.workspace.Project.Type; import org.oobium.build.workspace.Workspace; public class ClientCommand extends BuilderCommand { @Override protected void configure() { moduleRequired = true; } @Override protected void run() { Workspace workspace = getWorkspace(); Module module = getModule(); Project target = null; if(hasParam("target")) { target = workspace.getProject(param("target")); if(target == null) { console.err.println(param("target") + " does not exist in the workspace"); return; } } if(target == null) { Project[] projects = workspace.getProjects(Type.Android); if(projects.length == 1) { String s = ask("use \"" + projects[0] + "\" as the target? [Y/N] "); if("Y".equalsIgnoreCase(s)) { target = (AndroidApp) projects[0]; } } else if(projects.length > 1) { Arrays.sort(projects); StringBuilder sb = new StringBuilder(); sb.append(projects.length).append(" Android projects found:"); for(int i = 0; i < projects.length; i++) { sb.append("\n " + i + " - " + projects[i].name); } sb.append("\nselect which to use as the target (0-" + (projects.length - 1) + "), or <Enter> for none "); String s = ask(sb.toString()); try { int i = Integer.parseInt(s); if(i >= 0 && i < projects.length) { target = (AndroidApp) projects[i]; } } catch(Exception e) { // discard } } } try { boolean full = !module.hasModels() || ("Y".equalsIgnoreCase(ask("export the full [P]roject, or just its [M]odels? [P/M] "))); ClientExporter exporter = new ClientExporter(workspace, module); exporter.setFull(full); exporter.includeSource(true); exporter.setTarget(target); File[] jars = exporter.export(); for(File jar : jars) { if(target == null) { console.out.println("exported <a href=\"open file " + jar.getAbsolutePath() + "\">" + jar.getName() + "</a>" + " to <a href=\"open file " + workspace.getExportDir().getAbsolutePath() + "\">Export Directory</a>"); } else { int len = target.file.getAbsolutePath().length(); String name = target.name + ": " + jar.getParent().substring(len); console.out.println("exported <a href=\"open file " + jar.getAbsolutePath() + "\">" + jar.getName() + "</a>" + " to <a href=\"open file " + jar.getParent() + "\">" + name + "</a>"); } } if(target instanceof AndroidApp) { String s = ask("create scaffolding? [Y/N] "); if("Y".equalsIgnoreCase(s)) { AndroidApp android = (AndroidApp) target; ScaffoldingGenerator gen = new ScaffoldingGenerator(module, android); gen.setListener(new GeneratorListener() { @Override public void handleEvent(GeneratorEvent event) { console.out.println(event.data); } }); List<File> files = gen.generateScaffolding(); for(File file : files) { int len = target.file.getAbsolutePath().length(); String path = target.file.getAbsolutePath() + "#" + file.getAbsolutePath().substring(len+1); console.out.println(" exported <a href=\"open file " + path + "\">" + file.getName() + "</a>"); } File[] ma = android.getMainActivities(); if(ma.length == 1) { String name = ma[0].getName(); name = name.substring(0, name.length()-5); s = ask("add launch buttons to the '" + name + "' activity? [Y/N] "); if("Y".equalsIgnoreCase(s)) { File layout = gen.generateLaunchButton(ma[0]); if(layout != null) { int len = target.file.getAbsolutePath().length(); String path = target.file.getAbsolutePath() + "#" + ma[0].getAbsolutePath().substring(len+1); console.out.println(" modified activity <a href=\"open file " + path + "\">" + ma[0].getName() + "</a>"); path = target.file.getAbsolutePath() + "#" + layout.getAbsolutePath().substring(len+1); console.out.println(" modified layout <a href=\"open file " + path + "\">" + layout.getName() + "</a>"); } } } } } if(target != null) { - console.out.println("export complete\n *** models to be accessed by the client must be publised first ***"); + console.out.println("export complete\n *** models to be accessed by the client must be published first ***"); Eclipse.refreshProject(target.name); } } catch(IOException e) { console.err.print(e); } } }
true
true
protected void run() { Workspace workspace = getWorkspace(); Module module = getModule(); Project target = null; if(hasParam("target")) { target = workspace.getProject(param("target")); if(target == null) { console.err.println(param("target") + " does not exist in the workspace"); return; } } if(target == null) { Project[] projects = workspace.getProjects(Type.Android); if(projects.length == 1) { String s = ask("use \"" + projects[0] + "\" as the target? [Y/N] "); if("Y".equalsIgnoreCase(s)) { target = (AndroidApp) projects[0]; } } else if(projects.length > 1) { Arrays.sort(projects); StringBuilder sb = new StringBuilder(); sb.append(projects.length).append(" Android projects found:"); for(int i = 0; i < projects.length; i++) { sb.append("\n " + i + " - " + projects[i].name); } sb.append("\nselect which to use as the target (0-" + (projects.length - 1) + "), or <Enter> for none "); String s = ask(sb.toString()); try { int i = Integer.parseInt(s); if(i >= 0 && i < projects.length) { target = (AndroidApp) projects[i]; } } catch(Exception e) { // discard } } } try { boolean full = !module.hasModels() || ("Y".equalsIgnoreCase(ask("export the full [P]roject, or just its [M]odels? [P/M] "))); ClientExporter exporter = new ClientExporter(workspace, module); exporter.setFull(full); exporter.includeSource(true); exporter.setTarget(target); File[] jars = exporter.export(); for(File jar : jars) { if(target == null) { console.out.println("exported <a href=\"open file " + jar.getAbsolutePath() + "\">" + jar.getName() + "</a>" + " to <a href=\"open file " + workspace.getExportDir().getAbsolutePath() + "\">Export Directory</a>"); } else { int len = target.file.getAbsolutePath().length(); String name = target.name + ": " + jar.getParent().substring(len); console.out.println("exported <a href=\"open file " + jar.getAbsolutePath() + "\">" + jar.getName() + "</a>" + " to <a href=\"open file " + jar.getParent() + "\">" + name + "</a>"); } } if(target instanceof AndroidApp) { String s = ask("create scaffolding? [Y/N] "); if("Y".equalsIgnoreCase(s)) { AndroidApp android = (AndroidApp) target; ScaffoldingGenerator gen = new ScaffoldingGenerator(module, android); gen.setListener(new GeneratorListener() { @Override public void handleEvent(GeneratorEvent event) { console.out.println(event.data); } }); List<File> files = gen.generateScaffolding(); for(File file : files) { int len = target.file.getAbsolutePath().length(); String path = target.file.getAbsolutePath() + "#" + file.getAbsolutePath().substring(len+1); console.out.println(" exported <a href=\"open file " + path + "\">" + file.getName() + "</a>"); } File[] ma = android.getMainActivities(); if(ma.length == 1) { String name = ma[0].getName(); name = name.substring(0, name.length()-5); s = ask("add launch buttons to the '" + name + "' activity? [Y/N] "); if("Y".equalsIgnoreCase(s)) { File layout = gen.generateLaunchButton(ma[0]); if(layout != null) { int len = target.file.getAbsolutePath().length(); String path = target.file.getAbsolutePath() + "#" + ma[0].getAbsolutePath().substring(len+1); console.out.println(" modified activity <a href=\"open file " + path + "\">" + ma[0].getName() + "</a>"); path = target.file.getAbsolutePath() + "#" + layout.getAbsolutePath().substring(len+1); console.out.println(" modified layout <a href=\"open file " + path + "\">" + layout.getName() + "</a>"); } } } } } if(target != null) { console.out.println("export complete\n *** models to be accessed by the client must be publised first ***"); Eclipse.refreshProject(target.name); } } catch(IOException e) { console.err.print(e); } }
protected void run() { Workspace workspace = getWorkspace(); Module module = getModule(); Project target = null; if(hasParam("target")) { target = workspace.getProject(param("target")); if(target == null) { console.err.println(param("target") + " does not exist in the workspace"); return; } } if(target == null) { Project[] projects = workspace.getProjects(Type.Android); if(projects.length == 1) { String s = ask("use \"" + projects[0] + "\" as the target? [Y/N] "); if("Y".equalsIgnoreCase(s)) { target = (AndroidApp) projects[0]; } } else if(projects.length > 1) { Arrays.sort(projects); StringBuilder sb = new StringBuilder(); sb.append(projects.length).append(" Android projects found:"); for(int i = 0; i < projects.length; i++) { sb.append("\n " + i + " - " + projects[i].name); } sb.append("\nselect which to use as the target (0-" + (projects.length - 1) + "), or <Enter> for none "); String s = ask(sb.toString()); try { int i = Integer.parseInt(s); if(i >= 0 && i < projects.length) { target = (AndroidApp) projects[i]; } } catch(Exception e) { // discard } } } try { boolean full = !module.hasModels() || ("Y".equalsIgnoreCase(ask("export the full [P]roject, or just its [M]odels? [P/M] "))); ClientExporter exporter = new ClientExporter(workspace, module); exporter.setFull(full); exporter.includeSource(true); exporter.setTarget(target); File[] jars = exporter.export(); for(File jar : jars) { if(target == null) { console.out.println("exported <a href=\"open file " + jar.getAbsolutePath() + "\">" + jar.getName() + "</a>" + " to <a href=\"open file " + workspace.getExportDir().getAbsolutePath() + "\">Export Directory</a>"); } else { int len = target.file.getAbsolutePath().length(); String name = target.name + ": " + jar.getParent().substring(len); console.out.println("exported <a href=\"open file " + jar.getAbsolutePath() + "\">" + jar.getName() + "</a>" + " to <a href=\"open file " + jar.getParent() + "\">" + name + "</a>"); } } if(target instanceof AndroidApp) { String s = ask("create scaffolding? [Y/N] "); if("Y".equalsIgnoreCase(s)) { AndroidApp android = (AndroidApp) target; ScaffoldingGenerator gen = new ScaffoldingGenerator(module, android); gen.setListener(new GeneratorListener() { @Override public void handleEvent(GeneratorEvent event) { console.out.println(event.data); } }); List<File> files = gen.generateScaffolding(); for(File file : files) { int len = target.file.getAbsolutePath().length(); String path = target.file.getAbsolutePath() + "#" + file.getAbsolutePath().substring(len+1); console.out.println(" exported <a href=\"open file " + path + "\">" + file.getName() + "</a>"); } File[] ma = android.getMainActivities(); if(ma.length == 1) { String name = ma[0].getName(); name = name.substring(0, name.length()-5); s = ask("add launch buttons to the '" + name + "' activity? [Y/N] "); if("Y".equalsIgnoreCase(s)) { File layout = gen.generateLaunchButton(ma[0]); if(layout != null) { int len = target.file.getAbsolutePath().length(); String path = target.file.getAbsolutePath() + "#" + ma[0].getAbsolutePath().substring(len+1); console.out.println(" modified activity <a href=\"open file " + path + "\">" + ma[0].getName() + "</a>"); path = target.file.getAbsolutePath() + "#" + layout.getAbsolutePath().substring(len+1); console.out.println(" modified layout <a href=\"open file " + path + "\">" + layout.getName() + "</a>"); } } } } } if(target != null) { console.out.println("export complete\n *** models to be accessed by the client must be published first ***"); Eclipse.refreshProject(target.name); } } catch(IOException e) { console.err.print(e); } }
diff --git a/hazelcast/src/main/java/com/hazelcast/impl/CMap.java b/hazelcast/src/main/java/com/hazelcast/impl/CMap.java index fb675411..8ab64f84 100644 --- a/hazelcast/src/main/java/com/hazelcast/impl/CMap.java +++ b/hazelcast/src/main/java/com/hazelcast/impl/CMap.java @@ -1,1761 +1,1764 @@ /* * Copyright (c) 2008-2010, Hazel Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hazelcast.impl; import com.hazelcast.cluster.ClusterImpl; import com.hazelcast.config.MapConfig; import com.hazelcast.config.MapStoreConfig; import com.hazelcast.config.MergePolicyConfig; import com.hazelcast.config.NearCacheConfig; import com.hazelcast.core.*; import com.hazelcast.impl.base.DistributedLock; import com.hazelcast.impl.base.ScheduledAction; import com.hazelcast.impl.concurrentmap.LFUMapEntryComparator; import com.hazelcast.impl.concurrentmap.LRUMapEntryComparator; import com.hazelcast.impl.concurrentmap.MapStoreWrapper; import com.hazelcast.impl.concurrentmap.MultiData; import com.hazelcast.logging.ILogger; import com.hazelcast.merge.MergePolicy; import com.hazelcast.nio.*; import com.hazelcast.query.Expression; import com.hazelcast.query.MapIndexService; import com.hazelcast.util.SortedHashMap; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import static com.hazelcast.core.Prefix.AS_LIST; import static com.hazelcast.core.Prefix.AS_SET; import static com.hazelcast.impl.ClusterOperation.*; import static com.hazelcast.impl.Constants.Objects.OBJECT_REDO; import static com.hazelcast.nio.IOUtil.toData; import static com.hazelcast.nio.IOUtil.toObject; public class CMap { private static final Comparator<MapEntry> LRU_COMPARATOR = new LRUMapEntryComparator(); private static final Comparator<MapEntry> LFU_COMPARATOR = new LFUMapEntryComparator(); enum EvictionPolicy { LRU, LFU, NONE } enum CleanupState { NONE, SHOULD_CLEAN, CLEANING } public final static int DEFAULT_MAP_SIZE = 10000; final ILogger logger; final ConcurrentMapManager concurrentMapManager; final Node node; final int PARTITION_COUNT; final Block[] blocks; final Address thisAddress; final ConcurrentMap<Data, Record> mapRecords = new ConcurrentHashMap<Data, Record>(10000, 0.75f, 1); final String name; final Map<Address, Boolean> mapListeners = new HashMap<Address, Boolean>(1); final int backupCount; final EvictionPolicy evictionPolicy; final Comparator<MapEntry> evictionComparator; final int maxSize; final float evictionRate; final long ttl; //ttl for entries final long maxIdle; //maxIdle for entries final Instance.InstanceType instanceType; final MapLoader loader; final MapStore store; final MergePolicy mergePolicy; final long writeDelayMillis; final long removeDelayMillis; final long evictionDelayMillis; final MapIndexService mapIndexService; final MapNearCache mapNearCache; final long creationTime; final boolean readBackupData; final boolean cacheValue; volatile boolean ttlPerRecord = false; volatile long lastEvictionTime = 0; DistributedLock lockEntireMap = null; CleanupState cleanupState = CleanupState.NONE; CMap(ConcurrentMapManager concurrentMapManager, String name) { this.concurrentMapManager = concurrentMapManager; this.logger = concurrentMapManager.node.getLogger(CMap.class.getName()); this.PARTITION_COUNT = concurrentMapManager.PARTITION_COUNT; this.blocks = concurrentMapManager.blocks; this.node = concurrentMapManager.node; this.thisAddress = concurrentMapManager.thisAddress; this.name = name; + instanceType = ConcurrentMapManager.getInstanceType(name); MapConfig mapConfig = null; String mapConfigName = name.substring(2); - if (mapConfigName.startsWith("__hz_") || mapConfigName.startsWith(AS_LIST) || mapConfigName.startsWith(AS_SET)) { + if (isMultiMap() + || mapConfigName.startsWith("__hz_") + || mapConfigName.startsWith(AS_LIST) + || mapConfigName.startsWith(AS_SET)) { mapConfig = new MapConfig(); } else { mapConfig = node.getConfig().getMapConfig(mapConfigName); } this.mapIndexService = new MapIndexService(mapConfig.isValueIndexed()); this.backupCount = mapConfig.getBackupCount(); ttl = mapConfig.getTimeToLiveSeconds() * 1000L; evictionDelayMillis = mapConfig.getEvictionDelaySeconds() * 1000L; maxIdle = mapConfig.getMaxIdleSeconds() * 1000L; evictionPolicy = EvictionPolicy.valueOf(mapConfig.getEvictionPolicy()); readBackupData = mapConfig.isReadBackupData(); cacheValue = mapConfig.isCacheValue(); if (evictionPolicy == EvictionPolicy.NONE) { maxSize = Integer.MAX_VALUE; evictionComparator = null; } else { maxSize = (mapConfig.getMaxSize() == 0) ? MapConfig.DEFAULT_MAX_SIZE : mapConfig.getMaxSize(); if (evictionPolicy == EvictionPolicy.LRU) { evictionComparator = new ComparatorWrapper(LRU_COMPARATOR); } else { evictionComparator = new ComparatorWrapper(LFU_COMPARATOR); } } evictionRate = mapConfig.getEvictionPercentage() / 100f; - instanceType = ConcurrentMapManager.getInstanceType(name); MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig(); MapStoreWrapper mapStoreWrapper = null; int writeDelaySeconds = -1; if (!node.isSuperClient() && mapStoreConfig != null && mapStoreConfig.isEnabled()) { try { Object storeInstance = mapStoreConfig.getImplementation(); if (storeInstance == null) { String mapStoreClassName = mapStoreConfig.getClassName(); storeInstance = Serializer.classForName(node.getConfig().getClassLoader(), mapStoreClassName).newInstance(); } mapStoreWrapper = new MapStoreWrapper(storeInstance, node.factory.getHazelcastInstanceProxy(), mapStoreConfig.getProperties(), mapConfigName); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds(); } writeDelayMillis = (writeDelaySeconds == -1) ? -1L : writeDelaySeconds * 1000L; if (writeDelaySeconds > 0) { removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS + writeDelaySeconds; } else { removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS; } loader = (mapStoreWrapper == null || !mapStoreWrapper.isMapLoader()) ? null : mapStoreWrapper; store = (mapStoreWrapper == null || !mapStoreWrapper.isMapStore()) ? null : mapStoreWrapper; NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig(); if (nearCacheConfig == null) { mapNearCache = null; } else { MapNearCache mapNearCache = new MapNearCache(this, SortedHashMap.getOrderingTypeByName(nearCacheConfig.getEvictionPolicy()), nearCacheConfig.getMaxSize(), nearCacheConfig.getTimeToLiveSeconds() * 1000L, nearCacheConfig.getMaxIdleSeconds() * 1000L, nearCacheConfig.isInvalidateOnChange()); final MapNearCache anotherMapNearCache = concurrentMapManager.mapCaches.putIfAbsent(name, mapNearCache); if (anotherMapNearCache != null) { mapNearCache = anotherMapNearCache; } this.mapNearCache = mapNearCache; } MergePolicy mergePolicyTemp = null; String mergePolicyName = mapConfig.getMergePolicy(); if (mergePolicyName != null && !"hz.NO_MERGE".equalsIgnoreCase(mergePolicyName)) { MergePolicyConfig mergePolicyConfig = node.getConfig().getMergePolicyConfig(mapConfig.getMergePolicy()); if (mergePolicyConfig != null) { mergePolicyTemp = mergePolicyConfig.getImplementation(); if (mergePolicyTemp == null) { String mergeClassName = mergePolicyConfig.getClassName(); try { mergePolicyTemp = (MergePolicy) Serializer.classForName(node.getConfig().getClassLoader(), mergeClassName).newInstance(); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } } } } this.mergePolicy = mergePolicyTemp; this.creationTime = System.currentTimeMillis(); } boolean isUserMap() { return !name.startsWith("c:__hz_"); } final boolean isNotLocked(Request request) { return (lockEntireMap == null || !lockEntireMap.isLocked() || lockEntireMap.isLockedBy(request.lockAddress, request.lockThreadId)); } final boolean exceedingMapMaxSize(Request request) { int perJVMMaxSize = maxSize / concurrentMapManager.getMembers().size(); if (perJVMMaxSize <= mapIndexService.size()) { boolean addOp = (request.operation == ClusterOperation.CONCURRENT_MAP_PUT) || (request.operation == ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT); if (addOp) { Record record = getRecord(request); if (record == null) { if (cleanupState == CleanupState.NONE) { cleanupState = CleanupState.SHOULD_CLEAN; } return true; } } } return false; } public void lockMap(Request request) { if (request.operation == CONCURRENT_MAP_LOCK_MAP) { if (lockEntireMap == null) { lockEntireMap = new DistributedLock(); } boolean locked = lockEntireMap.lock(request.lockAddress, request.lockThreadId); boolean isTimeOut = request.timeout == 0; request.clearForResponse(); if (!locked) { if (isTimeOut) { request.response = Boolean.FALSE; } else { request.response = OBJECT_REDO; } } else { request.response = Boolean.TRUE; } } else if (request.operation == CONCURRENT_MAP_UNLOCK_MAP) { if (lockEntireMap != null) { request.response = lockEntireMap.unlock(request.lockAddress, request.lockThreadId); } else { request.response = Boolean.TRUE; } } } public void addIndex(Expression expression, boolean ordered, int attributeIndex) { mapIndexService.addIndex(expression, ordered, attributeIndex); } public Record getRecord(Data key) { return mapRecords.get(key); } public int getBackupCount() { return backupCount; } public void own(Request req) { if (req.key == null || req.key.size() == 0) { throw new RuntimeException("Key cannot be null " + req.key); } if (req.value == null) { if (isSet() || isList()) { req.value = new Data(); } } Record record = toRecord(req); if (req.ttl <= 0 || req.timeout <= 0) { record.setInvalid(); } else { record.setExpirationTime(req.ttl); record.setMaxIdle(req.timeout); } markAsActive(record); if (store != null && writeDelayMillis > 0) { markAsDirty(record); } if (req.value != null) { updateIndexes(record); } record.setVersion(req.version); } public boolean isMultiMap() { return (instanceType == Instance.InstanceType.MULTIMAP); } public boolean isSet() { return (instanceType == Instance.InstanceType.SET); } public boolean isList() { return (instanceType == Instance.InstanceType.LIST); } public boolean isMap() { return (instanceType == Instance.InstanceType.MAP); } public boolean backup(Request req) { if (req.key == null || req.key.size() == 0) { throw new RuntimeException("Backup key size cannot be 0: " + req.key); } if (isMap() || isSet()) { return backupOneValue(req); } else { return backupMultiValue(req); } } /** * Map and Set have one value only so we can ignore the * values with old version. * * @param req * @return */ private boolean backupOneValue(Request req) { Record record = getRecord(req); if (record != null && record.isActive() && req.version < record.getVersion()) { return false; } doBackup(req); if (record != null) { record.setVersion(req.version); } return true; } /** * MultiMap and List have to use versioned backup * because each key can have multiple values and * we don't want to miss backing up each one. * * @param req * @return */ private boolean backupMultiValue(Request req) { Record record = getRecord(req); if (record != null) { record.setActive(); if (req.version > record.getVersion() + 1) { Request reqCopy = req.hardCopy(); record.addBackupOp(new VersionedBackupOp(this, reqCopy)); return true; } else if (req.version <= record.getVersion()) { return false; } } doBackup(req); if (record != null) { record.setVersion(req.version); record.runBackupOps(); } return true; } public void doBackup(Request req) { if (req.key == null || req.key.size() == 0) { throw new RuntimeException("Backup key size cannot be zero! " + req.key); } if (req.operation == CONCURRENT_MAP_BACKUP_PUT) { Record record = toRecord(req); markAsActive(record); record.setVersion(req.version); if (req.indexes != null) { if (req.indexTypes == null) { throw new RuntimeException("index types cannot be null!"); } if (req.indexes.length != req.indexTypes.length) { throw new RuntimeException("index and type lengths do not match"); } record.setIndexes(req.indexes, req.indexTypes); } if (req.ttl > 0 && req.ttl < Long.MAX_VALUE) { record.setExpirationTime(req.ttl); ttlPerRecord = true; } } else if (req.operation == CONCURRENT_MAP_BACKUP_REMOVE) { Record record = getRecord(req); if (record != null) { if (record.isActive()) { if (record.getCopyCount() > 0) { record.decrementCopyCount(); } markAsEvicted(record); } } } else if (req.operation == CONCURRENT_MAP_BACKUP_LOCK) { Record rec = toRecord(req); if (rec.getVersion() == 0) { rec.setVersion(req.version); } if (rec.getLockCount() == 0 && rec.valueCount() == 0) { markAsEvicted(rec); } } else if (req.operation == CONCURRENT_MAP_BACKUP_ADD) { add(req, true); } else if (req.operation == CONCURRENT_MAP_BACKUP_REMOVE_MULTI) { Record record = getRecord(req); if (record != null) { if (req.value == null) { markAsEvicted(record); } else { if (record.containsValue(req.value)) { if (record.getMultiValues() != null) { Iterator<Data> itValues = record.getMultiValues().iterator(); while (itValues.hasNext()) { Data value = itValues.next(); if (req.value.equals(value)) { itValues.remove(); } } } } if (record.valueCount() == 0) { markAsEvicted(record); } } } } else { logger.log(Level.SEVERE, "Unknown backup operation " + req.operation); } } private void purgeIfNotOwnedOrBackup(Collection<Record> records) { Map<Address, Integer> mapMemberDistances = new HashMap<Address, Integer>(); for (Record record : records) { Block block = blocks[record.getBlockId()]; boolean owned = thisAddress.equals(block.getOwner()); if (!owned && !block.isMigrating()) { Address owner = (block.isMigrating()) ? block.getMigrationAddress() : block.getOwner(); if (owner != null && !thisAddress.equals(owner)) { int distance; Integer d = mapMemberDistances.get(owner); if (d == null) { distance = concurrentMapManager.getDistance(owner, thisAddress); mapMemberDistances.put(owner, distance); } else { distance = d; } if (distance > getBackupCount()) { mapRecords.remove(record.getKeyData()); } } } } } Record getOwnedRecord(Data key) { PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(concurrentMapManager.getBlockId(key)); Member ownerNow = partition.getOwner(); if (ownerNow != null && !partition.isMigrating() && ownerNow.localMember()) { return getRecord(key); } return null; } boolean isBackup(Record record) { PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId()); Member ownerNow = partition.getOwner(); Member ownerEventual = partition.getEventualOwner(); if (ownerEventual != null && ownerNow != null && !ownerNow.localMember()) { int distance = node.getClusterImpl().getDistanceFrom(ownerEventual); return (distance != -1 && distance <= getBackupCount()); } return false; } public int size() { if (maxIdle > 0 || ttl > 0 || ttlPerRecord || isList() || isMultiMap()) { long now = System.currentTimeMillis(); int size = 0; Collection<Record> records = mapIndexService.getOwnedRecords(); for (Record record : records) { if (record.isActive() && record.isValid(now)) { size += record.valueCount(); } } return size; } else { return mapIndexService.size(); } } public boolean hasOwned(long blockId) { Collection<Record> records = mapRecords.values(); for (Record record : records) { if (record.getBlockId() == blockId && record.isActive()) { return true; } } return false; } public int valueCount(Data key) { long now = System.currentTimeMillis(); int count = 0; Record record = mapRecords.get(key); if (record != null && record.isValid(now)) { count = record.valueCount(); } return count; } public boolean contains(Request req) { Data key = req.key; Data value = req.value; if (key != null) { Record record = getRecord(req); if (record == null) { return false; } else { if (record.isActive() && record.isValid()) { if (value == null) { return record.valueCount() > 0; } else { return record.containsValue(value); } } } } else { Collection<Record> records = mapRecords.values(); for (Record record : records) { long now = System.currentTimeMillis(); if (record.isActive() && record.isValid(now)) { Block block = blocks[record.getBlockId()]; if (thisAddress.equals(block.getOwner())) { if (record.containsValue(value)) { return true; } } } } } return false; } public void containsValue(Request request) { if (isMultiMap()) { boolean found = false; Collection<Record> records = mapRecords.values(); for (Record record : records) { long now = System.currentTimeMillis(); if (record.isActive() && record.isValid(now)) { Block block = blocks[record.getBlockId()]; if (thisAddress.equals(block.getOwner())) { if (record.containsValue(request.value)) { found = true; } } } } request.response = found; } else { request.response = mapIndexService.containsValue(request.value); } } public CMapEntry getMapEntry(Request req) { Record record = getRecord(req); if (record == null || !record.isActive() || !record.isValid()) { return null; } return new CMapEntry(record.getCost(), record.getExpirationTime(), record.getLastAccessTime(), record.getLastUpdateTime(), record.getCreationTime(), record.getVersion(), record.getHits(), true); } public Data get(Request req) { Record record = getRecord(req); if (record == null) return null; if (!record.isActive()) return null; if (!record.isValid()) { if (record.isEvictable()) { return null; } } record.setLastAccessed(); Data data = record.getValueData(); Data returnValue = null; if (data != null) { returnValue = data; } else { if (record.getMultiValues() != null) { Values values = new Values(record.getMultiValues()); returnValue = toData(values); } } return returnValue; } public boolean add(Request req, boolean backup) { Record record = getRecord(req); if (record == null) { record = toRecord(req); } else { if (record.isActive() && req.operation == CONCURRENT_MAP_ADD_TO_SET) { return false; } } record.setActive(true); record.incrementVersion(); record.incrementCopyCount(); if (!backup) { updateIndexes(record); concurrentMapManager.fireMapEvent(mapListeners, EntryEvent.TYPE_ADDED, null, record, req.caller); } return true; } void lock(Request request) { Data reqValue = request.value; request.value = null; Record rec = concurrentMapManager.ensureRecord(request); if (request.operation == CONCURRENT_MAP_LOCK_AND_GET_VALUE) { if (reqValue == null) { request.value = rec.getValueData(); if (rec.getMultiValues() != null) { Values values = new Values(rec.getMultiValues()); request.value = toData(values); } } else { // multimap txn put operation if (!rec.containsValue(reqValue)) { request.value = null; } else { request.value = reqValue; } } } rec.lock(request.lockThreadId, request.lockAddress); rec.incrementVersion(); request.version = rec.getVersion(); request.lockCount = rec.getLockCount(); markAsActive(rec); request.response = Boolean.TRUE; } void unlock(Record record) { record.clearLock(); fireScheduledActions(record); } void fireScheduledActions(Record record) { concurrentMapManager.checkServiceThread(); if (record.getLockCount() == 0) { record.clearLock(); while (record.hasScheduledAction()) { ScheduledAction sa = record.getScheduledActions().remove(0); node.clusterManager.deregisterScheduledAction(sa); if (!sa.expired()) { sa.consume(); if (record.isLocked()) { return; } } else { sa.onExpire(); } } } } public void onMigrate(Record record) { if (record == null) return; List<ScheduledAction> lsScheduledActions = record.getScheduledActions(); if (lsScheduledActions != null) { if (lsScheduledActions.size() > 0) { Iterator<ScheduledAction> it = lsScheduledActions.iterator(); while (it.hasNext()) { ScheduledAction sa = it.next(); if (sa.isValid() && !sa.expired()) { sa.onMigrate(); } sa.setValid(false); node.clusterManager.deregisterScheduledAction(sa); it.remove(); } } } } public void onDisconnect(Record record, Address deadAddress) { if (record == null || deadAddress == null) return; List<ScheduledAction> lsScheduledActions = record.getScheduledActions(); if (lsScheduledActions != null) { if (lsScheduledActions.size() > 0) { Iterator<ScheduledAction> it = lsScheduledActions.iterator(); while (it.hasNext()) { ScheduledAction sa = it.next(); if (deadAddress.equals(sa.getRequest().caller)) { node.clusterManager.deregisterScheduledAction(sa); sa.setValid(false); it.remove(); } } } } if (record.getLockCount() > 0) { if (deadAddress.equals(record.getLockAddress())) { unlock(record); } } } public boolean removeMulti(Request req) { Record record = getRecord(req); if (record == null) return false; boolean removed = false; if (req.value == null) { removed = true; markAsRemoved(record); } else { if (record.containsValue(req.value)) { if (record.getMultiValues() != null) { Iterator<Data> itValues = record.getMultiValues().iterator(); while (itValues.hasNext()) { Data value = itValues.next(); if (req.value.equals(value)) { itValues.remove(); removed = true; } } } } } if (req.txnId != -1) { unlock(record); } if (removed) { record.incrementVersion(); concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_REMOVED, record.getKeyData(), null, req.value, record.getListeners(), req.caller); logger.log(Level.FINEST, record.getValueData() + " RemoveMulti " + record.getMultiValues()); } req.version = record.getVersion(); if (record.valueCount() == 0) { markAsRemoved(record); } return removed; } public boolean putMulti(Request req) { Record record = getRecord(req); boolean added = true; if (record == null) { record = toRecord(req); } else { if (!record.isActive()) { markAsActive(record); } if (record.containsValue(req.value)) { added = false; } } if (added) { Data value = req.value; updateIndexes(record); record.addValue(value); record.incrementVersion(); concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_ADDED, record.getKeyData(), null, value, record.getListeners(), req.caller); } if (req.txnId != -1) { unlock(record); } logger.log(Level.FINEST, record.getValueData() + " PutMulti " + record.getMultiValues()); req.clearForResponse(); req.version = record.getVersion(); return added; } public void doAtomic(Request req) { Record record = getRecord(req); if (record == null) { record = createNewRecord(req.key, toData(0L)); mapRecords.put(req.key, record); } if (req.operation == ATOMIC_NUMBER_GET_AND_SET) { req.response = record.getValueData(); record.setValue(toData(req.longValue)); } else if (req.operation == ATOMIC_NUMBER_ADD_AND_GET) { record.setValue(IOUtil.addDelta(record.getValueData(), req.longValue)); req.response = record.getValueData(); } else if (req.operation == ATOMIC_NUMBER_GET_AND_ADD) { req.response = record.getValueData(); record.setValue(IOUtil.addDelta(record.getValueData(), req.longValue)); } else if (req.operation == ATOMIC_NUMBER_COMPARE_AND_SET) { if (record.getValueData().equals(req.value)) { record.setValue(toData(req.longValue)); req.response = Boolean.TRUE; } else { req.response = Boolean.FALSE; } req.value = null; } } public void put(Request req) { long now = System.currentTimeMillis(); if (req.value == null) { req.value = new Data(); } Record record = getRecord(req); if (record != null && !record.isValid(now)) { record.setValue(null); record.setMultiValues(null); } if (req.operation == CONCURRENT_MAP_PUT_IF_ABSENT) { if (record != null && record.isActive() && record.isValid(now) && record.getValueData() != null) { req.clearForResponse(); req.response = record.getValueData(); return; } } else if (req.operation == CONCURRENT_MAP_REPLACE_IF_NOT_NULL) { if (record == null || !record.isActive() || !record.isValid(now) || record.getValueData() == null) { return; } } else if (req.operation == CONCURRENT_MAP_REPLACE_IF_SAME) { if (record == null || !record.isActive() || !record.isValid(now)) { req.response = Boolean.FALSE; return; } MultiData multiData = (MultiData) toObject(req.value); if (multiData == null || multiData.size() != 2) { throw new RuntimeException("Illegal replaceIfSame argument: " + multiData); } Data expectedOldValue = multiData.getData(0); req.value = multiData.getData(1); if (!record.getValueData().equals(expectedOldValue)) { req.response = Boolean.FALSE; return; } } Data oldValue = null; if (record == null) { record = createNewRecord(req.key, req.value); mapRecords.put(req.key, record); } else { markAsActive(record); oldValue = (record.isValid(now)) ? record.getValueData() : null; record.setValue(req.value); record.incrementVersion(); record.setLastUpdated(); } if (req.ttl > 0 && req.ttl < Long.MAX_VALUE) { record.setExpirationTime(req.ttl); ttlPerRecord = true; } if (oldValue == null) { concurrentMapManager.fireMapEvent(mapListeners, EntryEvent.TYPE_ADDED, null, record, req.caller); } else { fireInvalidation(record); concurrentMapManager.fireMapEvent(mapListeners, EntryEvent.TYPE_UPDATED, oldValue, record, req.caller); } if (req.txnId != -1) { unlock(record); } record.setIndexes(req.indexes, req.indexTypes); updateIndexes(record); markAsDirty(record); req.clearForResponse(); req.version = record.getVersion(); req.longValue = record.getCopyCount(); if (req.operation == CONCURRENT_MAP_REPLACE_IF_SAME) { req.response = Boolean.TRUE; } else { req.response = oldValue; } } private void executeStoreUpdate(final Set<Record> dirtyRecords) { if (dirtyRecords.size() > 0) { concurrentMapManager.node.executorManager.executeStoreTask(new Runnable() { public void run() { try { Set<Object> keysToDelete = new HashSet<Object>(); Map<Object, Object> updates = new HashMap<Object, Object>(); for (Record dirtyRecord : dirtyRecords) { if (!dirtyRecord.isActive()) { keysToDelete.add(dirtyRecord.getKey()); } else { updates.put(dirtyRecord.getKey(), dirtyRecord.getValue()); } } if (keysToDelete.size() == 1) { store.delete(keysToDelete.iterator().next()); } else if (keysToDelete.size() > 1) { store.deleteAll(keysToDelete); } if (updates.size() == 1) { Map.Entry entry = updates.entrySet().iterator().next(); store.store(entry.getKey(), entry.getValue()); } else if (updates.size() > 1) { store.storeAll(updates); } } catch (Exception e) { for (Record dirtyRecord : dirtyRecords) { dirtyRecord.setDirty(true); } } } }); } } LocalMapStatsImpl getLocalMapStats() { LocalMapStatsImpl localMapStats = new LocalMapStatsImpl(); long now = System.currentTimeMillis(); long ownedEntryCount = 0; long backupEntryCount = 0; long markedAsRemovedEntryCount = 0; long ownedEntryMemoryCost = 0; long backupEntryMemoryCost = 0; long markedAsRemovedMemoryCost = 0; long hits = 0; long lockedEntryCount = 0; long lockWaitCount = 0; ClusterImpl clusterImpl = node.getClusterImpl(); final Collection<Record> records = mapRecords.values(); final PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; for (Record record : records) { if (!record.isActive() || !record.isValid(now)) { markedAsRemovedEntryCount++; markedAsRemovedMemoryCost += record.getCost(); } else { PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId()); Member owner = partition.getOwner(); if (owner != null && !partition.isMigrating()) { boolean owned = owner.localMember(); if (owned) { ownedEntryCount += record.valueCount(); ownedEntryMemoryCost += record.getCost(); localMapStats.setLastAccessTime(record.getLastAccessTime()); localMapStats.setLastUpdateTime(record.getLastUpdateTime()); hits += record.getHits(); if (record.isLocked()) { lockedEntryCount++; lockWaitCount += record.getScheduledActionCount(); } } else { Member ownerEventual = partition.getEventualOwner(); boolean backup = false; if (ownerEventual != null && !owner.localMember()) { int distance = node.getClusterImpl().getDistanceFrom(ownerEventual, true); backup = (distance != -1 && distance <= getBackupCount()); } if (backup && !shouldPurgeRecord(record, now)) { backupEntryCount += record.valueCount(); backupEntryMemoryCost += record.getCost(); } else { markedAsRemovedEntryCount++; markedAsRemovedMemoryCost += record.getCost(); } } } } } localMapStats.setMarkedAsRemovedEntryCount(zeroOrPositive(markedAsRemovedEntryCount)); localMapStats.setMarkedAsRemovedMemoryCost(zeroOrPositive(markedAsRemovedMemoryCost)); localMapStats.setLockWaitCount(zeroOrPositive(lockWaitCount)); localMapStats.setLockedEntryCount(zeroOrPositive(lockedEntryCount)); localMapStats.setHits(zeroOrPositive(hits)); localMapStats.setOwnedEntryCount(zeroOrPositive(ownedEntryCount)); localMapStats.setBackupEntryCount(zeroOrPositive(backupEntryCount)); localMapStats.setOwnedEntryMemoryCost(zeroOrPositive(ownedEntryMemoryCost)); localMapStats.setBackupEntryMemoryCost(zeroOrPositive(backupEntryMemoryCost)); localMapStats.setLastEvictionTime(zeroOrPositive(clusterImpl.getClusterTimeFor(lastEvictionTime))); localMapStats.setCreationTime(zeroOrPositive(clusterImpl.getClusterTimeFor(creationTime))); return localMapStats; } private static long zeroOrPositive(long value) { return (value > 0) ? value : 0; } /** * Comparator that never returns 0. It is * either 1 or -1; */ class ComparatorWrapper implements Comparator<MapEntry> { final Comparator<MapEntry> comparator; ComparatorWrapper(Comparator<MapEntry> comparator) { this.comparator = comparator; } public int compare(MapEntry o1, MapEntry o2) { int result = comparator.compare(o1, o2); if (result == 0) { Record r1 = (Record) o1; Record r2 = (Record) o2; // we don't want to return 0 here. return (r1.getId() > r2.getId()) ? 1 : -1; } else { return result; } } } void evict(int percentage) { final long now = System.currentTimeMillis(); final Collection<Record> records = mapRecords.values(); Comparator<MapEntry> comparator = evictionComparator; if (comparator == null) { comparator = new ComparatorWrapper(LRU_COMPARATOR); } final PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; final Set<Record> sortedRecords = new TreeSet<Record>(new ComparatorWrapper(comparator)); final Set<Record> recordsToEvict = new HashSet<Record>(); for (Record record : records) { PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId()); Member owner = partition.getOwner(); if (owner != null && !partition.isMigrating()) { boolean owned = owner.localMember(); if (owned) { if (store != null && writeDelayMillis > 0 && record.isDirty()) { } else if (shouldPurgeRecord(record, now)) { } else if (record.isActive() && !record.isValid(now)) { recordsToEvict.add(record); // expired records } else if (record.isActive() && record.isEvictable()) { sortedRecords.add(record); // sorting for eviction } } } } int numberOfRecordsToEvict = sortedRecords.size() * percentage / 100; int evictedCount = 0; for (Record record : sortedRecords) { recordsToEvict.add(record); if (++evictedCount >= numberOfRecordsToEvict) { break; } } executeEviction(recordsToEvict); } void startCleanup(boolean forced) { final long now = System.currentTimeMillis(); if (mapNearCache != null) { mapNearCache.evict(now, false); } final Set<Record> recordsDirty = new HashSet<Record>(); final Set<Record> recordsUnknown = new HashSet<Record>(); final Set<Record> recordsToPurge = new HashSet<Record>(); final Set<Record> recordsToEvict = new HashSet<Record>(); final Set<Record> sortedRecords = new TreeSet<Record>(new ComparatorWrapper(evictionComparator)); final Collection<Record> records = mapRecords.values(); final int clusterMemberSize = node.getClusterImpl().getMembers().size(); final int memberCount = (clusterMemberSize == 0) ? 1 : clusterMemberSize; final int maxSizePerJVM = maxSize / memberCount; final boolean evictionAware = evictionComparator != null && maxSizePerJVM > 0; final PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; int recordsStillOwned = 0; int backupPurgeCount = 0; for (Record record : records) { PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId()); Member owner = partition.getOwner(); if (owner != null && !partition.isMigrating()) { boolean owned = owner.localMember(); if (owned) { if (store != null && writeDelayMillis > 0 && record.isDirty()) { if (now > record.getWriteTime()) { recordsDirty.add(record); record.setDirty(false); } } else if (shouldPurgeRecord(record, now)) { recordsToPurge.add(record); // removed records } else if (record.isActive() && !record.isValid(now)) { recordsToEvict.add(record); // expired records } else if (evictionAware && record.isActive() && record.isEvictable()) { sortedRecords.add(record); // sorting for eviction recordsStillOwned++; } else { recordsStillOwned++; } } else { Member ownerEventual = partition.getEventualOwner(); boolean backup = false; if (ownerEventual != null && owner != null && !owner.localMember()) { int distance = node.getClusterImpl().getDistanceFrom(ownerEventual, true); backup = (distance != -1 && distance <= getBackupCount()); } if (backup) { if (shouldPurgeRecord(record, now)) { recordsToPurge.add(record); backupPurgeCount++; } } else { recordsUnknown.add(record); } } } } if (evictionAware && ((forced) ? maxSizePerJVM <= recordsStillOwned : maxSizePerJVM < recordsStillOwned)) { int numberOfRecordsToEvict = (int) (recordsStillOwned * evictionRate); int evictedCount = 0; for (Record record : sortedRecords) { if (record.isActive() && record.isEvictable()) { recordsToEvict.add(record); if (++evictedCount >= numberOfRecordsToEvict) { break; } } } } Level levelLog = (concurrentMapManager.LOG_STATE) ? Level.INFO : Level.FINEST; logger.log(levelLog, name + " Cleanup " + ", dirty:" + recordsDirty.size() + ", purge:" + recordsToPurge.size() + ", evict:" + recordsToEvict.size() + ", unknown:" + recordsUnknown.size() + ", stillOwned:" + recordsStillOwned + ", backupPurge:" + backupPurgeCount ); executeStoreUpdate(recordsDirty); executeEviction(recordsToEvict); executePurge(recordsToPurge); executePurgeUnknowns(recordsUnknown); } private void executePurgeUnknowns(final Set<Record> recordsUnknown) { if (recordsUnknown.size() > 0) { concurrentMapManager.enqueueAndReturn(new Processable() { public void process() { purgeIfNotOwnedOrBackup(recordsUnknown); } }); } } private void executePurge(final Set<Record> recordsToPurge) { if (recordsToPurge.size() > 0) { concurrentMapManager.enqueueAndReturn(new Processable() { public void process() { final long now = System.currentTimeMillis(); for (Record recordToPurge : recordsToPurge) { if (shouldPurgeRecord(recordToPurge, now)) { removeAndPurgeRecord(recordToPurge); } } } }); } } boolean shouldPurgeRecord(Record record, long now) { return !record.isActive() && shouldRemove(record, now); } private void executeEviction(Collection<Record> lsRecordsToEvict) { if (lsRecordsToEvict != null && lsRecordsToEvict.size() > 0) { logger.log(Level.FINEST, lsRecordsToEvict.size() + " evicting"); for (final Record recordToEvict : lsRecordsToEvict) { concurrentMapManager.evictAsync(recordToEvict.getName(), recordToEvict.getKeyData()); } } } void fireInvalidation(Record record) { if (mapNearCache != null && mapNearCache.shouldInvalidateOnChange()) { for (MemberImpl member : concurrentMapManager.lsMembers) { if (!member.localMember()) { if (member.getAddress() != null) { Packet packet = concurrentMapManager.obtainPacket(); packet.name = getName(); packet.setKey(record.getKeyData()); packet.operation = ClusterOperation.CONCURRENT_MAP_INVALIDATE; boolean sent = concurrentMapManager.send(packet, member.getAddress()); if (!sent) { concurrentMapManager.releasePacket(packet); } } } } mapNearCache.invalidate(record.getKeyData()); } } Record getRecord(Request req) { if (req.record == null || !req.record.isActive()) { req.record = mapRecords.get(req.key); } return req.record; } Record toRecord(Request req) { Record record = getRecord(req); if (record == null) { if (isMultiMap()) { record = createNewRecord(req.key, null); record.addValue(req.value); } else { record = createNewRecord(req.key, req.value); } mapRecords.put(req.key, record); } else { if (req.value != null) { if (isMultiMap()) { record.addValue(req.value); } else { record.setValue(req.value); } } } record.setIndexes(req.indexes, req.indexTypes); record.setCopyCount((int) req.longValue); if (req.lockCount >= 0) { DistributedLock lock = new DistributedLock(req.lockAddress, req.lockThreadId, req.lockCount); record.setLock(lock); } return record; } public boolean removeItem(Request req) { Record record = getRecord(req); if (record == null) { return false; } if (req.txnId != -1) { unlock(record); } boolean removed = false; if (record.getCopyCount() > 0) { record.decrementCopyCount(); removed = true; } else if (record.getValueData() != null) { removed = true; } else if (record.getMultiValues() != null) { removed = true; } if (removed) { concurrentMapManager.fireMapEvent(mapListeners, EntryEvent.TYPE_REMOVED, null, record, req.caller); record.incrementVersion(); } req.version = record.getVersion(); req.longValue = record.getCopyCount(); markAsRemoved(record); return true; } boolean evict(Request req) { Record record = getRecord(req.key); long now = System.currentTimeMillis(); if (record != null && record.isActive() && record.valueCount() > 0) { concurrentMapManager.checkServiceThread(); fireInvalidation(record); concurrentMapManager.fireMapEvent(mapListeners, EntryEvent.TYPE_EVICTED, null, record, req.caller); record.incrementVersion(); markAsEvicted(record); req.clearForResponse(); req.version = record.getVersion(); req.longValue = record.getCopyCount(); lastEvictionTime = now; return true; } return false; } public void remove(Request req) { Record record = getRecord(req); if (record == null) { req.clearForResponse(); return; } if (req.txnId != -1) { unlock(record); } if (!record.isActive()) { return; } if (!record.isValid()) { if (record.isEvictable()) { return; } } if (req.value != null) { if (record.getValueData() != null) { if (!record.getValueData().equals(req.value)) { return; } } } Data oldValue = record.getValueData(); if (oldValue == null && record.getMultiValues() != null && record.getMultiValues().size() > 0) { Values values = new Values(record.getMultiValues()); oldValue = toData(values); } if (oldValue != null) { fireInvalidation(record); concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_REMOVED, record.getKeyData(), null, oldValue, record.getListeners(), req.caller); record.incrementVersion(); } markAsRemoved(record); req.clearForResponse(); req.version = record.getVersion(); req.longValue = record.getCopyCount(); req.response = oldValue; } void reset() { for (Record record : mapRecords.values()) { if (record.hasScheduledAction()) { List<ScheduledAction> lsScheduledActions = record.getScheduledActions(); if (lsScheduledActions != null) { for (ScheduledAction scheduledAction : lsScheduledActions) { scheduledAction.setValid(false); } } } } if (mapNearCache != null) { mapNearCache.reset(); } mapRecords.clear(); mapIndexService.clear(); if (store != null && store instanceof MapStoreWrapper) { try { ((MapStoreWrapper) store).destroy(); } catch (Exception e) { e.printStackTrace(); } } } void markAsDirty(Record record) { if (!record.isDirty()) { record.setDirty(true); if (writeDelayMillis > 0) { record.setWriteTime(System.currentTimeMillis() + writeDelayMillis); } } } void markAsActive(Record record) { long now = System.currentTimeMillis(); if (!record.isActive() || !record.isValid(now)) { record.setActive(); record.setCreationTime(now); record.setExpirationTime(ttl); } } boolean shouldRemove(Record record, long now) { return record.isRemovable() && ((now - record.getRemoveTime()) > removeDelayMillis); } void markAsRemoved(Record record) { if (record.isActive()) { record.markRemoved(); } record.setValue(null); record.setMultiValues(null); updateIndexes(record); markAsDirty(record); } /** * same as markAsRemoved but it doesn't * mark the entry as 'dirty' because * inactive and dirty records are deleted * from mapStore * * @param record */ void markAsEvicted(Record record) { if (record.isActive()) { record.markRemoved(); } record.setValue(null); record.setMultiValues(null); updateIndexes(record); } void removeAndPurgeRecord(Record record) { mapRecords.remove(record.getKeyData()); mapIndexService.remove(record); } void updateIndexes(Record record) { mapIndexService.index(record); } Record createNewRecord(Data key, Data value) { if (key == null || key.size() == 0) { throw new RuntimeException("Cannot create record from a 0 size key: " + key); } int blockId = concurrentMapManager.getBlockId(key); return new Record(this, blockId, key, value, ttl, maxIdle, concurrentMapManager.newRecordId()); } public void addListener(Data key, Address address, boolean includeValue) { if (key == null || key.size() == 0) { mapListeners.put(address, includeValue); } else { Record rec = getRecord(key); if (rec == null) { rec = createNewRecord(key, null); mapRecords.put(key, rec); } rec.addListener(address, includeValue); } } public void removeListener(Data key, Address address) { if (key == null || key.size() == 0) { mapListeners.remove(address); } else { Record rec = getRecord(key); if (rec != null) { rec.removeListener(address); } } } public void appendState(StringBuffer sbState) { sbState.append("\nCMap ["); sbState.append(name); sbState.append("] r:"); sbState.append(mapRecords.size()); if (mapNearCache != null) { mapNearCache.appendState(sbState); } mapIndexService.appendState(sbState); } public static class Values implements Collection, DataSerializable { Collection<Data> lsValues = null; public Values() { } public Values(Collection<Data> lsValues) { super(); this.lsValues = lsValues; } public boolean add(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean contains(Object o) { if (o == null) { throw new IllegalArgumentException("Contains cannot have null argument."); } Iterator it = iterator(); while (it.hasNext()) { Object v = it.next(); if (o.equals(v)) { return true; } } return false; } public boolean containsAll(Collection c) { throw new UnsupportedOperationException(); } public boolean isEmpty() { return (size() == 0); } public Iterator iterator() { return new ValueIterator(lsValues.iterator()); } class ValueIterator implements Iterator { final Iterator<Data> it; public ValueIterator(Iterator<Data> it) { super(); this.it = it; } public boolean hasNext() { return it.hasNext(); } public Object next() { Data value = it.next(); return toObject(value); } public void remove() { it.remove(); } } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public int size() { return (lsValues == null) ? 0 : lsValues.size(); } public Object[] toArray() { if (size() == 0) { return null; } return toArray(new Object[size()]); } public Object[] toArray(Object[] a) { int size = size(); if (size == 0) { return null; } if (a == null || a.length < size) { a = new Object[size]; } Iterator<Data> it = lsValues.iterator(); int index = 0; while (it.hasNext()) { a[index++] = toObject(it.next()); } return a; } public void readData(DataInput in) throws IOException { int size = in.readInt(); lsValues = new ArrayList<Data>(size); for (int i = 0; i < size; i++) { Data data = new Data(); data.readData(in); lsValues.add(data); } } public void writeData(DataOutput out) throws IOException { int size = (lsValues == null) ? 0 : lsValues.size(); out.writeInt(size); if (size > 0) { for (Data data : lsValues) { data.writeData(out); } } } } public static class CMapEntry implements HazelcastInstanceAware, MapEntry, DataSerializable { private long cost = 0; private long expirationTime = 0; private long lastAccessTime = 0; private long lastUpdateTime = 0; private long creationTime = 0; private long version = 0; private int hits = 0; private boolean valid = true; private String name = null; private Object key = null; private Object value = null; private HazelcastInstance hazelcastInstance = null; public CMapEntry() { } public CMapEntry(long cost, long expirationTime, long lastAccessTime, long lastUpdateTime, long creationTime, long version, int hits, boolean valid) { this.cost = cost; this.expirationTime = expirationTime; this.lastAccessTime = lastAccessTime; this.lastUpdateTime = lastUpdateTime; this.creationTime = creationTime; this.version = version; this.hits = hits; this.valid = valid; } public void writeData(DataOutput out) throws IOException { out.writeLong(cost); out.writeLong(expirationTime); out.writeLong(lastAccessTime); out.writeLong(lastUpdateTime); out.writeLong(creationTime); out.writeLong(version); out.writeInt(hits); out.writeBoolean(valid); } public void readData(DataInput in) throws IOException { cost = in.readLong(); expirationTime = in.readLong(); lastAccessTime = in.readLong(); lastUpdateTime = in.readLong(); creationTime = in.readLong(); version = in.readLong(); hits = in.readInt(); valid = in.readBoolean(); } public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } public void set(String name, Object key) { this.name = name; this.key = key; } public long getCost() { return cost; } public long getCreationTime() { return creationTime; } public long getExpirationTime() { return expirationTime; } public long getLastUpdateTime() { return lastUpdateTime; } public int getHits() { return hits; } public long getLastAccessTime() { return lastAccessTime; } public long getVersion() { return version; } public boolean isValid() { return valid; } public Object getKey() { return key; } public Object getValue() { if (value == null) { FactoryImpl factory = (FactoryImpl) hazelcastInstance; value = ((MProxy) factory.getOrCreateProxyByName(name)).get(key); } return value; } public Object setValue(Object value) { Object oldValue = this.value; FactoryImpl factory = (FactoryImpl) hazelcastInstance; ((MProxy) factory.getOrCreateProxyByName(name)).put(key, value); return oldValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CMapEntry cMapEntry = (CMapEntry) o; return !(key != null ? !key.equals(cMapEntry.key) : cMapEntry.key != null) && !(name != null ? !name.equals(cMapEntry.name) : cMapEntry.name != null); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (key != null ? key.hashCode() : 0); return result; } @Override public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("MapEntry"); sb.append("{key=").append(key); sb.append(", valid=").append(valid); sb.append(", hits=").append(hits); sb.append(", version=").append(version); sb.append(", creationTime=").append(creationTime); sb.append(", lastUpdateTime=").append(lastUpdateTime); sb.append(", lastAccessTime=").append(lastAccessTime); sb.append(", expirationTime=").append(expirationTime); sb.append(", cost=").append(cost); sb.append('}'); return sb.toString(); } } @Override public String toString() { return "CMap [" + getName() + "] size=" + size(); } /** * @return the name */ public String getName() { return name; } public MapIndexService getMapIndexService() { return mapIndexService; } }
false
true
CMap(ConcurrentMapManager concurrentMapManager, String name) { this.concurrentMapManager = concurrentMapManager; this.logger = concurrentMapManager.node.getLogger(CMap.class.getName()); this.PARTITION_COUNT = concurrentMapManager.PARTITION_COUNT; this.blocks = concurrentMapManager.blocks; this.node = concurrentMapManager.node; this.thisAddress = concurrentMapManager.thisAddress; this.name = name; MapConfig mapConfig = null; String mapConfigName = name.substring(2); if (mapConfigName.startsWith("__hz_") || mapConfigName.startsWith(AS_LIST) || mapConfigName.startsWith(AS_SET)) { mapConfig = new MapConfig(); } else { mapConfig = node.getConfig().getMapConfig(mapConfigName); } this.mapIndexService = new MapIndexService(mapConfig.isValueIndexed()); this.backupCount = mapConfig.getBackupCount(); ttl = mapConfig.getTimeToLiveSeconds() * 1000L; evictionDelayMillis = mapConfig.getEvictionDelaySeconds() * 1000L; maxIdle = mapConfig.getMaxIdleSeconds() * 1000L; evictionPolicy = EvictionPolicy.valueOf(mapConfig.getEvictionPolicy()); readBackupData = mapConfig.isReadBackupData(); cacheValue = mapConfig.isCacheValue(); if (evictionPolicy == EvictionPolicy.NONE) { maxSize = Integer.MAX_VALUE; evictionComparator = null; } else { maxSize = (mapConfig.getMaxSize() == 0) ? MapConfig.DEFAULT_MAX_SIZE : mapConfig.getMaxSize(); if (evictionPolicy == EvictionPolicy.LRU) { evictionComparator = new ComparatorWrapper(LRU_COMPARATOR); } else { evictionComparator = new ComparatorWrapper(LFU_COMPARATOR); } } evictionRate = mapConfig.getEvictionPercentage() / 100f; instanceType = ConcurrentMapManager.getInstanceType(name); MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig(); MapStoreWrapper mapStoreWrapper = null; int writeDelaySeconds = -1; if (!node.isSuperClient() && mapStoreConfig != null && mapStoreConfig.isEnabled()) { try { Object storeInstance = mapStoreConfig.getImplementation(); if (storeInstance == null) { String mapStoreClassName = mapStoreConfig.getClassName(); storeInstance = Serializer.classForName(node.getConfig().getClassLoader(), mapStoreClassName).newInstance(); } mapStoreWrapper = new MapStoreWrapper(storeInstance, node.factory.getHazelcastInstanceProxy(), mapStoreConfig.getProperties(), mapConfigName); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds(); } writeDelayMillis = (writeDelaySeconds == -1) ? -1L : writeDelaySeconds * 1000L; if (writeDelaySeconds > 0) { removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS + writeDelaySeconds; } else { removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS; } loader = (mapStoreWrapper == null || !mapStoreWrapper.isMapLoader()) ? null : mapStoreWrapper; store = (mapStoreWrapper == null || !mapStoreWrapper.isMapStore()) ? null : mapStoreWrapper; NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig(); if (nearCacheConfig == null) { mapNearCache = null; } else { MapNearCache mapNearCache = new MapNearCache(this, SortedHashMap.getOrderingTypeByName(nearCacheConfig.getEvictionPolicy()), nearCacheConfig.getMaxSize(), nearCacheConfig.getTimeToLiveSeconds() * 1000L, nearCacheConfig.getMaxIdleSeconds() * 1000L, nearCacheConfig.isInvalidateOnChange()); final MapNearCache anotherMapNearCache = concurrentMapManager.mapCaches.putIfAbsent(name, mapNearCache); if (anotherMapNearCache != null) { mapNearCache = anotherMapNearCache; } this.mapNearCache = mapNearCache; } MergePolicy mergePolicyTemp = null; String mergePolicyName = mapConfig.getMergePolicy(); if (mergePolicyName != null && !"hz.NO_MERGE".equalsIgnoreCase(mergePolicyName)) { MergePolicyConfig mergePolicyConfig = node.getConfig().getMergePolicyConfig(mapConfig.getMergePolicy()); if (mergePolicyConfig != null) { mergePolicyTemp = mergePolicyConfig.getImplementation(); if (mergePolicyTemp == null) { String mergeClassName = mergePolicyConfig.getClassName(); try { mergePolicyTemp = (MergePolicy) Serializer.classForName(node.getConfig().getClassLoader(), mergeClassName).newInstance(); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } } } } this.mergePolicy = mergePolicyTemp; this.creationTime = System.currentTimeMillis(); }
CMap(ConcurrentMapManager concurrentMapManager, String name) { this.concurrentMapManager = concurrentMapManager; this.logger = concurrentMapManager.node.getLogger(CMap.class.getName()); this.PARTITION_COUNT = concurrentMapManager.PARTITION_COUNT; this.blocks = concurrentMapManager.blocks; this.node = concurrentMapManager.node; this.thisAddress = concurrentMapManager.thisAddress; this.name = name; instanceType = ConcurrentMapManager.getInstanceType(name); MapConfig mapConfig = null; String mapConfigName = name.substring(2); if (isMultiMap() || mapConfigName.startsWith("__hz_") || mapConfigName.startsWith(AS_LIST) || mapConfigName.startsWith(AS_SET)) { mapConfig = new MapConfig(); } else { mapConfig = node.getConfig().getMapConfig(mapConfigName); } this.mapIndexService = new MapIndexService(mapConfig.isValueIndexed()); this.backupCount = mapConfig.getBackupCount(); ttl = mapConfig.getTimeToLiveSeconds() * 1000L; evictionDelayMillis = mapConfig.getEvictionDelaySeconds() * 1000L; maxIdle = mapConfig.getMaxIdleSeconds() * 1000L; evictionPolicy = EvictionPolicy.valueOf(mapConfig.getEvictionPolicy()); readBackupData = mapConfig.isReadBackupData(); cacheValue = mapConfig.isCacheValue(); if (evictionPolicy == EvictionPolicy.NONE) { maxSize = Integer.MAX_VALUE; evictionComparator = null; } else { maxSize = (mapConfig.getMaxSize() == 0) ? MapConfig.DEFAULT_MAX_SIZE : mapConfig.getMaxSize(); if (evictionPolicy == EvictionPolicy.LRU) { evictionComparator = new ComparatorWrapper(LRU_COMPARATOR); } else { evictionComparator = new ComparatorWrapper(LFU_COMPARATOR); } } evictionRate = mapConfig.getEvictionPercentage() / 100f; MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig(); MapStoreWrapper mapStoreWrapper = null; int writeDelaySeconds = -1; if (!node.isSuperClient() && mapStoreConfig != null && mapStoreConfig.isEnabled()) { try { Object storeInstance = mapStoreConfig.getImplementation(); if (storeInstance == null) { String mapStoreClassName = mapStoreConfig.getClassName(); storeInstance = Serializer.classForName(node.getConfig().getClassLoader(), mapStoreClassName).newInstance(); } mapStoreWrapper = new MapStoreWrapper(storeInstance, node.factory.getHazelcastInstanceProxy(), mapStoreConfig.getProperties(), mapConfigName); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds(); } writeDelayMillis = (writeDelaySeconds == -1) ? -1L : writeDelaySeconds * 1000L; if (writeDelaySeconds > 0) { removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS + writeDelaySeconds; } else { removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS; } loader = (mapStoreWrapper == null || !mapStoreWrapper.isMapLoader()) ? null : mapStoreWrapper; store = (mapStoreWrapper == null || !mapStoreWrapper.isMapStore()) ? null : mapStoreWrapper; NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig(); if (nearCacheConfig == null) { mapNearCache = null; } else { MapNearCache mapNearCache = new MapNearCache(this, SortedHashMap.getOrderingTypeByName(nearCacheConfig.getEvictionPolicy()), nearCacheConfig.getMaxSize(), nearCacheConfig.getTimeToLiveSeconds() * 1000L, nearCacheConfig.getMaxIdleSeconds() * 1000L, nearCacheConfig.isInvalidateOnChange()); final MapNearCache anotherMapNearCache = concurrentMapManager.mapCaches.putIfAbsent(name, mapNearCache); if (anotherMapNearCache != null) { mapNearCache = anotherMapNearCache; } this.mapNearCache = mapNearCache; } MergePolicy mergePolicyTemp = null; String mergePolicyName = mapConfig.getMergePolicy(); if (mergePolicyName != null && !"hz.NO_MERGE".equalsIgnoreCase(mergePolicyName)) { MergePolicyConfig mergePolicyConfig = node.getConfig().getMergePolicyConfig(mapConfig.getMergePolicy()); if (mergePolicyConfig != null) { mergePolicyTemp = mergePolicyConfig.getImplementation(); if (mergePolicyTemp == null) { String mergeClassName = mergePolicyConfig.getClassName(); try { mergePolicyTemp = (MergePolicy) Serializer.classForName(node.getConfig().getClassLoader(), mergeClassName).newInstance(); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } } } } this.mergePolicy = mergePolicyTemp; this.creationTime = System.currentTimeMillis(); }
diff --git a/UtahGreekFestival/src/com/saltlakegreekfestival/utahgreekfestival/AdFragment.java b/UtahGreekFestival/src/com/saltlakegreekfestival/utahgreekfestival/AdFragment.java index c64160b..b17131f 100644 --- a/UtahGreekFestival/src/com/saltlakegreekfestival/utahgreekfestival/AdFragment.java +++ b/UtahGreekFestival/src/com/saltlakegreekfestival/utahgreekfestival/AdFragment.java @@ -1,97 +1,99 @@ package com.saltlakegreekfestival.utahgreekfestival; import java.io.File; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class AdFragment extends Fragment { Drawable myImage = null; File imageFile = null; String URL = null; //int myImageId = R.drawable.roofers; int myImageId = 0; String TAG = "AdFragment"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.adfragmentlayout, null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.v(TAG,"Created ImageId: "+String.valueOf(myImageId)); ImageView image = (ImageView)this.getView().findViewById(R.id.advertimage); if(imageFile != null) image.setImageBitmap(BitmapFactory.decodeFile(imageFile.getPath())); else { - this.myImage = this.getActivity().getResources().getDrawable(myImageId); - image.setImageDrawable(this.myImage); + if(myImageId > 0){ + this.myImage = this.getActivity().getResources().getDrawable(myImageId); + image.setImageDrawable(this.myImage); + } } if(URL != null){ image.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(URL)); startActivity(intent); } }); } } public AdFragment() { } public ImageView getImageView(){ if(this.getView() == null) return null; else return (ImageView)this.getView().findViewById(R.id.advertimage); } public void setDrawable(Drawable myImage){ //ImageView image = (ImageView)myLayout.findViewById(R.id.advertimage); //image.setImageDrawable(myImage); } public void setDrawable(int myImage){ Log.v(TAG,"Image Id:"+String.valueOf(myImage)); this.myImageId = myImage; Log.v(TAG,"Image Id:"+String.valueOf(this.myImageId)); } public Drawable getDrawable(){ return this.myImage; } public void setDrawableFile(File adImage) { this.imageFile = adImage; } public void setUrl(String url){ this.URL = url; } public String getUrl(){ return URL; } }
true
true
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.v(TAG,"Created ImageId: "+String.valueOf(myImageId)); ImageView image = (ImageView)this.getView().findViewById(R.id.advertimage); if(imageFile != null) image.setImageBitmap(BitmapFactory.decodeFile(imageFile.getPath())); else { this.myImage = this.getActivity().getResources().getDrawable(myImageId); image.setImageDrawable(this.myImage); } if(URL != null){ image.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(URL)); startActivity(intent); } }); } }
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.v(TAG,"Created ImageId: "+String.valueOf(myImageId)); ImageView image = (ImageView)this.getView().findViewById(R.id.advertimage); if(imageFile != null) image.setImageBitmap(BitmapFactory.decodeFile(imageFile.getPath())); else { if(myImageId > 0){ this.myImage = this.getActivity().getResources().getDrawable(myImageId); image.setImageDrawable(this.myImage); } } if(URL != null){ image.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(URL)); startActivity(intent); } }); } }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizardUtils.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizardUtils.java index b3a19623e..44db8908c 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizardUtils.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizardUtils.java @@ -1,211 +1,211 @@ package de.fu_berlin.inf.dpp.ui.wizards; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import de.fu_berlin.inf.dpp.FileList; import de.fu_berlin.inf.dpp.editor.internal.EditorAPI; import de.fu_berlin.inf.dpp.invitation.IIncomingInvitationProcess; import de.fu_berlin.inf.dpp.util.Util; public class JoinSessionWizardUtils { private static final Logger log = Logger .getLogger(JoinSessionWizardUtils.class.getName()); public static class ScanRunner implements Runnable { public ScanRunner(IIncomingInvitationProcess invitationProcess) { this.invitationProcess = invitationProcess; } IIncomingInvitationProcess invitationProcess; IProject project = null; public void run() { ProgressMonitorDialog dialog = new ProgressMonitorDialog(EditorAPI .getShell()); try { dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InterruptedException { monitor.beginTask("Scanning workspace projects ... ", IProgressMonitor.UNKNOWN); IProject project = JoinSessionWizardUtils .getLocalProject(ScanRunner.this.invitationProcess .getRemoteFileList(), monitor); monitor.done(); ScanRunner.this.project = project; } }); } catch (InvocationTargetException e) { log.error("An error occurred while scanning " + "for best matching project: ", e); MessageDialog.openError(EditorAPI.getShell(), "An Error occurred in Saros", "An error occurred while scanning " + "for best matching project: " + e.getMessage()); } catch (InterruptedException e) { this.project = null; } } } /** * Run the scan for the best matching project as a blocking operation. */ public static IProject getBestScanMatch( IIncomingInvitationProcess invitationProcess) { ScanRunner runner = new ScanRunner(invitationProcess); Util.runSafeSWTSync(log, runner); return runner.project; } public static int getMatch(FileList remoteFileList, IProject project) { try { return remoteFileList.match(new FileList(project)); } catch (CoreException e) { log.debug("Couldn't calculate match for project " + project, e); return -1; } } /** * Return the best match among all project from workspace with the given * remote file list or null if no best match could be found or if the * operation was canceled by the user. * * To be considered a match, projects have to match at least 80%. */ public static IProject getLocalProject(FileList remoteFileList, IProgressMonitor monitor) throws InterruptedException { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject[] projects = workspace.getRoot().getProjects(); IProject bestMatch = null; // A match needs to be at least 80% for us to consider. int bestMatchScore = 80; for (int i = 0; i < projects.length; i++) { monitor.worked(1); if (monitor.isCanceled()) throw new InterruptedException(); if (!projects[i].isOpen()) { continue; } int matchScore = JoinSessionWizardUtils.getMatch(remoteFileList, projects[i]); if (matchScore > bestMatchScore) { bestMatchScore = matchScore; bestMatch = projects[i]; if (matchScore == 100) return bestMatch; } } return bestMatch; } public static boolean projectIsUnique(String name) { // Then check with all the projects IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject[] projects = workspace.getRoot().getProjects(); return JoinSessionWizardUtils.projectIsUnique(name, projects); } public static IProject getProjectForName(String name) { return ResourcesPlugin.getWorkspace().getRoot().getProject(name); } public static boolean projectIsUnique(String name, IProject[] projects) { // Use File to compare so the comparison is case-sensitive depending on // the underlying platform File newProjectName = new File(name); for (IProject project : projects) { if (new File(project.getName()).equals(newProjectName)) { return false; } } return true; } public static String findProjectNameProposal(String projectName) { // Start with the projects name String projectProposal = projectName; // Then check with all the projects IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject[] projects = workspace.getRoot().getProjects(); if (JoinSessionWizardUtils.projectIsUnique(projectProposal, projects)) { return projectProposal; } else { // Name is already in use! - Pattern p = Pattern.compile("^(.*)(\\d+)$"); + Pattern p = Pattern.compile("^(.+?)(\\d+)$"); Matcher m = p.matcher(projectProposal); int i; // Check whether the name ends in a number or not if (m.find()) { projectProposal = m.group(1).trim(); i = Integer.parseInt(m.group(2)); } else { i = 2; } // Then find the next available number while (!JoinSessionWizardUtils.projectIsUnique(projectProposal + " " + i, projects)) { i++; } return projectProposal + " " + i; } } public static boolean existsProjects(String projectName) { // Start with the projects name File proposedName = new File(projectName); // Then check with all the projects IWorkspace workspace = ResourcesPlugin.getWorkspace(); for (IProject project : workspace.getRoot().getProjects()) { if (new File(project.getName()).equals(proposedName)) return true; } return false; } }
true
true
public static String findProjectNameProposal(String projectName) { // Start with the projects name String projectProposal = projectName; // Then check with all the projects IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject[] projects = workspace.getRoot().getProjects(); if (JoinSessionWizardUtils.projectIsUnique(projectProposal, projects)) { return projectProposal; } else { // Name is already in use! Pattern p = Pattern.compile("^(.*)(\\d+)$"); Matcher m = p.matcher(projectProposal); int i; // Check whether the name ends in a number or not if (m.find()) { projectProposal = m.group(1).trim(); i = Integer.parseInt(m.group(2)); } else { i = 2; } // Then find the next available number while (!JoinSessionWizardUtils.projectIsUnique(projectProposal + " " + i, projects)) { i++; } return projectProposal + " " + i; } }
public static String findProjectNameProposal(String projectName) { // Start with the projects name String projectProposal = projectName; // Then check with all the projects IWorkspace workspace = ResourcesPlugin.getWorkspace(); IProject[] projects = workspace.getRoot().getProjects(); if (JoinSessionWizardUtils.projectIsUnique(projectProposal, projects)) { return projectProposal; } else { // Name is already in use! Pattern p = Pattern.compile("^(.+?)(\\d+)$"); Matcher m = p.matcher(projectProposal); int i; // Check whether the name ends in a number or not if (m.find()) { projectProposal = m.group(1).trim(); i = Integer.parseInt(m.group(2)); } else { i = 2; } // Then find the next available number while (!JoinSessionWizardUtils.projectIsUnique(projectProposal + " " + i, projects)) { i++; } return projectProposal + " " + i; } }
diff --git a/freeplane/src/org/freeplane/features/help/FilePropertiesAction.java b/freeplane/src/org/freeplane/features/help/FilePropertiesAction.java index 35e370de1..c9774ea91 100644 --- a/freeplane/src/org/freeplane/features/help/FilePropertiesAction.java +++ b/freeplane/src/org/freeplane/features/help/FilePropertiesAction.java @@ -1,351 +1,351 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is modified by Dimitry Polivaev in 2008. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.help; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.net.URL; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Enumeration; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.SwingConstants; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.ui.AFreeplaneAction; import org.freeplane.core.util.TextUtils; import org.freeplane.features.filter.Filter; import org.freeplane.features.filter.condition.ICondition; import org.freeplane.features.icon.factory.ImageIconFactory; import org.freeplane.features.map.MapModel; import org.freeplane.features.map.NodeModel; import org.freeplane.features.mode.Controller; /** * @author Stefan Ott */ class FilePropertiesAction extends AFreeplaneAction { private static final long serialVersionUID = 1L; FilePropertiesAction() { super("FilePropertiesAction"); } /** * Gets called when File -> Properties is selected */ public void actionPerformed(final ActionEvent e) { //variables for informations to be displayed final String fileNamePath, fileSavedDateTime, fileSize; final int fileChangesSinceSave; //get informations //if file has been saved once final MapModel map = Controller.getCurrentController().getMap(); if (map.getFile() != null) { //fileNamePath fileNamePath = map.getFile().toString(); //fleSavedDateTime as formatted string final Calendar c = Calendar.getInstance(); c.setTimeInMillis(map.getFile().lastModified()); final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); fileSavedDateTime = df.format(c.getTime()); //fileSize as formatted string final DecimalFormat def = new DecimalFormat(); def.setGroupingUsed(true); fileSize = def.format(map.getFile().length()) + " " + TextUtils.getText("NewerFileRevisionsFoundDialog.file_size"); //fileChangesSinceSave fileChangesSinceSave = map.getNumberOfChangesSinceLastSave(); } else { fileNamePath = TextUtils.getText("FileProperties_NeverSaved"); fileSavedDateTime = TextUtils.getText("FileProperties_NeverSaved"); fileSize = TextUtils.getText("FileProperties_NeverSaved"); fileChangesSinceSave = 0; } //node statistics final NodeModel rootNode = map.getRootNode(); final int nodeMainBranches = rootNode.getChildCount(); final ICondition trueCondition = new ICondition() { public boolean checkNode(NodeModel node) { return true; } }; final ICondition isLeafCondition = new ICondition() { public boolean checkNode(NodeModel node) { return node.isLeaf(); } }; final int nodeTotalNodeCount = getNodeCount(rootNode, trueCondition); final int nodeTotalLeafCount = getNodeCount(rootNode, isLeafCondition); final Filter filter = map.getFilter(); final int nodeTotalFiltered; - if(filter != null){ + if(filter != null && filter.getCondition() != null){ final ICondition matchesFilterCondition = new ICondition() { public boolean checkNode(NodeModel node) { return filter.matches(node); } }; nodeTotalFiltered = getNodeCount(rootNode, matchesFilterCondition); } else{ nodeTotalFiltered = -1; } //Multiple nodes may be selected final List<NodeModel> nodes = Controller.getCurrentController().getSelection().getSelection(); boolean isDescendant = false; int nodeRelativeChildCount = 0; int nodeRelativeNodeCount = 0; int nodeRelativeLeafCount = 0; for (final NodeModel n : nodes) { nodeRelativeChildCount += n.getChildCount(); isDescendant = false; //Nodes and leaf nodes are only counted once per branch for (int i = 0; i < nodes.size(); i++) { if (n.isDescendantOf(nodes.get(i))) { isDescendant = true; break; } } if (!isDescendant) { nodeRelativeNodeCount += getNodeCount(n, trueCondition); nodeRelativeLeafCount += getNodeCount(n, isLeafCondition); } } final int nodeSelectedNodeCount = Controller.getCurrentController().getSelection().getSelection().size(); //build component final JPanel panel = new JPanel(); final GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(5, 0, 5, 0))); final GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.ipady = 5; c.ipadx = 0; c.insets = new Insets(0, 10, 0, 10); c.anchor = GridBagConstraints.FIRST_LINE_START; //fileNamePath final URL imageURL = ResourceController.getResourceController().getResource("/images/filenew.png"); final JLabel fileIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL)); gridbag.setConstraints(fileIcon, c); panel.add(fileIcon); c.gridx = 1; final JLabel fileNamePathText = new JLabel(TextUtils.getText("FileProperties_FileName")); gridbag.setConstraints(fileNamePathText, c); panel.add(fileNamePathText); c.gridx = 2; final JLabel fileNamePathLabel = new JLabel(fileNamePath); gridbag.setConstraints(fileNamePathLabel, c); panel.add(fileNamePathLabel); //fileSize c.gridy++; c.gridx = 1; final JLabel fileSizeText = new JLabel(TextUtils.getText("FileProperties_FileSize")); gridbag.setConstraints(fileSizeText, c); panel.add(fileSizeText); c.gridx = 2; final JLabel fileSizeLabel = new JLabel(fileSize); gridbag.setConstraints(fileSizeLabel, c); panel.add(fileSizeLabel); //fileSavedDateTime c.gridy++; c.gridx = 1; final JLabel fileSavedDateTimeText = new JLabel(TextUtils.getText("FileProperties_FileSaved")); gridbag.setConstraints(fileSavedDateTimeText, c); panel.add(fileSavedDateTimeText); c.gridx = 2; final JLabel fileSavedDateTimeLabel = new JLabel(fileSavedDateTime); gridbag.setConstraints(fileSavedDateTimeLabel, c); panel.add(fileSavedDateTimeLabel); //fileChangesSinceSave c.gridy++; c.gridx = 1; final JLabel fileChangesSinceSaveText = new JLabel(TextUtils.getText("FileProperties_ChangesSinceLastSave")); gridbag.setConstraints(fileChangesSinceSaveText, c); panel.add(fileChangesSinceSaveText); c.gridx = 2; final JLabel fileChangesSinceSaveLabel = new JLabel(String.valueOf(fileChangesSinceSave)); gridbag.setConstraints(fileChangesSinceSaveLabel, c); panel.add(fileChangesSinceSaveLabel); //Separator c.gridy++; c.gridx = 0; c.insets = new Insets(5, 10, 5, 10); c.ipady = 2; c.gridwidth = 3; final JSeparator js = new JSeparator(SwingConstants.HORIZONTAL); js.setLayout(gridbag); js.setBorder(BorderFactory.createEtchedBorder()); js.setPreferredSize(new Dimension(0, 0)); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(js, c); panel.add(js); //nodeTotalNodeCount c.gridy++; c.insets = new Insets(0, 10, 0, 10); c.ipady = 5; c.gridwidth = 1; c.gridx = 0; final URL imageURL2 = ResourceController.getResourceController().getResource("/images/MapStats.png"); final JLabel MapStatsIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL2)); gridbag.setConstraints(MapStatsIcon, c); panel.add(MapStatsIcon); c.gridx = 1; final JLabel nodeTotalNodeCountText = new JLabel(TextUtils.getText("FileProperties_TotalNodeCount")); gridbag.setConstraints(nodeTotalNodeCountText, c); panel.add(nodeTotalNodeCountText); c.gridx = 2; final JLabel nodeTotalNodeCountLabel = new JLabel(String.valueOf(nodeTotalNodeCount)); gridbag.setConstraints(nodeTotalNodeCountLabel, c); panel.add(nodeTotalNodeCountLabel); //nodeTotalFiltered if(nodeTotalFiltered != -1){ c.gridy++; c.gridx = 1; final JLabel nodeTotalFilteredLabelText = new JLabel(TextUtils.getText("FileProperties_TotalFilteredCount")); gridbag.setConstraints(nodeTotalFilteredLabelText, c); panel.add(nodeTotalFilteredLabelText); c.gridx = 2; final JLabel nodeTotalFilteredLabel = new JLabel(String.valueOf(nodeTotalFiltered)); gridbag.setConstraints(nodeTotalFilteredLabel, c); panel.add(nodeTotalFilteredLabel); } //nodeTotalLeafCount c.gridy++; c.gridx = 1; final JLabel nodeTotalLeafCountText = new JLabel(TextUtils.getText("FileProperties_TotalLeafCount")); gridbag.setConstraints(nodeTotalLeafCountText, c); panel.add(nodeTotalLeafCountText); c.gridx = 2; final JLabel nodeTotalLeafCountLabel = new JLabel(String.valueOf(nodeTotalLeafCount)); gridbag.setConstraints(nodeTotalLeafCountLabel, c); panel.add(nodeTotalLeafCountLabel); //nodeMainBranches c.gridy++; c.gridx = 1; final JLabel nodeMainBranchesText = new JLabel(TextUtils.getText("FileProperties_MainBranchCount")); gridbag.setConstraints(nodeMainBranchesText, c); panel.add(nodeMainBranchesText); c.gridx = 2; final JLabel nodeMainBranchesLabel = new JLabel(String.valueOf(nodeMainBranches)); gridbag.setConstraints(nodeMainBranchesLabel, c); panel.add(nodeMainBranchesLabel); //Separator c.gridy++; c.gridx = 0; c.insets = new Insets(5, 10, 5, 10); c.ipady = 2; c.gridwidth = 3; final JSeparator js2 = new JSeparator(SwingConstants.HORIZONTAL); js2.setLayout(gridbag); js2.setBorder(BorderFactory.createEtchedBorder()); js2.setPreferredSize(new Dimension(0, 0)); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(js2, c); panel.add(js2); //nodeRelativeNodeCount c.gridy++; c.insets = new Insets(0, 10, 0, 10); c.ipady = 5; c.gridwidth = 1; c.gridx = 0; final URL imageURL3 = ResourceController.getResourceController().getResource("/images/BranchStats.png"); final JLabel BranchStatsIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL3)); gridbag.setConstraints(BranchStatsIcon, c); panel.add(BranchStatsIcon); c.gridx = 1; final JLabel nodeRelativeNodeCountText = new JLabel(TextUtils.getText("FileProperties_BranchNodeCount")); gridbag.setConstraints(nodeRelativeNodeCountText, c); panel.add(nodeRelativeNodeCountText); c.gridx = 2; final JLabel nodeRelativeNodeCountLabel = new JLabel(String.valueOf(nodeRelativeNodeCount)); gridbag.setConstraints(nodeRelativeNodeCountLabel, c); panel.add(nodeRelativeNodeCountLabel); //nodeRelativeLeafCount c.gridy++; c.gridx = 1; final JLabel nodeRelativeLeafCountText = new JLabel(TextUtils.getText("FileProperties_BranchLeafCount")); gridbag.setConstraints(nodeRelativeLeafCountText, c); panel.add(nodeRelativeLeafCountText); c.gridx = 2; final JLabel nodeRelativeLeafCountLabel = new JLabel(String.valueOf(nodeRelativeLeafCount)); gridbag.setConstraints(nodeRelativeLeafCountLabel, c); panel.add(nodeRelativeLeafCountLabel); //nodeRelativeChildCount c.gridy++; c.gridx = 1; final JLabel nodeRelativeChildCountText = new JLabel(TextUtils.getText("FileProperties_NodeChildCount")); gridbag.setConstraints(nodeRelativeChildCountText, c); panel.add(nodeRelativeChildCountText); c.gridx = 2; final JLabel nodeRelativeChildCountLabel = new JLabel(String.valueOf(nodeRelativeChildCount)); gridbag.setConstraints(nodeRelativeChildCountLabel, c); panel.add(nodeRelativeChildCountLabel); //nodeSelectedNodeCount c.gridy++; c.gridx = 1; final JLabel nodeSelectedNodeCountText = new JLabel(TextUtils.getText("FileProperties_NodeSelectionCount")); gridbag.setConstraints(nodeSelectedNodeCountText, c); panel.add(nodeSelectedNodeCountText); c.gridx = 2; final JLabel nodeSelectedNodeCountLabel = new JLabel(String.valueOf(nodeSelectedNodeCount)); gridbag.setConstraints(nodeSelectedNodeCountLabel, c); panel.add(nodeSelectedNodeCountLabel); //Show dialog JOptionPane.showMessageDialog(Controller.getCurrentController().getViewController().getViewport(), panel, TextUtils.removeMnemonic(TextUtils.getText("FilePropertiesAction.text")), JOptionPane.PLAIN_MESSAGE); } /** * Builts an array containing nodes form the given node on downwards. * * @param NodeModel node: The node from which on to search * @param boolean CountLeaves: If true only leave nodes are included in the return list, * otherwise all nodes from the selected on are included * * @return Returns a list of nodes */ private int getNodeCount(final NodeModel node, final ICondition condition) { int result = 0; final Enumeration<NodeModel> children = node.children(); if (condition.checkNode(node)) { result++; } while (children.hasMoreElements()) { final NodeModel child = children.nextElement(); result += getNodeCount(child, condition); } return result; } }
true
true
public void actionPerformed(final ActionEvent e) { //variables for informations to be displayed final String fileNamePath, fileSavedDateTime, fileSize; final int fileChangesSinceSave; //get informations //if file has been saved once final MapModel map = Controller.getCurrentController().getMap(); if (map.getFile() != null) { //fileNamePath fileNamePath = map.getFile().toString(); //fleSavedDateTime as formatted string final Calendar c = Calendar.getInstance(); c.setTimeInMillis(map.getFile().lastModified()); final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); fileSavedDateTime = df.format(c.getTime()); //fileSize as formatted string final DecimalFormat def = new DecimalFormat(); def.setGroupingUsed(true); fileSize = def.format(map.getFile().length()) + " " + TextUtils.getText("NewerFileRevisionsFoundDialog.file_size"); //fileChangesSinceSave fileChangesSinceSave = map.getNumberOfChangesSinceLastSave(); } else { fileNamePath = TextUtils.getText("FileProperties_NeverSaved"); fileSavedDateTime = TextUtils.getText("FileProperties_NeverSaved"); fileSize = TextUtils.getText("FileProperties_NeverSaved"); fileChangesSinceSave = 0; } //node statistics final NodeModel rootNode = map.getRootNode(); final int nodeMainBranches = rootNode.getChildCount(); final ICondition trueCondition = new ICondition() { public boolean checkNode(NodeModel node) { return true; } }; final ICondition isLeafCondition = new ICondition() { public boolean checkNode(NodeModel node) { return node.isLeaf(); } }; final int nodeTotalNodeCount = getNodeCount(rootNode, trueCondition); final int nodeTotalLeafCount = getNodeCount(rootNode, isLeafCondition); final Filter filter = map.getFilter(); final int nodeTotalFiltered; if(filter != null){ final ICondition matchesFilterCondition = new ICondition() { public boolean checkNode(NodeModel node) { return filter.matches(node); } }; nodeTotalFiltered = getNodeCount(rootNode, matchesFilterCondition); } else{ nodeTotalFiltered = -1; } //Multiple nodes may be selected final List<NodeModel> nodes = Controller.getCurrentController().getSelection().getSelection(); boolean isDescendant = false; int nodeRelativeChildCount = 0; int nodeRelativeNodeCount = 0; int nodeRelativeLeafCount = 0; for (final NodeModel n : nodes) { nodeRelativeChildCount += n.getChildCount(); isDescendant = false; //Nodes and leaf nodes are only counted once per branch for (int i = 0; i < nodes.size(); i++) { if (n.isDescendantOf(nodes.get(i))) { isDescendant = true; break; } } if (!isDescendant) { nodeRelativeNodeCount += getNodeCount(n, trueCondition); nodeRelativeLeafCount += getNodeCount(n, isLeafCondition); } } final int nodeSelectedNodeCount = Controller.getCurrentController().getSelection().getSelection().size(); //build component final JPanel panel = new JPanel(); final GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(5, 0, 5, 0))); final GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.ipady = 5; c.ipadx = 0; c.insets = new Insets(0, 10, 0, 10); c.anchor = GridBagConstraints.FIRST_LINE_START; //fileNamePath final URL imageURL = ResourceController.getResourceController().getResource("/images/filenew.png"); final JLabel fileIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL)); gridbag.setConstraints(fileIcon, c); panel.add(fileIcon); c.gridx = 1; final JLabel fileNamePathText = new JLabel(TextUtils.getText("FileProperties_FileName")); gridbag.setConstraints(fileNamePathText, c); panel.add(fileNamePathText); c.gridx = 2; final JLabel fileNamePathLabel = new JLabel(fileNamePath); gridbag.setConstraints(fileNamePathLabel, c); panel.add(fileNamePathLabel); //fileSize c.gridy++; c.gridx = 1; final JLabel fileSizeText = new JLabel(TextUtils.getText("FileProperties_FileSize")); gridbag.setConstraints(fileSizeText, c); panel.add(fileSizeText); c.gridx = 2; final JLabel fileSizeLabel = new JLabel(fileSize); gridbag.setConstraints(fileSizeLabel, c); panel.add(fileSizeLabel); //fileSavedDateTime c.gridy++; c.gridx = 1; final JLabel fileSavedDateTimeText = new JLabel(TextUtils.getText("FileProperties_FileSaved")); gridbag.setConstraints(fileSavedDateTimeText, c); panel.add(fileSavedDateTimeText); c.gridx = 2; final JLabel fileSavedDateTimeLabel = new JLabel(fileSavedDateTime); gridbag.setConstraints(fileSavedDateTimeLabel, c); panel.add(fileSavedDateTimeLabel); //fileChangesSinceSave c.gridy++; c.gridx = 1; final JLabel fileChangesSinceSaveText = new JLabel(TextUtils.getText("FileProperties_ChangesSinceLastSave")); gridbag.setConstraints(fileChangesSinceSaveText, c); panel.add(fileChangesSinceSaveText); c.gridx = 2; final JLabel fileChangesSinceSaveLabel = new JLabel(String.valueOf(fileChangesSinceSave)); gridbag.setConstraints(fileChangesSinceSaveLabel, c); panel.add(fileChangesSinceSaveLabel); //Separator c.gridy++; c.gridx = 0; c.insets = new Insets(5, 10, 5, 10); c.ipady = 2; c.gridwidth = 3; final JSeparator js = new JSeparator(SwingConstants.HORIZONTAL); js.setLayout(gridbag); js.setBorder(BorderFactory.createEtchedBorder()); js.setPreferredSize(new Dimension(0, 0)); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(js, c); panel.add(js); //nodeTotalNodeCount c.gridy++; c.insets = new Insets(0, 10, 0, 10); c.ipady = 5; c.gridwidth = 1; c.gridx = 0; final URL imageURL2 = ResourceController.getResourceController().getResource("/images/MapStats.png"); final JLabel MapStatsIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL2)); gridbag.setConstraints(MapStatsIcon, c); panel.add(MapStatsIcon); c.gridx = 1; final JLabel nodeTotalNodeCountText = new JLabel(TextUtils.getText("FileProperties_TotalNodeCount")); gridbag.setConstraints(nodeTotalNodeCountText, c); panel.add(nodeTotalNodeCountText); c.gridx = 2; final JLabel nodeTotalNodeCountLabel = new JLabel(String.valueOf(nodeTotalNodeCount)); gridbag.setConstraints(nodeTotalNodeCountLabel, c); panel.add(nodeTotalNodeCountLabel); //nodeTotalFiltered if(nodeTotalFiltered != -1){ c.gridy++; c.gridx = 1; final JLabel nodeTotalFilteredLabelText = new JLabel(TextUtils.getText("FileProperties_TotalFilteredCount")); gridbag.setConstraints(nodeTotalFilteredLabelText, c); panel.add(nodeTotalFilteredLabelText); c.gridx = 2; final JLabel nodeTotalFilteredLabel = new JLabel(String.valueOf(nodeTotalFiltered)); gridbag.setConstraints(nodeTotalFilteredLabel, c); panel.add(nodeTotalFilteredLabel); } //nodeTotalLeafCount c.gridy++; c.gridx = 1; final JLabel nodeTotalLeafCountText = new JLabel(TextUtils.getText("FileProperties_TotalLeafCount")); gridbag.setConstraints(nodeTotalLeafCountText, c); panel.add(nodeTotalLeafCountText); c.gridx = 2; final JLabel nodeTotalLeafCountLabel = new JLabel(String.valueOf(nodeTotalLeafCount)); gridbag.setConstraints(nodeTotalLeafCountLabel, c); panel.add(nodeTotalLeafCountLabel); //nodeMainBranches c.gridy++; c.gridx = 1; final JLabel nodeMainBranchesText = new JLabel(TextUtils.getText("FileProperties_MainBranchCount")); gridbag.setConstraints(nodeMainBranchesText, c); panel.add(nodeMainBranchesText); c.gridx = 2; final JLabel nodeMainBranchesLabel = new JLabel(String.valueOf(nodeMainBranches)); gridbag.setConstraints(nodeMainBranchesLabel, c); panel.add(nodeMainBranchesLabel); //Separator c.gridy++; c.gridx = 0; c.insets = new Insets(5, 10, 5, 10); c.ipady = 2; c.gridwidth = 3; final JSeparator js2 = new JSeparator(SwingConstants.HORIZONTAL); js2.setLayout(gridbag); js2.setBorder(BorderFactory.createEtchedBorder()); js2.setPreferredSize(new Dimension(0, 0)); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(js2, c); panel.add(js2); //nodeRelativeNodeCount c.gridy++; c.insets = new Insets(0, 10, 0, 10); c.ipady = 5; c.gridwidth = 1; c.gridx = 0; final URL imageURL3 = ResourceController.getResourceController().getResource("/images/BranchStats.png"); final JLabel BranchStatsIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL3)); gridbag.setConstraints(BranchStatsIcon, c); panel.add(BranchStatsIcon); c.gridx = 1; final JLabel nodeRelativeNodeCountText = new JLabel(TextUtils.getText("FileProperties_BranchNodeCount")); gridbag.setConstraints(nodeRelativeNodeCountText, c); panel.add(nodeRelativeNodeCountText); c.gridx = 2; final JLabel nodeRelativeNodeCountLabel = new JLabel(String.valueOf(nodeRelativeNodeCount)); gridbag.setConstraints(nodeRelativeNodeCountLabel, c); panel.add(nodeRelativeNodeCountLabel); //nodeRelativeLeafCount c.gridy++; c.gridx = 1; final JLabel nodeRelativeLeafCountText = new JLabel(TextUtils.getText("FileProperties_BranchLeafCount")); gridbag.setConstraints(nodeRelativeLeafCountText, c); panel.add(nodeRelativeLeafCountText); c.gridx = 2; final JLabel nodeRelativeLeafCountLabel = new JLabel(String.valueOf(nodeRelativeLeafCount)); gridbag.setConstraints(nodeRelativeLeafCountLabel, c); panel.add(nodeRelativeLeafCountLabel); //nodeRelativeChildCount c.gridy++; c.gridx = 1; final JLabel nodeRelativeChildCountText = new JLabel(TextUtils.getText("FileProperties_NodeChildCount")); gridbag.setConstraints(nodeRelativeChildCountText, c); panel.add(nodeRelativeChildCountText); c.gridx = 2; final JLabel nodeRelativeChildCountLabel = new JLabel(String.valueOf(nodeRelativeChildCount)); gridbag.setConstraints(nodeRelativeChildCountLabel, c); panel.add(nodeRelativeChildCountLabel); //nodeSelectedNodeCount c.gridy++; c.gridx = 1; final JLabel nodeSelectedNodeCountText = new JLabel(TextUtils.getText("FileProperties_NodeSelectionCount")); gridbag.setConstraints(nodeSelectedNodeCountText, c); panel.add(nodeSelectedNodeCountText); c.gridx = 2; final JLabel nodeSelectedNodeCountLabel = new JLabel(String.valueOf(nodeSelectedNodeCount)); gridbag.setConstraints(nodeSelectedNodeCountLabel, c); panel.add(nodeSelectedNodeCountLabel); //Show dialog JOptionPane.showMessageDialog(Controller.getCurrentController().getViewController().getViewport(), panel, TextUtils.removeMnemonic(TextUtils.getText("FilePropertiesAction.text")), JOptionPane.PLAIN_MESSAGE); }
public void actionPerformed(final ActionEvent e) { //variables for informations to be displayed final String fileNamePath, fileSavedDateTime, fileSize; final int fileChangesSinceSave; //get informations //if file has been saved once final MapModel map = Controller.getCurrentController().getMap(); if (map.getFile() != null) { //fileNamePath fileNamePath = map.getFile().toString(); //fleSavedDateTime as formatted string final Calendar c = Calendar.getInstance(); c.setTimeInMillis(map.getFile().lastModified()); final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); fileSavedDateTime = df.format(c.getTime()); //fileSize as formatted string final DecimalFormat def = new DecimalFormat(); def.setGroupingUsed(true); fileSize = def.format(map.getFile().length()) + " " + TextUtils.getText("NewerFileRevisionsFoundDialog.file_size"); //fileChangesSinceSave fileChangesSinceSave = map.getNumberOfChangesSinceLastSave(); } else { fileNamePath = TextUtils.getText("FileProperties_NeverSaved"); fileSavedDateTime = TextUtils.getText("FileProperties_NeverSaved"); fileSize = TextUtils.getText("FileProperties_NeverSaved"); fileChangesSinceSave = 0; } //node statistics final NodeModel rootNode = map.getRootNode(); final int nodeMainBranches = rootNode.getChildCount(); final ICondition trueCondition = new ICondition() { public boolean checkNode(NodeModel node) { return true; } }; final ICondition isLeafCondition = new ICondition() { public boolean checkNode(NodeModel node) { return node.isLeaf(); } }; final int nodeTotalNodeCount = getNodeCount(rootNode, trueCondition); final int nodeTotalLeafCount = getNodeCount(rootNode, isLeafCondition); final Filter filter = map.getFilter(); final int nodeTotalFiltered; if(filter != null && filter.getCondition() != null){ final ICondition matchesFilterCondition = new ICondition() { public boolean checkNode(NodeModel node) { return filter.matches(node); } }; nodeTotalFiltered = getNodeCount(rootNode, matchesFilterCondition); } else{ nodeTotalFiltered = -1; } //Multiple nodes may be selected final List<NodeModel> nodes = Controller.getCurrentController().getSelection().getSelection(); boolean isDescendant = false; int nodeRelativeChildCount = 0; int nodeRelativeNodeCount = 0; int nodeRelativeLeafCount = 0; for (final NodeModel n : nodes) { nodeRelativeChildCount += n.getChildCount(); isDescendant = false; //Nodes and leaf nodes are only counted once per branch for (int i = 0; i < nodes.size(); i++) { if (n.isDescendantOf(nodes.get(i))) { isDescendant = true; break; } } if (!isDescendant) { nodeRelativeNodeCount += getNodeCount(n, trueCondition); nodeRelativeLeafCount += getNodeCount(n, isLeafCondition); } } final int nodeSelectedNodeCount = Controller.getCurrentController().getSelection().getSelection().size(); //build component final JPanel panel = new JPanel(); final GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(5, 0, 5, 0))); final GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.ipady = 5; c.ipadx = 0; c.insets = new Insets(0, 10, 0, 10); c.anchor = GridBagConstraints.FIRST_LINE_START; //fileNamePath final URL imageURL = ResourceController.getResourceController().getResource("/images/filenew.png"); final JLabel fileIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL)); gridbag.setConstraints(fileIcon, c); panel.add(fileIcon); c.gridx = 1; final JLabel fileNamePathText = new JLabel(TextUtils.getText("FileProperties_FileName")); gridbag.setConstraints(fileNamePathText, c); panel.add(fileNamePathText); c.gridx = 2; final JLabel fileNamePathLabel = new JLabel(fileNamePath); gridbag.setConstraints(fileNamePathLabel, c); panel.add(fileNamePathLabel); //fileSize c.gridy++; c.gridx = 1; final JLabel fileSizeText = new JLabel(TextUtils.getText("FileProperties_FileSize")); gridbag.setConstraints(fileSizeText, c); panel.add(fileSizeText); c.gridx = 2; final JLabel fileSizeLabel = new JLabel(fileSize); gridbag.setConstraints(fileSizeLabel, c); panel.add(fileSizeLabel); //fileSavedDateTime c.gridy++; c.gridx = 1; final JLabel fileSavedDateTimeText = new JLabel(TextUtils.getText("FileProperties_FileSaved")); gridbag.setConstraints(fileSavedDateTimeText, c); panel.add(fileSavedDateTimeText); c.gridx = 2; final JLabel fileSavedDateTimeLabel = new JLabel(fileSavedDateTime); gridbag.setConstraints(fileSavedDateTimeLabel, c); panel.add(fileSavedDateTimeLabel); //fileChangesSinceSave c.gridy++; c.gridx = 1; final JLabel fileChangesSinceSaveText = new JLabel(TextUtils.getText("FileProperties_ChangesSinceLastSave")); gridbag.setConstraints(fileChangesSinceSaveText, c); panel.add(fileChangesSinceSaveText); c.gridx = 2; final JLabel fileChangesSinceSaveLabel = new JLabel(String.valueOf(fileChangesSinceSave)); gridbag.setConstraints(fileChangesSinceSaveLabel, c); panel.add(fileChangesSinceSaveLabel); //Separator c.gridy++; c.gridx = 0; c.insets = new Insets(5, 10, 5, 10); c.ipady = 2; c.gridwidth = 3; final JSeparator js = new JSeparator(SwingConstants.HORIZONTAL); js.setLayout(gridbag); js.setBorder(BorderFactory.createEtchedBorder()); js.setPreferredSize(new Dimension(0, 0)); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(js, c); panel.add(js); //nodeTotalNodeCount c.gridy++; c.insets = new Insets(0, 10, 0, 10); c.ipady = 5; c.gridwidth = 1; c.gridx = 0; final URL imageURL2 = ResourceController.getResourceController().getResource("/images/MapStats.png"); final JLabel MapStatsIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL2)); gridbag.setConstraints(MapStatsIcon, c); panel.add(MapStatsIcon); c.gridx = 1; final JLabel nodeTotalNodeCountText = new JLabel(TextUtils.getText("FileProperties_TotalNodeCount")); gridbag.setConstraints(nodeTotalNodeCountText, c); panel.add(nodeTotalNodeCountText); c.gridx = 2; final JLabel nodeTotalNodeCountLabel = new JLabel(String.valueOf(nodeTotalNodeCount)); gridbag.setConstraints(nodeTotalNodeCountLabel, c); panel.add(nodeTotalNodeCountLabel); //nodeTotalFiltered if(nodeTotalFiltered != -1){ c.gridy++; c.gridx = 1; final JLabel nodeTotalFilteredLabelText = new JLabel(TextUtils.getText("FileProperties_TotalFilteredCount")); gridbag.setConstraints(nodeTotalFilteredLabelText, c); panel.add(nodeTotalFilteredLabelText); c.gridx = 2; final JLabel nodeTotalFilteredLabel = new JLabel(String.valueOf(nodeTotalFiltered)); gridbag.setConstraints(nodeTotalFilteredLabel, c); panel.add(nodeTotalFilteredLabel); } //nodeTotalLeafCount c.gridy++; c.gridx = 1; final JLabel nodeTotalLeafCountText = new JLabel(TextUtils.getText("FileProperties_TotalLeafCount")); gridbag.setConstraints(nodeTotalLeafCountText, c); panel.add(nodeTotalLeafCountText); c.gridx = 2; final JLabel nodeTotalLeafCountLabel = new JLabel(String.valueOf(nodeTotalLeafCount)); gridbag.setConstraints(nodeTotalLeafCountLabel, c); panel.add(nodeTotalLeafCountLabel); //nodeMainBranches c.gridy++; c.gridx = 1; final JLabel nodeMainBranchesText = new JLabel(TextUtils.getText("FileProperties_MainBranchCount")); gridbag.setConstraints(nodeMainBranchesText, c); panel.add(nodeMainBranchesText); c.gridx = 2; final JLabel nodeMainBranchesLabel = new JLabel(String.valueOf(nodeMainBranches)); gridbag.setConstraints(nodeMainBranchesLabel, c); panel.add(nodeMainBranchesLabel); //Separator c.gridy++; c.gridx = 0; c.insets = new Insets(5, 10, 5, 10); c.ipady = 2; c.gridwidth = 3; final JSeparator js2 = new JSeparator(SwingConstants.HORIZONTAL); js2.setLayout(gridbag); js2.setBorder(BorderFactory.createEtchedBorder()); js2.setPreferredSize(new Dimension(0, 0)); c.fill = GridBagConstraints.HORIZONTAL; gridbag.setConstraints(js2, c); panel.add(js2); //nodeRelativeNodeCount c.gridy++; c.insets = new Insets(0, 10, 0, 10); c.ipady = 5; c.gridwidth = 1; c.gridx = 0; final URL imageURL3 = ResourceController.getResourceController().getResource("/images/BranchStats.png"); final JLabel BranchStatsIcon = new JLabel(ImageIconFactory.getInstance().getImageIcon(imageURL3)); gridbag.setConstraints(BranchStatsIcon, c); panel.add(BranchStatsIcon); c.gridx = 1; final JLabel nodeRelativeNodeCountText = new JLabel(TextUtils.getText("FileProperties_BranchNodeCount")); gridbag.setConstraints(nodeRelativeNodeCountText, c); panel.add(nodeRelativeNodeCountText); c.gridx = 2; final JLabel nodeRelativeNodeCountLabel = new JLabel(String.valueOf(nodeRelativeNodeCount)); gridbag.setConstraints(nodeRelativeNodeCountLabel, c); panel.add(nodeRelativeNodeCountLabel); //nodeRelativeLeafCount c.gridy++; c.gridx = 1; final JLabel nodeRelativeLeafCountText = new JLabel(TextUtils.getText("FileProperties_BranchLeafCount")); gridbag.setConstraints(nodeRelativeLeafCountText, c); panel.add(nodeRelativeLeafCountText); c.gridx = 2; final JLabel nodeRelativeLeafCountLabel = new JLabel(String.valueOf(nodeRelativeLeafCount)); gridbag.setConstraints(nodeRelativeLeafCountLabel, c); panel.add(nodeRelativeLeafCountLabel); //nodeRelativeChildCount c.gridy++; c.gridx = 1; final JLabel nodeRelativeChildCountText = new JLabel(TextUtils.getText("FileProperties_NodeChildCount")); gridbag.setConstraints(nodeRelativeChildCountText, c); panel.add(nodeRelativeChildCountText); c.gridx = 2; final JLabel nodeRelativeChildCountLabel = new JLabel(String.valueOf(nodeRelativeChildCount)); gridbag.setConstraints(nodeRelativeChildCountLabel, c); panel.add(nodeRelativeChildCountLabel); //nodeSelectedNodeCount c.gridy++; c.gridx = 1; final JLabel nodeSelectedNodeCountText = new JLabel(TextUtils.getText("FileProperties_NodeSelectionCount")); gridbag.setConstraints(nodeSelectedNodeCountText, c); panel.add(nodeSelectedNodeCountText); c.gridx = 2; final JLabel nodeSelectedNodeCountLabel = new JLabel(String.valueOf(nodeSelectedNodeCount)); gridbag.setConstraints(nodeSelectedNodeCountLabel, c); panel.add(nodeSelectedNodeCountLabel); //Show dialog JOptionPane.showMessageDialog(Controller.getCurrentController().getViewController().getViewport(), panel, TextUtils.removeMnemonic(TextUtils.getText("FilePropertiesAction.text")), JOptionPane.PLAIN_MESSAGE); }
diff --git a/components/bio-formats/src/loci/formats/in/LeicaHandler.java b/components/bio-formats/src/loci/formats/in/LeicaHandler.java index 423795d67..1e7674d75 100644 --- a/components/bio-formats/src/loci/formats/in/LeicaHandler.java +++ b/components/bio-formats/src/loci/formats/in/LeicaHandler.java @@ -1,1126 +1,1129 @@ // // LeicaHandler.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.util.Arrays; import java.util.Hashtable; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import loci.common.DateTools; import loci.formats.CoreMetadata; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import ome.xml.model.enums.Correction; import ome.xml.model.enums.DetectorType; import ome.xml.model.enums.EnumerationException; import ome.xml.model.enums.Immersion; import ome.xml.model.enums.LaserMedium; import ome.xml.model.enums.LaserType; import ome.xml.model.enums.MicroscopeType; import ome.xml.model.enums.handlers.CorrectionEnumHandler; import ome.xml.model.enums.handlers.DetectorTypeEnumHandler; import ome.xml.model.enums.handlers.ImmersionEnumHandler; import ome.xml.model.enums.handlers.LaserMediumEnumHandler; import ome.xml.model.enums.handlers.LaserTypeEnumHandler; import ome.xml.model.enums.handlers.MicroscopeTypeEnumHandler; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PercentFraction; import ome.xml.model.primitives.PositiveInteger; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; /** * SAX handler for parsing XML in Leica LIF and Leica TCS files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">SVN</a></dd></dl> * * @author Melissa Linkert melissa at glencoesoftware.com */ public class LeicaHandler extends DefaultHandler { // -- Fields -- private Stack<String> nameStack = new Stack<String>(); private String elementName, collection; private int count = 0, numChannels, extras = 1; private Vector<String> lutNames; private Vector<Double> xPos, yPos, zPos; private double physicalSizeX, physicalSizeY; private int numDatasets = -1; private Hashtable globalMetadata; private MetadataStore store; private int nextChannel = 0; private Double zoom, pinhole; private Vector<Integer> detectorIndices; private String filterWheelName; private int nextFilter = 0; private int nextROI = 0; private ROI roi; private boolean alternateCenter = false; private boolean linkedInstruments = false; private int detectorChannel = 0; private Vector<CoreMetadata> core; private boolean canParse = true; private long firstStamp = 0; private Hashtable<Integer, String> bytesPerAxis; private Vector<MultiBand> multiBands = new Vector<MultiBand>(); private Vector<Detector> detectors = new Vector<Detector>(); private Vector<Laser> lasers = new Vector<Laser>(); private Hashtable<String, Channel> channels = new Hashtable<String, Channel>(); private MetadataLevel level; private int laserCount = 0; // -- Constructor -- public LeicaHandler(MetadataStore store, MetadataLevel level) { super(); globalMetadata = new Hashtable(); lutNames = new Vector<String>(); this.store = store; core = new Vector<CoreMetadata>(); detectorIndices = new Vector<Integer>(); xPos = new Vector<Double>(); yPos = new Vector<Double>(); zPos = new Vector<Double>(); bytesPerAxis = new Hashtable<Integer, String>(); this.level = level; } // -- LeicaHandler API methods -- public Vector<CoreMetadata> getCoreMetadata() { return core; } public Hashtable getGlobalMetadata() { return globalMetadata; } public Vector<String> getLutNames() { return lutNames; } // -- DefaultHandler API methods -- public void endElement(String uri, String localName, String qName) { if (!nameStack.empty() && nameStack.peek().equals(qName)) nameStack.pop(); if (qName.equals("ImageDescription")) { CoreMetadata coreMeta = core.get(numDatasets); if (numChannels == 0) numChannels = 1; coreMeta.sizeC = numChannels; if (extras > 1) { if (coreMeta.sizeZ == 1) coreMeta.sizeZ = extras; else { if (coreMeta.sizeT == 0) coreMeta.sizeT = extras; else coreMeta.sizeT *= extras; } } if (coreMeta.sizeX == 0 && coreMeta.sizeY == 0) { if (numDatasets > 0) numDatasets--; } else { if (coreMeta.sizeX == 0) coreMeta.sizeX = 1; if (coreMeta.sizeZ == 0) coreMeta.sizeZ = 1; if (coreMeta.sizeT == 0) coreMeta.sizeT = 1; coreMeta.orderCertain = true; coreMeta.metadataComplete = true; coreMeta.littleEndian = true; coreMeta.interleaved = coreMeta.rgb; coreMeta.imageCount = coreMeta.sizeZ * coreMeta.sizeT; if (!coreMeta.rgb) coreMeta.imageCount *= coreMeta.sizeC; coreMeta.indexed = !coreMeta.rgb; coreMeta.falseColor = true; Integer[] bytes = bytesPerAxis.keySet().toArray(new Integer[0]); Arrays.sort(bytes); coreMeta.dimensionOrder = "XY"; for (Integer nBytes : bytes) { String axis = bytesPerAxis.get(nBytes); if (coreMeta.dimensionOrder.indexOf(axis) == -1) { coreMeta.dimensionOrder += axis; } } String[] axes = new String[] {"Z", "C", "T"}; for (String axis : axes) { if (coreMeta.dimensionOrder.indexOf(axis) == -1) { coreMeta.dimensionOrder += axis; } } core.setElementAt(coreMeta, numDatasets); } if (level != MetadataLevel.MINIMUM) { int nChannels = coreMeta.rgb ? 0 : numChannels; for (int c=0; c<nChannels; c++) { store.setChannelPinholeSize(pinhole, numDatasets, c); } for (int i=0; i<xPos.size(); i++) { int pos = i + 1; globalMetadata.put("X position for position #" + pos, xPos.get(i)); globalMetadata.put("Y position for position #" + pos, yPos.get(i)); globalMetadata.put("Z position for position #" + pos, zPos.get(i)); for (int image=0; image<coreMeta.imageCount; image++) { store.setPlanePositionX(xPos.get(i), numDatasets, image); store.setPlanePositionY(yPos.get(i), numDatasets, image); store.setPlanePositionZ(zPos.get(i), numDatasets, image); } } for (int c=0; c<nChannels; c++) { int index = c < detectorIndices.size() ? detectorIndices.get(c).intValue() : detectorIndices.size() - 1; if (index < 0 || index >= nChannels || index >= 0) break; String id = MetadataTools.createLSID("Detector", numDatasets, index); store.setDetectorSettingsID(id, numDatasets, c); } String[] keys = channels.keySet().toArray(new String[0]); Arrays.sort(keys); for (int c=0; c<keys.length; c++) { Channel ch = channels.get(keys[c]); store.setDetectorSettingsID(ch.detector, numDatasets, c); store.setChannelExcitationWavelength(ch.exWave, numDatasets, c); store.setChannelName(ch.name, numDatasets, c); store.setDetectorSettingsGain(ch.gain, numDatasets, c); } } channels.clear(); xPos.clear(); yPos.clear(); zPos.clear(); detectorIndices.clear(); } else if (qName.equals("Element") && level != MetadataLevel.MINIMUM) { multiBands.clear(); nextROI = 0; if (numDatasets >= 0) { int nChannels = core.get(numDatasets).rgb ? 1 : numChannels; for (int c=0; c<detectorIndices.size(); c++) { int index = detectorIndices.get(c).intValue(); if (c >= nChannels || index >= nChannels || index >= 0) break; String id = MetadataTools.createLSID("Detector", numDatasets, index); store.setDetectorSettingsID(id, numDatasets, index); } for (int c=0; c<nChannels; c++) { store.setChannelPinholeSize(pinhole, numDatasets, c); } } } else if (qName.equals("Image")) { nextChannel = 0; } else if (qName.equals("LDM_Block_Sequential_Master")) { canParse = true; } else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) { roi.storeROI(store, numDatasets, nextROI++); } } public void startElement(String uri, String localName, String qName, Attributes attributes) { if (attributes.getLength() > 0 && !qName.equals("Element") && !qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader")) { nameStack.push(qName); } int oldSeriesCount = numDatasets; Hashtable h = getSeriesHashtable(numDatasets); if (qName.equals("LDM_Block_Sequential_Master")) { canParse = false; } else if (qName.startsWith("LDM")) { linkedInstruments = true; } if (!canParse) return; StringBuffer key = new StringBuffer(); for (String k : nameStack) { key.append(k); key.append("|"); } String suffix = attributes.getValue("Identifier"); String value = attributes.getValue("Variant"); if (suffix == null) suffix = attributes.getValue("Description"); if (level != MetadataLevel.MINIMUM) { if (suffix != null && value != null) { storeKeyValue(h, key.toString() + suffix, value); } else { for (int i=0; i<attributes.getLength(); i++) { String name = attributes.getQName(i); storeKeyValue(h, key.toString() + name, attributes.getValue(i)); } } } if (qName.equals("Element")) { elementName = attributes.getValue("Name"); } else if (qName.equals("Collection")) { collection = elementName; } else if (qName.equals("Image")) { if (!linkedInstruments && level != MetadataLevel.MINIMUM) { int c = 0; for (Detector d : detectors) { String id = MetadataTools.createLSID( "Detector", numDatasets, detectorChannel); store.setDetectorID(id, numDatasets, detectorChannel); try { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); store.setDetectorType((DetectorType) handler.getEnumeration(d.type), numDatasets, detectorChannel); } catch (EnumerationException e) { } store.setDetectorModel(d.model, numDatasets, detectorChannel); store.setDetectorZoom(d.zoom, numDatasets, detectorChannel); store.setDetectorOffset(d.offset, numDatasets, detectorChannel); store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel); if (c < numChannels) { if (d.active) { store.setDetectorSettingsOffset(d.offset, numDatasets, c); store.setDetectorSettingsID(id, numDatasets, c); c++; } } detectorChannel++; } int filter = 0; for (int i=0; i<nextFilter; i++) { while (filter < detectors.size() && !detectors.get(filter).active) { filter++; } if (filter >= detectors.size() || filter >= nextFilter) break; String id = MetadataTools.createLSID("Filter", numDatasets, filter); if (i < numChannels && detectors.get(filter).active) { String lsid = MetadataTools.createLSID("Channel", numDatasets, i); store.setChannelID(lsid, numDatasets, i); store.setLightPathEmissionFilterRef(id, numDatasets, i, 0); } filter++; } } core.add(new CoreMetadata()); numDatasets++; laserCount = 0; linkedInstruments = false; detectorChannel = 0; detectors.clear(); lasers.clear(); nextFilter = 0; String name = elementName; if (collection != null) name = collection + "/" + name; store.setImageName(name, numDatasets); String instrumentID = MetadataTools.createLSID("Instrument", numDatasets); store.setInstrumentID(instrumentID, numDatasets); store.setImageInstrumentRef(instrumentID, numDatasets); numChannels = 0; extras = 1; } else if (qName.equals("Attachment") && level != MetadataLevel.MINIMUM) { if ("ContextDescription".equals(attributes.getValue("Name"))) { store.setImageDescription(attributes.getValue("Content"), numDatasets); } } else if (qName.equals("ChannelDescription")) { count++; numChannels++; lutNames.add(attributes.getValue("LUTName")); String bytesInc = attributes.getValue("BytesInc"); int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc); if (bytes > 0) { bytesPerAxis.put(new Integer(bytes), "C"); } } else if (qName.equals("DimensionDescription")) { int len = Integer.parseInt(attributes.getValue("NumberOfElements")); int id = Integer.parseInt(attributes.getValue("DimID")); double physicalLen = Double.parseDouble(attributes.getValue("Length")); String unit = attributes.getValue("Unit"); int nBytes = Integer.parseInt(attributes.getValue("BytesInc")); physicalLen /= len; if (unit.equals("Ks")) { physicalLen /= 1000; } else if (unit.equals("m")) { physicalLen *= 1000000; } Double physicalSize = new Double(physicalLen); CoreMetadata coreMeta = core.get(core.size() - 1); switch (id) { case 1: // X axis coreMeta.sizeX = len; coreMeta.rgb = (nBytes % 3) == 0; if (coreMeta.rgb) nBytes /= 3; switch (nBytes) { case 1: coreMeta.pixelType = FormatTools.UINT8; break; case 2: coreMeta.pixelType = FormatTools.UINT16; break; case 4: coreMeta.pixelType = FormatTools.FLOAT; break; } physicalSizeX = physicalSize.doubleValue(); store.setPixelsPhysicalSizeX(physicalSize, numDatasets); break; case 2: // Y axis if (coreMeta.sizeY != 0) { if (coreMeta.sizeZ == 1) { coreMeta.sizeZ = len; bytesPerAxis.put(new Integer(nBytes), "Z"); } else if (coreMeta.sizeT == 1) { coreMeta.sizeT = len; bytesPerAxis.put(new Integer(nBytes), "T"); } } else { coreMeta.sizeY = len; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); } break; case 3: // Z axis if (coreMeta.sizeY == 0) { // XZ scan - swap Y and Z coreMeta.sizeY = len; coreMeta.sizeZ = 1; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); bytesPerAxis.put(new Integer(nBytes), "Y"); } else { coreMeta.sizeZ = len; bytesPerAxis.put(new Integer(nBytes), "Z"); } break; case 4: // T axis if (coreMeta.sizeY == 0) { // XT scan - swap Y and T coreMeta.sizeY = len; coreMeta.sizeT = 1; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); bytesPerAxis.put(new Integer(nBytes), "Y"); } else { coreMeta.sizeT = len; bytesPerAxis.put(new Integer(nBytes), "T"); } break; default: extras *= len; } count++; } else if (qName.equals("ScannerSettingRecord") && level != MetadataLevel.MINIMUM) { String id = attributes.getValue("Identifier"); if (id == null) id = ""; if (id.equals("SystemType")) { store.setMicroscopeModel(value, numDatasets); store.setMicroscopeType(MicroscopeType.OTHER, numDatasets); } else if (id.equals("dblPinhole")) { pinhole = new Double(Double.parseDouble(value) * 1000000); } else if (id.equals("dblZoom")) { zoom = new Double(value); } else if (id.equals("dblStepSize")) { double zStep = Double.parseDouble(value) * 1000000; store.setPixelsPhysicalSizeZ(zStep, numDatasets); } else if (id.equals("nDelayTime_s")) { store.setPixelsTimeIncrement(new Double(value), numDatasets); } else if (id.equals("CameraName")) { store.setDetectorModel(value, numDatasets, 0); } else if (id.indexOf("WFC") == 1) { int c = 0; try { c = Integer.parseInt(id.replaceAll("\\D", "")); } catch (NumberFormatException e) { } Channel channel = channels.get(numDatasets + "-" + c); if (channel == null) channel = new Channel(); if (id.endsWith("ExposureTime")) { - store.setPlaneExposureTime(new Double(value), numDatasets, c); + try { + store.setPlaneExposureTime(new Double(value), numDatasets, c); + } + catch (IndexOutOfBoundsException e) { } } else if (id.endsWith("Gain")) { channel.gain = new Double(value); String detectorID = MetadataTools.createLSID("Detector", numDatasets, 0); channel.detector = detectorID; store.setDetectorID(detectorID, numDatasets, 0); store.setDetectorType(DetectorType.CCD, numDatasets, 0); } else if (id.endsWith("WaveLength")) { Integer exWave = new Integer(value); if (exWave > 0) { channel.exWave = new PositiveInteger(exWave); } } // NB: "UesrDefName" is not a typo. else if (id.endsWith("UesrDefName") && !value.equals("None")) { channel.name = value; } channels.put(numDatasets + "-" + c, channel); } } else if (qName.equals("FilterSettingRecord") && level != MetadataLevel.MINIMUM) { String object = attributes.getValue("ObjectName"); String attribute = attributes.getValue("Attribute"); String objectClass = attributes.getValue("ClassName"); String variant = attributes.getValue("Variant"); CoreMetadata coreMeta = core.get(numDatasets); if (attribute.equals("NumericalAperture")) { store.setObjectiveLensNA(new Double(variant), numDatasets, 0); } else if (attribute.equals("OrderNumber")) { store.setObjectiveSerialNumber(variant, numDatasets, 0); } else if (objectClass.equals("CDetectionUnit")) { if (attribute.equals("State")) { Detector d = new Detector(); String data = attributes.getValue("data"); if (data == null) data = attributes.getValue("Data"); d.channel = data == null ? 0 : Integer.parseInt(data); d.type = "PMT"; d.model = object; d.active = variant.equals("Active"); d.zoom = zoom; detectors.add(d); } else if (attribute.equals("HighVoltage")) { Detector d = detectors.get(detectors.size() - 1); d.voltage = new Double(variant); } else if (attribute.equals("VideoOffset")) { Detector d = detectors.get(detectors.size() - 1); d.offset = new Double(variant); } } else if (attribute.equals("Objective")) { StringTokenizer tokens = new StringTokenizer(variant, " "); boolean foundMag = false; StringBuffer model = new StringBuffer(); while (!foundMag) { String token = tokens.nextToken(); int x = token.indexOf("x"); if (x != -1) { foundMag = true; int mag = (int) Double.parseDouble(token.substring(0, x)); String na = token.substring(x + 1); store.setObjectiveNominalMagnification( new PositiveInteger(mag), numDatasets, 0); store.setObjectiveLensNA(new Double(na), numDatasets, 0); } else { model.append(token); model.append(" "); } } String immersion = "Other"; if (tokens.hasMoreTokens()) { immersion = tokens.nextToken(); if (immersion == null || immersion.trim().equals("")) { immersion = "Other"; } } try { ImmersionEnumHandler handler = new ImmersionEnumHandler(); store.setObjectiveImmersion( (Immersion) handler.getEnumeration(immersion), numDatasets, 0); } catch (EnumerationException e) { } String correction = "Other"; if (tokens.hasMoreTokens()) { correction = tokens.nextToken(); if (correction == null || correction.trim().equals("")) { correction = "Other"; } } try { CorrectionEnumHandler handler = new CorrectionEnumHandler(); store.setObjectiveCorrection( (Correction) handler.getEnumeration(correction), numDatasets, 0); } catch (EnumerationException e) { } store.setObjectiveModel(model.toString().trim(), numDatasets, 0); } else if (attribute.equals("RefractionIndex")) { String id = MetadataTools.createLSID("Objective", numDatasets, 0); store.setObjectiveID(id, numDatasets, 0); store.setImageObjectiveSettingsID(id, numDatasets); store.setImageObjectiveSettingsRefractiveIndex(new Double(variant), numDatasets); } else if (attribute.equals("XPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posX = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionX(posX, numDatasets, image); } if (numChannels == 0) xPos.add(posX); } else if (attribute.equals("YPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posY = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionY(posY, numDatasets, image); } if (numChannels == 0) yPos.add(posY); } else if (attribute.equals("ZPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posZ = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionZ(posZ, numDatasets, image); } if (numChannels == 0) zPos.add(posZ); } else if (objectClass.equals("CSpectrophotometerUnit")) { Integer v = null; try { v = new Integer((int) Double.parseDouble(variant)); } catch (NumberFormatException e) { } if (attributes.getValue("Description").endsWith("(left)")) { String id = MetadataTools.createLSID("Filter", numDatasets, nextFilter); store.setFilterID(id, numDatasets, nextFilter); store.setFilterModel(object, numDatasets, nextFilter); if (v != null) { store.setTransmittanceRangeCutIn( new PositiveInteger(v), numDatasets, nextFilter); } } else if (attributes.getValue("Description").endsWith("(right)")) { if (v != null) { store.setTransmittanceRangeCutOut( new PositiveInteger(v), numDatasets, nextFilter); nextFilter++; } } } } else if (qName.equals("Detector") && level != MetadataLevel.MINIMUM) { String v = attributes.getValue("Gain"); Double gain = v == null ? null : new Double(v); v = attributes.getValue("Offset"); Double offset = v == null ? null : new Double(v); boolean active = "1".equals(attributes.getValue("IsActive")); if (active) { // find the corresponding MultiBand and Detector MultiBand m = null; Detector detector = null; Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1); String c = attributes.getValue("Channel"); int channel = c == null ? 0 : Integer.parseInt(c); for (MultiBand mb : multiBands) { if (mb.channel == channel) { m = mb; break; } } for (Detector d : detectors) { if (d.channel == channel) { detector = d; break; } } String id = MetadataTools.createLSID("Detector", numDatasets, nextChannel); if (m != null) { String channelID = MetadataTools.createLSID( "Channel", numDatasets, nextChannel); store.setChannelID(channelID, numDatasets, nextChannel); store.setChannelName(m.dyeName, numDatasets, nextChannel); String filter = MetadataTools.createLSID("Filter", numDatasets, nextFilter); store.setFilterID(filter, numDatasets, nextFilter); store.setTransmittanceRangeCutIn( new PositiveInteger(m.cutIn), numDatasets, nextFilter); store.setTransmittanceRangeCutOut( new PositiveInteger(m.cutOut), numDatasets, nextFilter); store.setLightPathEmissionFilterRef( filter, numDatasets, nextChannel, 0); nextFilter++; store.setDetectorID(id, numDatasets, nextChannel); store.setDetectorType(DetectorType.PMT, numDatasets, nextChannel); store.setDetectorSettingsGain(gain, numDatasets, nextChannel); store.setDetectorSettingsOffset(offset, numDatasets, nextChannel); store.setDetectorSettingsID(id, numDatasets, nextChannel); } store.setDetectorID(id, numDatasets, nextChannel); if (detector != null) { store.setDetectorSettingsGain(gain, numDatasets, nextChannel); store.setDetectorSettingsOffset(offset, numDatasets, nextChannel); store.setDetectorSettingsID(id, numDatasets, nextChannel); try { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); store.setDetectorType( (DetectorType) handler.getEnumeration(detector.type), numDatasets, nextChannel); } catch (EnumerationException e) { } store.setDetectorModel(detector.model, numDatasets, nextChannel); store.setDetectorZoom(detector.zoom, numDatasets, nextChannel); store.setDetectorOffset(detector.offset, numDatasets, nextChannel); store.setDetectorVoltage(detector.voltage, numDatasets, nextChannel); } if (laser != null && laser.intensity < 100) { store.setChannelLightSourceSettingsID(laser.id, numDatasets, nextChannel); store.setChannelLightSourceSettingsAttenuation( new PercentFraction((float) laser.intensity / 100f), numDatasets, nextChannel); store.setChannelExcitationWavelength( new PositiveInteger(laser.wavelength), numDatasets, nextChannel); } nextChannel++; } } else if (qName.equals("LaserLineSetting") && level != MetadataLevel.MINIMUM) { Laser l = new Laser(); String lineIndex = attributes.getValue("LineIndex"); String qual = attributes.getValue("Qualifier"); l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex); int qualifier = qual == null ? 0 : Integer.parseInt(qual); l.index += (2 - (qualifier / 10)); if (l.index < 0) l.index = 0; l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index); l.wavelength = new Integer(attributes.getValue("LaserLine")); while (l.index > laserCount) { String lsid = MetadataTools.createLSID("LightSource", numDatasets, laserCount); store.setLaserID(lsid, numDatasets, laserCount); laserCount++; } store.setLaserID(l.id, numDatasets, l.index); laserCount++; if (l.wavelength > 0) { store.setLaserWavelength( new PositiveInteger(l.wavelength), numDatasets, l.index); } store.setLaserType(LaserType.OTHER, numDatasets, l.index); store.setLaserLaserMedium(LaserMedium.OTHER, numDatasets, l.index); String intensity = attributes.getValue("IntensityDev"); l.intensity = intensity == null ? 0d : Double.parseDouble(intensity); if (l.intensity > 0) { l.intensity = 100d - l.intensity; lasers.add(l); } } else if (qName.equals("TimeStamp") && numDatasets >= 0) { String stampHigh = attributes.getValue("HighInteger"); String stampLow = attributes.getValue("LowInteger"); long high = stampHigh == null ? 0 : Long.parseLong(stampHigh); long low = stampLow == null ? 0 : Long.parseLong(stampLow); long ms = DateTools.getMillisFromTicks(high, low); if (count == 0) { String date = DateTools.convertDate(ms, DateTools.COBOL); if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) < System.currentTimeMillis()) { store.setImageAcquiredDate(date, numDatasets); } firstStamp = ms; store.setPlaneDeltaT(0.0, numDatasets, count); } else if (level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { ms -= firstStamp; store.setPlaneDeltaT(ms / 1000.0, numDatasets, count); } } count++; } else if (qName.equals("RelTimeStamp") && level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { Double time = new Double(attributes.getValue("Time")); store.setPlaneDeltaT(time, numDatasets, count++); } } else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) { roi = new ROI(); String type = attributes.getValue("type"); if (type != null) roi.type = Integer.parseInt(type); String color = attributes.getValue("color"); if (color != null) roi.color = Integer.parseInt(color); roi.name = attributes.getValue("name"); roi.fontName = attributes.getValue("fontName"); roi.fontSize = attributes.getValue("fontSize"); roi.transX = parseDouble(attributes.getValue("transTransX")); roi.transY = parseDouble(attributes.getValue("transTransY")); roi.scaleX = parseDouble(attributes.getValue("transScalingX")); roi.scaleY = parseDouble(attributes.getValue("transScalingY")); roi.rotation = parseDouble(attributes.getValue("transRotation")); String linewidth = attributes.getValue("linewidth"); if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth); roi.text = attributes.getValue("text"); } else if (qName.equals("Vertex") && level != MetadataLevel.MINIMUM) { String x = attributes.getValue("x"); String y = attributes.getValue("y"); if (x != null) { x = x.replaceAll(",", "."); roi.x.add(new Double(x)); } if (y != null) { y = y.replaceAll(",", "."); roi.y.add(new Double(y)); } } else if (qName.equals("ROI")) { alternateCenter = true; } else if (qName.equals("MultiBand") && level != MetadataLevel.MINIMUM) { MultiBand m = new MultiBand(); m.dyeName = attributes.getValue("DyeName"); m.channel = Integer.parseInt(attributes.getValue("Channel")); m.cutIn = (int) Math.round(Double.parseDouble(attributes.getValue("LeftWorld"))); m.cutOut = (int) Math.round(Double.parseDouble(attributes.getValue("RightWorld"))); multiBands.add(m); } else if (qName.equals("ChannelInfo")) { int index = Integer.parseInt(attributes.getValue("Index")); channels.remove(numDatasets + "-" + index); } else count = 0; if (numDatasets == oldSeriesCount) storeSeriesHashtable(numDatasets, h); } // -- Helper methods -- private Hashtable getSeriesHashtable(int series) { if (series < 0 || series >= core.size()) return new Hashtable(); return core.get(series).seriesMetadata; } private void storeSeriesHashtable(int series, Hashtable h) { if (series < 0) return; Object[] keys = h.keySet().toArray(new Object[h.size()]); for (Object key : keys) { Object value = h.get(key); if (value instanceof Vector) { Vector v = (Vector) value; for (int o=0; o<v.size(); o++) { h.put(key + " " + (o + 1), v.get(o)); } h.remove(key); } } CoreMetadata coreMeta = core.get(series); coreMeta.seriesMetadata = h; core.setElementAt(coreMeta, series); } // -- Helper class -- class ROI { // -- Constants -- public static final int TEXT = 512; public static final int SCALE_BAR = 8192; public static final int POLYGON = 32; public static final int RECTANGLE = 16; public static final int LINE = 256; public static final int ARROW = 2; // -- Fields -- public int type; public Vector<Double> x = new Vector<Double>(); public Vector<Double> y = new Vector<Double>(); // center point of the ROI public double transX, transY; // transformation parameters public double scaleX, scaleY; public double rotation; public int color; public int linewidth; public String text; public String fontName; public String fontSize; public String name; private boolean normalized = false; // -- ROI API methods -- public void storeROI(MetadataStore store, int series, int roi) { if (level == MetadataLevel.NO_OVERLAYS || level == MetadataLevel.MINIMUM) { return; } // keep in mind that vertices are given relative to the center // point of the ROI and the transX/transY values are relative to // the center point of the image store.setROIID(MetadataTools.createLSID("ROI", roi), roi); store.setTextID(MetadataTools.createLSID("Shape", roi, 0), roi, 0); if (text == null) text = ""; store.setTextValue(text, roi, 0); if (fontSize != null) { store.setTextFontSize( new NonNegativeInteger((int) Double.parseDouble(fontSize)), roi, 0); } store.setTextStrokeWidth(new Double(linewidth), roi, 0); if (!normalized) normalize(); double cornerX = x.get(0).doubleValue(); double cornerY = y.get(0).doubleValue(); store.setTextX(cornerX, roi, 0); store.setTextY(cornerY, roi, 0); int centerX = (core.get(series).sizeX / 2) - 1; int centerY = (core.get(series).sizeY / 2) - 1; double roiX = centerX + transX; double roiY = centerY + transY; if (alternateCenter) { roiX = transX - 2 * cornerX; roiY = transY - 2 * cornerY; } // TODO : rotation/scaling not populated String shapeID = MetadataTools.createLSID("Shape", roi, 1); switch (type) { case POLYGON: StringBuffer points = new StringBuffer(); for (int i=0; i<x.size(); i++) { points.append(x.get(i).doubleValue() + roiX); points.append(","); points.append(y.get(i).doubleValue() + roiY); if (i < x.size() - 1) points.append(" "); } store.setPolylineID(shapeID, roi, 1); store.setPolylinePoints(points.toString(), roi, 1); store.setPolylineClosed(Boolean.TRUE, roi, 1); break; case TEXT: case RECTANGLE: store.setRectangleID(shapeID, roi, 1); store.setRectangleX(roiX - Math.abs(cornerX), roi, 1); store.setRectangleY(roiY - Math.abs(cornerY), roi, 1); double width = 2 * Math.abs(cornerX); double height = 2 * Math.abs(cornerY); store.setRectangleWidth(width, roi, 1); store.setRectangleHeight(height, roi, 1); break; case SCALE_BAR: case ARROW: case LINE: store.setLineID(shapeID, roi, 1); store.setLineX1(roiX + x.get(0), roi, 1); store.setLineY1(roiY + y.get(0), roi, 1); store.setLineX2(roiX + x.get(1), roi, 1); store.setLineY2(roiY + y.get(1), roi, 1); break; } } // -- Helper methods -- /** * Vertices and transformation values are not stored in pixel coordinates. * We need to convert them from physical coordinates to pixel coordinates * so that they can be stored in a MetadataStore. */ private void normalize() { if (normalized) return; // coordinates are in meters transX *= 1000000; transY *= 1000000; transX *= (1 / physicalSizeX); transY *= (1 / physicalSizeY); for (int i=0; i<x.size(); i++) { double coordinate = x.get(i).doubleValue() * 1000000; coordinate *= (1 / physicalSizeX); x.setElementAt(coordinate, i); } for (int i=0; i<y.size(); i++) { double coordinate = y.get(i).doubleValue() * 1000000; coordinate *= (1 / physicalSizeY); y.setElementAt(coordinate, i); } normalized = true; } } private double parseDouble(String number) { if (number != null) { number = number.replaceAll(",", "."); return Double.parseDouble(number); } return 0; } private void storeKeyValue(Hashtable h, String key, String value) { if (h.get(key) == null) { h.put(key, value); } else { Object oldValue = h.get(key); if (oldValue instanceof Vector) { Vector values = (Vector) oldValue; values.add(value); h.put(key, values); } else { Vector values = new Vector(); values.add(oldValue); values.add(value); h.put(key, values); } } } // -- Helper classes -- class MultiBand { public int channel; public int cutIn; public int cutOut; public String dyeName; } class Detector { public int channel; public Double zoom; public String type; public String model; public boolean active; public Double voltage; public Double offset; } class Laser { public Integer wavelength; public double intensity; public String id; public int index; } class Channel { public String detector; public Double gain; public PositiveInteger exWave; public String name; } }
true
true
public void startElement(String uri, String localName, String qName, Attributes attributes) { if (attributes.getLength() > 0 && !qName.equals("Element") && !qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader")) { nameStack.push(qName); } int oldSeriesCount = numDatasets; Hashtable h = getSeriesHashtable(numDatasets); if (qName.equals("LDM_Block_Sequential_Master")) { canParse = false; } else if (qName.startsWith("LDM")) { linkedInstruments = true; } if (!canParse) return; StringBuffer key = new StringBuffer(); for (String k : nameStack) { key.append(k); key.append("|"); } String suffix = attributes.getValue("Identifier"); String value = attributes.getValue("Variant"); if (suffix == null) suffix = attributes.getValue("Description"); if (level != MetadataLevel.MINIMUM) { if (suffix != null && value != null) { storeKeyValue(h, key.toString() + suffix, value); } else { for (int i=0; i<attributes.getLength(); i++) { String name = attributes.getQName(i); storeKeyValue(h, key.toString() + name, attributes.getValue(i)); } } } if (qName.equals("Element")) { elementName = attributes.getValue("Name"); } else if (qName.equals("Collection")) { collection = elementName; } else if (qName.equals("Image")) { if (!linkedInstruments && level != MetadataLevel.MINIMUM) { int c = 0; for (Detector d : detectors) { String id = MetadataTools.createLSID( "Detector", numDatasets, detectorChannel); store.setDetectorID(id, numDatasets, detectorChannel); try { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); store.setDetectorType((DetectorType) handler.getEnumeration(d.type), numDatasets, detectorChannel); } catch (EnumerationException e) { } store.setDetectorModel(d.model, numDatasets, detectorChannel); store.setDetectorZoom(d.zoom, numDatasets, detectorChannel); store.setDetectorOffset(d.offset, numDatasets, detectorChannel); store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel); if (c < numChannels) { if (d.active) { store.setDetectorSettingsOffset(d.offset, numDatasets, c); store.setDetectorSettingsID(id, numDatasets, c); c++; } } detectorChannel++; } int filter = 0; for (int i=0; i<nextFilter; i++) { while (filter < detectors.size() && !detectors.get(filter).active) { filter++; } if (filter >= detectors.size() || filter >= nextFilter) break; String id = MetadataTools.createLSID("Filter", numDatasets, filter); if (i < numChannels && detectors.get(filter).active) { String lsid = MetadataTools.createLSID("Channel", numDatasets, i); store.setChannelID(lsid, numDatasets, i); store.setLightPathEmissionFilterRef(id, numDatasets, i, 0); } filter++; } } core.add(new CoreMetadata()); numDatasets++; laserCount = 0; linkedInstruments = false; detectorChannel = 0; detectors.clear(); lasers.clear(); nextFilter = 0; String name = elementName; if (collection != null) name = collection + "/" + name; store.setImageName(name, numDatasets); String instrumentID = MetadataTools.createLSID("Instrument", numDatasets); store.setInstrumentID(instrumentID, numDatasets); store.setImageInstrumentRef(instrumentID, numDatasets); numChannels = 0; extras = 1; } else if (qName.equals("Attachment") && level != MetadataLevel.MINIMUM) { if ("ContextDescription".equals(attributes.getValue("Name"))) { store.setImageDescription(attributes.getValue("Content"), numDatasets); } } else if (qName.equals("ChannelDescription")) { count++; numChannels++; lutNames.add(attributes.getValue("LUTName")); String bytesInc = attributes.getValue("BytesInc"); int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc); if (bytes > 0) { bytesPerAxis.put(new Integer(bytes), "C"); } } else if (qName.equals("DimensionDescription")) { int len = Integer.parseInt(attributes.getValue("NumberOfElements")); int id = Integer.parseInt(attributes.getValue("DimID")); double physicalLen = Double.parseDouble(attributes.getValue("Length")); String unit = attributes.getValue("Unit"); int nBytes = Integer.parseInt(attributes.getValue("BytesInc")); physicalLen /= len; if (unit.equals("Ks")) { physicalLen /= 1000; } else if (unit.equals("m")) { physicalLen *= 1000000; } Double physicalSize = new Double(physicalLen); CoreMetadata coreMeta = core.get(core.size() - 1); switch (id) { case 1: // X axis coreMeta.sizeX = len; coreMeta.rgb = (nBytes % 3) == 0; if (coreMeta.rgb) nBytes /= 3; switch (nBytes) { case 1: coreMeta.pixelType = FormatTools.UINT8; break; case 2: coreMeta.pixelType = FormatTools.UINT16; break; case 4: coreMeta.pixelType = FormatTools.FLOAT; break; } physicalSizeX = physicalSize.doubleValue(); store.setPixelsPhysicalSizeX(physicalSize, numDatasets); break; case 2: // Y axis if (coreMeta.sizeY != 0) { if (coreMeta.sizeZ == 1) { coreMeta.sizeZ = len; bytesPerAxis.put(new Integer(nBytes), "Z"); } else if (coreMeta.sizeT == 1) { coreMeta.sizeT = len; bytesPerAxis.put(new Integer(nBytes), "T"); } } else { coreMeta.sizeY = len; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); } break; case 3: // Z axis if (coreMeta.sizeY == 0) { // XZ scan - swap Y and Z coreMeta.sizeY = len; coreMeta.sizeZ = 1; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); bytesPerAxis.put(new Integer(nBytes), "Y"); } else { coreMeta.sizeZ = len; bytesPerAxis.put(new Integer(nBytes), "Z"); } break; case 4: // T axis if (coreMeta.sizeY == 0) { // XT scan - swap Y and T coreMeta.sizeY = len; coreMeta.sizeT = 1; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); bytesPerAxis.put(new Integer(nBytes), "Y"); } else { coreMeta.sizeT = len; bytesPerAxis.put(new Integer(nBytes), "T"); } break; default: extras *= len; } count++; } else if (qName.equals("ScannerSettingRecord") && level != MetadataLevel.MINIMUM) { String id = attributes.getValue("Identifier"); if (id == null) id = ""; if (id.equals("SystemType")) { store.setMicroscopeModel(value, numDatasets); store.setMicroscopeType(MicroscopeType.OTHER, numDatasets); } else if (id.equals("dblPinhole")) { pinhole = new Double(Double.parseDouble(value) * 1000000); } else if (id.equals("dblZoom")) { zoom = new Double(value); } else if (id.equals("dblStepSize")) { double zStep = Double.parseDouble(value) * 1000000; store.setPixelsPhysicalSizeZ(zStep, numDatasets); } else if (id.equals("nDelayTime_s")) { store.setPixelsTimeIncrement(new Double(value), numDatasets); } else if (id.equals("CameraName")) { store.setDetectorModel(value, numDatasets, 0); } else if (id.indexOf("WFC") == 1) { int c = 0; try { c = Integer.parseInt(id.replaceAll("\\D", "")); } catch (NumberFormatException e) { } Channel channel = channels.get(numDatasets + "-" + c); if (channel == null) channel = new Channel(); if (id.endsWith("ExposureTime")) { store.setPlaneExposureTime(new Double(value), numDatasets, c); } else if (id.endsWith("Gain")) { channel.gain = new Double(value); String detectorID = MetadataTools.createLSID("Detector", numDatasets, 0); channel.detector = detectorID; store.setDetectorID(detectorID, numDatasets, 0); store.setDetectorType(DetectorType.CCD, numDatasets, 0); } else if (id.endsWith("WaveLength")) { Integer exWave = new Integer(value); if (exWave > 0) { channel.exWave = new PositiveInteger(exWave); } } // NB: "UesrDefName" is not a typo. else if (id.endsWith("UesrDefName") && !value.equals("None")) { channel.name = value; } channels.put(numDatasets + "-" + c, channel); } } else if (qName.equals("FilterSettingRecord") && level != MetadataLevel.MINIMUM) { String object = attributes.getValue("ObjectName"); String attribute = attributes.getValue("Attribute"); String objectClass = attributes.getValue("ClassName"); String variant = attributes.getValue("Variant"); CoreMetadata coreMeta = core.get(numDatasets); if (attribute.equals("NumericalAperture")) { store.setObjectiveLensNA(new Double(variant), numDatasets, 0); } else if (attribute.equals("OrderNumber")) { store.setObjectiveSerialNumber(variant, numDatasets, 0); } else if (objectClass.equals("CDetectionUnit")) { if (attribute.equals("State")) { Detector d = new Detector(); String data = attributes.getValue("data"); if (data == null) data = attributes.getValue("Data"); d.channel = data == null ? 0 : Integer.parseInt(data); d.type = "PMT"; d.model = object; d.active = variant.equals("Active"); d.zoom = zoom; detectors.add(d); } else if (attribute.equals("HighVoltage")) { Detector d = detectors.get(detectors.size() - 1); d.voltage = new Double(variant); } else if (attribute.equals("VideoOffset")) { Detector d = detectors.get(detectors.size() - 1); d.offset = new Double(variant); } } else if (attribute.equals("Objective")) { StringTokenizer tokens = new StringTokenizer(variant, " "); boolean foundMag = false; StringBuffer model = new StringBuffer(); while (!foundMag) { String token = tokens.nextToken(); int x = token.indexOf("x"); if (x != -1) { foundMag = true; int mag = (int) Double.parseDouble(token.substring(0, x)); String na = token.substring(x + 1); store.setObjectiveNominalMagnification( new PositiveInteger(mag), numDatasets, 0); store.setObjectiveLensNA(new Double(na), numDatasets, 0); } else { model.append(token); model.append(" "); } } String immersion = "Other"; if (tokens.hasMoreTokens()) { immersion = tokens.nextToken(); if (immersion == null || immersion.trim().equals("")) { immersion = "Other"; } } try { ImmersionEnumHandler handler = new ImmersionEnumHandler(); store.setObjectiveImmersion( (Immersion) handler.getEnumeration(immersion), numDatasets, 0); } catch (EnumerationException e) { } String correction = "Other"; if (tokens.hasMoreTokens()) { correction = tokens.nextToken(); if (correction == null || correction.trim().equals("")) { correction = "Other"; } } try { CorrectionEnumHandler handler = new CorrectionEnumHandler(); store.setObjectiveCorrection( (Correction) handler.getEnumeration(correction), numDatasets, 0); } catch (EnumerationException e) { } store.setObjectiveModel(model.toString().trim(), numDatasets, 0); } else if (attribute.equals("RefractionIndex")) { String id = MetadataTools.createLSID("Objective", numDatasets, 0); store.setObjectiveID(id, numDatasets, 0); store.setImageObjectiveSettingsID(id, numDatasets); store.setImageObjectiveSettingsRefractiveIndex(new Double(variant), numDatasets); } else if (attribute.equals("XPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posX = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionX(posX, numDatasets, image); } if (numChannels == 0) xPos.add(posX); } else if (attribute.equals("YPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posY = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionY(posY, numDatasets, image); } if (numChannels == 0) yPos.add(posY); } else if (attribute.equals("ZPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posZ = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionZ(posZ, numDatasets, image); } if (numChannels == 0) zPos.add(posZ); } else if (objectClass.equals("CSpectrophotometerUnit")) { Integer v = null; try { v = new Integer((int) Double.parseDouble(variant)); } catch (NumberFormatException e) { } if (attributes.getValue("Description").endsWith("(left)")) { String id = MetadataTools.createLSID("Filter", numDatasets, nextFilter); store.setFilterID(id, numDatasets, nextFilter); store.setFilterModel(object, numDatasets, nextFilter); if (v != null) { store.setTransmittanceRangeCutIn( new PositiveInteger(v), numDatasets, nextFilter); } } else if (attributes.getValue("Description").endsWith("(right)")) { if (v != null) { store.setTransmittanceRangeCutOut( new PositiveInteger(v), numDatasets, nextFilter); nextFilter++; } } } } else if (qName.equals("Detector") && level != MetadataLevel.MINIMUM) { String v = attributes.getValue("Gain"); Double gain = v == null ? null : new Double(v); v = attributes.getValue("Offset"); Double offset = v == null ? null : new Double(v); boolean active = "1".equals(attributes.getValue("IsActive")); if (active) { // find the corresponding MultiBand and Detector MultiBand m = null; Detector detector = null; Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1); String c = attributes.getValue("Channel"); int channel = c == null ? 0 : Integer.parseInt(c); for (MultiBand mb : multiBands) { if (mb.channel == channel) { m = mb; break; } } for (Detector d : detectors) { if (d.channel == channel) { detector = d; break; } } String id = MetadataTools.createLSID("Detector", numDatasets, nextChannel); if (m != null) { String channelID = MetadataTools.createLSID( "Channel", numDatasets, nextChannel); store.setChannelID(channelID, numDatasets, nextChannel); store.setChannelName(m.dyeName, numDatasets, nextChannel); String filter = MetadataTools.createLSID("Filter", numDatasets, nextFilter); store.setFilterID(filter, numDatasets, nextFilter); store.setTransmittanceRangeCutIn( new PositiveInteger(m.cutIn), numDatasets, nextFilter); store.setTransmittanceRangeCutOut( new PositiveInteger(m.cutOut), numDatasets, nextFilter); store.setLightPathEmissionFilterRef( filter, numDatasets, nextChannel, 0); nextFilter++; store.setDetectorID(id, numDatasets, nextChannel); store.setDetectorType(DetectorType.PMT, numDatasets, nextChannel); store.setDetectorSettingsGain(gain, numDatasets, nextChannel); store.setDetectorSettingsOffset(offset, numDatasets, nextChannel); store.setDetectorSettingsID(id, numDatasets, nextChannel); } store.setDetectorID(id, numDatasets, nextChannel); if (detector != null) { store.setDetectorSettingsGain(gain, numDatasets, nextChannel); store.setDetectorSettingsOffset(offset, numDatasets, nextChannel); store.setDetectorSettingsID(id, numDatasets, nextChannel); try { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); store.setDetectorType( (DetectorType) handler.getEnumeration(detector.type), numDatasets, nextChannel); } catch (EnumerationException e) { } store.setDetectorModel(detector.model, numDatasets, nextChannel); store.setDetectorZoom(detector.zoom, numDatasets, nextChannel); store.setDetectorOffset(detector.offset, numDatasets, nextChannel); store.setDetectorVoltage(detector.voltage, numDatasets, nextChannel); } if (laser != null && laser.intensity < 100) { store.setChannelLightSourceSettingsID(laser.id, numDatasets, nextChannel); store.setChannelLightSourceSettingsAttenuation( new PercentFraction((float) laser.intensity / 100f), numDatasets, nextChannel); store.setChannelExcitationWavelength( new PositiveInteger(laser.wavelength), numDatasets, nextChannel); } nextChannel++; } } else if (qName.equals("LaserLineSetting") && level != MetadataLevel.MINIMUM) { Laser l = new Laser(); String lineIndex = attributes.getValue("LineIndex"); String qual = attributes.getValue("Qualifier"); l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex); int qualifier = qual == null ? 0 : Integer.parseInt(qual); l.index += (2 - (qualifier / 10)); if (l.index < 0) l.index = 0; l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index); l.wavelength = new Integer(attributes.getValue("LaserLine")); while (l.index > laserCount) { String lsid = MetadataTools.createLSID("LightSource", numDatasets, laserCount); store.setLaserID(lsid, numDatasets, laserCount); laserCount++; } store.setLaserID(l.id, numDatasets, l.index); laserCount++; if (l.wavelength > 0) { store.setLaserWavelength( new PositiveInteger(l.wavelength), numDatasets, l.index); } store.setLaserType(LaserType.OTHER, numDatasets, l.index); store.setLaserLaserMedium(LaserMedium.OTHER, numDatasets, l.index); String intensity = attributes.getValue("IntensityDev"); l.intensity = intensity == null ? 0d : Double.parseDouble(intensity); if (l.intensity > 0) { l.intensity = 100d - l.intensity; lasers.add(l); } } else if (qName.equals("TimeStamp") && numDatasets >= 0) { String stampHigh = attributes.getValue("HighInteger"); String stampLow = attributes.getValue("LowInteger"); long high = stampHigh == null ? 0 : Long.parseLong(stampHigh); long low = stampLow == null ? 0 : Long.parseLong(stampLow); long ms = DateTools.getMillisFromTicks(high, low); if (count == 0) { String date = DateTools.convertDate(ms, DateTools.COBOL); if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) < System.currentTimeMillis()) { store.setImageAcquiredDate(date, numDatasets); } firstStamp = ms; store.setPlaneDeltaT(0.0, numDatasets, count); } else if (level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { ms -= firstStamp; store.setPlaneDeltaT(ms / 1000.0, numDatasets, count); } } count++; } else if (qName.equals("RelTimeStamp") && level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { Double time = new Double(attributes.getValue("Time")); store.setPlaneDeltaT(time, numDatasets, count++); } } else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) { roi = new ROI(); String type = attributes.getValue("type"); if (type != null) roi.type = Integer.parseInt(type); String color = attributes.getValue("color"); if (color != null) roi.color = Integer.parseInt(color); roi.name = attributes.getValue("name"); roi.fontName = attributes.getValue("fontName"); roi.fontSize = attributes.getValue("fontSize"); roi.transX = parseDouble(attributes.getValue("transTransX")); roi.transY = parseDouble(attributes.getValue("transTransY")); roi.scaleX = parseDouble(attributes.getValue("transScalingX")); roi.scaleY = parseDouble(attributes.getValue("transScalingY")); roi.rotation = parseDouble(attributes.getValue("transRotation")); String linewidth = attributes.getValue("linewidth"); if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth); roi.text = attributes.getValue("text"); } else if (qName.equals("Vertex") && level != MetadataLevel.MINIMUM) { String x = attributes.getValue("x"); String y = attributes.getValue("y"); if (x != null) { x = x.replaceAll(",", "."); roi.x.add(new Double(x)); } if (y != null) { y = y.replaceAll(",", "."); roi.y.add(new Double(y)); } } else if (qName.equals("ROI")) { alternateCenter = true; } else if (qName.equals("MultiBand") && level != MetadataLevel.MINIMUM) { MultiBand m = new MultiBand(); m.dyeName = attributes.getValue("DyeName"); m.channel = Integer.parseInt(attributes.getValue("Channel")); m.cutIn = (int) Math.round(Double.parseDouble(attributes.getValue("LeftWorld"))); m.cutOut = (int) Math.round(Double.parseDouble(attributes.getValue("RightWorld"))); multiBands.add(m); } else if (qName.equals("ChannelInfo")) { int index = Integer.parseInt(attributes.getValue("Index")); channels.remove(numDatasets + "-" + index); } else count = 0; if (numDatasets == oldSeriesCount) storeSeriesHashtable(numDatasets, h); }
public void startElement(String uri, String localName, String qName, Attributes attributes) { if (attributes.getLength() > 0 && !qName.equals("Element") && !qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader")) { nameStack.push(qName); } int oldSeriesCount = numDatasets; Hashtable h = getSeriesHashtable(numDatasets); if (qName.equals("LDM_Block_Sequential_Master")) { canParse = false; } else if (qName.startsWith("LDM")) { linkedInstruments = true; } if (!canParse) return; StringBuffer key = new StringBuffer(); for (String k : nameStack) { key.append(k); key.append("|"); } String suffix = attributes.getValue("Identifier"); String value = attributes.getValue("Variant"); if (suffix == null) suffix = attributes.getValue("Description"); if (level != MetadataLevel.MINIMUM) { if (suffix != null && value != null) { storeKeyValue(h, key.toString() + suffix, value); } else { for (int i=0; i<attributes.getLength(); i++) { String name = attributes.getQName(i); storeKeyValue(h, key.toString() + name, attributes.getValue(i)); } } } if (qName.equals("Element")) { elementName = attributes.getValue("Name"); } else if (qName.equals("Collection")) { collection = elementName; } else if (qName.equals("Image")) { if (!linkedInstruments && level != MetadataLevel.MINIMUM) { int c = 0; for (Detector d : detectors) { String id = MetadataTools.createLSID( "Detector", numDatasets, detectorChannel); store.setDetectorID(id, numDatasets, detectorChannel); try { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); store.setDetectorType((DetectorType) handler.getEnumeration(d.type), numDatasets, detectorChannel); } catch (EnumerationException e) { } store.setDetectorModel(d.model, numDatasets, detectorChannel); store.setDetectorZoom(d.zoom, numDatasets, detectorChannel); store.setDetectorOffset(d.offset, numDatasets, detectorChannel); store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel); if (c < numChannels) { if (d.active) { store.setDetectorSettingsOffset(d.offset, numDatasets, c); store.setDetectorSettingsID(id, numDatasets, c); c++; } } detectorChannel++; } int filter = 0; for (int i=0; i<nextFilter; i++) { while (filter < detectors.size() && !detectors.get(filter).active) { filter++; } if (filter >= detectors.size() || filter >= nextFilter) break; String id = MetadataTools.createLSID("Filter", numDatasets, filter); if (i < numChannels && detectors.get(filter).active) { String lsid = MetadataTools.createLSID("Channel", numDatasets, i); store.setChannelID(lsid, numDatasets, i); store.setLightPathEmissionFilterRef(id, numDatasets, i, 0); } filter++; } } core.add(new CoreMetadata()); numDatasets++; laserCount = 0; linkedInstruments = false; detectorChannel = 0; detectors.clear(); lasers.clear(); nextFilter = 0; String name = elementName; if (collection != null) name = collection + "/" + name; store.setImageName(name, numDatasets); String instrumentID = MetadataTools.createLSID("Instrument", numDatasets); store.setInstrumentID(instrumentID, numDatasets); store.setImageInstrumentRef(instrumentID, numDatasets); numChannels = 0; extras = 1; } else if (qName.equals("Attachment") && level != MetadataLevel.MINIMUM) { if ("ContextDescription".equals(attributes.getValue("Name"))) { store.setImageDescription(attributes.getValue("Content"), numDatasets); } } else if (qName.equals("ChannelDescription")) { count++; numChannels++; lutNames.add(attributes.getValue("LUTName")); String bytesInc = attributes.getValue("BytesInc"); int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc); if (bytes > 0) { bytesPerAxis.put(new Integer(bytes), "C"); } } else if (qName.equals("DimensionDescription")) { int len = Integer.parseInt(attributes.getValue("NumberOfElements")); int id = Integer.parseInt(attributes.getValue("DimID")); double physicalLen = Double.parseDouble(attributes.getValue("Length")); String unit = attributes.getValue("Unit"); int nBytes = Integer.parseInt(attributes.getValue("BytesInc")); physicalLen /= len; if (unit.equals("Ks")) { physicalLen /= 1000; } else if (unit.equals("m")) { physicalLen *= 1000000; } Double physicalSize = new Double(physicalLen); CoreMetadata coreMeta = core.get(core.size() - 1); switch (id) { case 1: // X axis coreMeta.sizeX = len; coreMeta.rgb = (nBytes % 3) == 0; if (coreMeta.rgb) nBytes /= 3; switch (nBytes) { case 1: coreMeta.pixelType = FormatTools.UINT8; break; case 2: coreMeta.pixelType = FormatTools.UINT16; break; case 4: coreMeta.pixelType = FormatTools.FLOAT; break; } physicalSizeX = physicalSize.doubleValue(); store.setPixelsPhysicalSizeX(physicalSize, numDatasets); break; case 2: // Y axis if (coreMeta.sizeY != 0) { if (coreMeta.sizeZ == 1) { coreMeta.sizeZ = len; bytesPerAxis.put(new Integer(nBytes), "Z"); } else if (coreMeta.sizeT == 1) { coreMeta.sizeT = len; bytesPerAxis.put(new Integer(nBytes), "T"); } } else { coreMeta.sizeY = len; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); } break; case 3: // Z axis if (coreMeta.sizeY == 0) { // XZ scan - swap Y and Z coreMeta.sizeY = len; coreMeta.sizeZ = 1; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); bytesPerAxis.put(new Integer(nBytes), "Y"); } else { coreMeta.sizeZ = len; bytesPerAxis.put(new Integer(nBytes), "Z"); } break; case 4: // T axis if (coreMeta.sizeY == 0) { // XT scan - swap Y and T coreMeta.sizeY = len; coreMeta.sizeT = 1; physicalSizeY = physicalSize.doubleValue(); store.setPixelsPhysicalSizeY(physicalSize, numDatasets); bytesPerAxis.put(new Integer(nBytes), "Y"); } else { coreMeta.sizeT = len; bytesPerAxis.put(new Integer(nBytes), "T"); } break; default: extras *= len; } count++; } else if (qName.equals("ScannerSettingRecord") && level != MetadataLevel.MINIMUM) { String id = attributes.getValue("Identifier"); if (id == null) id = ""; if (id.equals("SystemType")) { store.setMicroscopeModel(value, numDatasets); store.setMicroscopeType(MicroscopeType.OTHER, numDatasets); } else if (id.equals("dblPinhole")) { pinhole = new Double(Double.parseDouble(value) * 1000000); } else if (id.equals("dblZoom")) { zoom = new Double(value); } else if (id.equals("dblStepSize")) { double zStep = Double.parseDouble(value) * 1000000; store.setPixelsPhysicalSizeZ(zStep, numDatasets); } else if (id.equals("nDelayTime_s")) { store.setPixelsTimeIncrement(new Double(value), numDatasets); } else if (id.equals("CameraName")) { store.setDetectorModel(value, numDatasets, 0); } else if (id.indexOf("WFC") == 1) { int c = 0; try { c = Integer.parseInt(id.replaceAll("\\D", "")); } catch (NumberFormatException e) { } Channel channel = channels.get(numDatasets + "-" + c); if (channel == null) channel = new Channel(); if (id.endsWith("ExposureTime")) { try { store.setPlaneExposureTime(new Double(value), numDatasets, c); } catch (IndexOutOfBoundsException e) { } } else if (id.endsWith("Gain")) { channel.gain = new Double(value); String detectorID = MetadataTools.createLSID("Detector", numDatasets, 0); channel.detector = detectorID; store.setDetectorID(detectorID, numDatasets, 0); store.setDetectorType(DetectorType.CCD, numDatasets, 0); } else if (id.endsWith("WaveLength")) { Integer exWave = new Integer(value); if (exWave > 0) { channel.exWave = new PositiveInteger(exWave); } } // NB: "UesrDefName" is not a typo. else if (id.endsWith("UesrDefName") && !value.equals("None")) { channel.name = value; } channels.put(numDatasets + "-" + c, channel); } } else if (qName.equals("FilterSettingRecord") && level != MetadataLevel.MINIMUM) { String object = attributes.getValue("ObjectName"); String attribute = attributes.getValue("Attribute"); String objectClass = attributes.getValue("ClassName"); String variant = attributes.getValue("Variant"); CoreMetadata coreMeta = core.get(numDatasets); if (attribute.equals("NumericalAperture")) { store.setObjectiveLensNA(new Double(variant), numDatasets, 0); } else if (attribute.equals("OrderNumber")) { store.setObjectiveSerialNumber(variant, numDatasets, 0); } else if (objectClass.equals("CDetectionUnit")) { if (attribute.equals("State")) { Detector d = new Detector(); String data = attributes.getValue("data"); if (data == null) data = attributes.getValue("Data"); d.channel = data == null ? 0 : Integer.parseInt(data); d.type = "PMT"; d.model = object; d.active = variant.equals("Active"); d.zoom = zoom; detectors.add(d); } else if (attribute.equals("HighVoltage")) { Detector d = detectors.get(detectors.size() - 1); d.voltage = new Double(variant); } else if (attribute.equals("VideoOffset")) { Detector d = detectors.get(detectors.size() - 1); d.offset = new Double(variant); } } else if (attribute.equals("Objective")) { StringTokenizer tokens = new StringTokenizer(variant, " "); boolean foundMag = false; StringBuffer model = new StringBuffer(); while (!foundMag) { String token = tokens.nextToken(); int x = token.indexOf("x"); if (x != -1) { foundMag = true; int mag = (int) Double.parseDouble(token.substring(0, x)); String na = token.substring(x + 1); store.setObjectiveNominalMagnification( new PositiveInteger(mag), numDatasets, 0); store.setObjectiveLensNA(new Double(na), numDatasets, 0); } else { model.append(token); model.append(" "); } } String immersion = "Other"; if (tokens.hasMoreTokens()) { immersion = tokens.nextToken(); if (immersion == null || immersion.trim().equals("")) { immersion = "Other"; } } try { ImmersionEnumHandler handler = new ImmersionEnumHandler(); store.setObjectiveImmersion( (Immersion) handler.getEnumeration(immersion), numDatasets, 0); } catch (EnumerationException e) { } String correction = "Other"; if (tokens.hasMoreTokens()) { correction = tokens.nextToken(); if (correction == null || correction.trim().equals("")) { correction = "Other"; } } try { CorrectionEnumHandler handler = new CorrectionEnumHandler(); store.setObjectiveCorrection( (Correction) handler.getEnumeration(correction), numDatasets, 0); } catch (EnumerationException e) { } store.setObjectiveModel(model.toString().trim(), numDatasets, 0); } else if (attribute.equals("RefractionIndex")) { String id = MetadataTools.createLSID("Objective", numDatasets, 0); store.setObjectiveID(id, numDatasets, 0); store.setImageObjectiveSettingsID(id, numDatasets); store.setImageObjectiveSettingsRefractiveIndex(new Double(variant), numDatasets); } else if (attribute.equals("XPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posX = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionX(posX, numDatasets, image); } if (numChannels == 0) xPos.add(posX); } else if (attribute.equals("YPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posY = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionY(posY, numDatasets, image); } if (numChannels == 0) yPos.add(posY); } else if (attribute.equals("ZPos")) { int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC; int nPlanes = coreMeta.imageCount; Double posZ = new Double(variant); for (int image=0; image<nPlanes; image++) { store.setPlanePositionZ(posZ, numDatasets, image); } if (numChannels == 0) zPos.add(posZ); } else if (objectClass.equals("CSpectrophotometerUnit")) { Integer v = null; try { v = new Integer((int) Double.parseDouble(variant)); } catch (NumberFormatException e) { } if (attributes.getValue("Description").endsWith("(left)")) { String id = MetadataTools.createLSID("Filter", numDatasets, nextFilter); store.setFilterID(id, numDatasets, nextFilter); store.setFilterModel(object, numDatasets, nextFilter); if (v != null) { store.setTransmittanceRangeCutIn( new PositiveInteger(v), numDatasets, nextFilter); } } else if (attributes.getValue("Description").endsWith("(right)")) { if (v != null) { store.setTransmittanceRangeCutOut( new PositiveInteger(v), numDatasets, nextFilter); nextFilter++; } } } } else if (qName.equals("Detector") && level != MetadataLevel.MINIMUM) { String v = attributes.getValue("Gain"); Double gain = v == null ? null : new Double(v); v = attributes.getValue("Offset"); Double offset = v == null ? null : new Double(v); boolean active = "1".equals(attributes.getValue("IsActive")); if (active) { // find the corresponding MultiBand and Detector MultiBand m = null; Detector detector = null; Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1); String c = attributes.getValue("Channel"); int channel = c == null ? 0 : Integer.parseInt(c); for (MultiBand mb : multiBands) { if (mb.channel == channel) { m = mb; break; } } for (Detector d : detectors) { if (d.channel == channel) { detector = d; break; } } String id = MetadataTools.createLSID("Detector", numDatasets, nextChannel); if (m != null) { String channelID = MetadataTools.createLSID( "Channel", numDatasets, nextChannel); store.setChannelID(channelID, numDatasets, nextChannel); store.setChannelName(m.dyeName, numDatasets, nextChannel); String filter = MetadataTools.createLSID("Filter", numDatasets, nextFilter); store.setFilterID(filter, numDatasets, nextFilter); store.setTransmittanceRangeCutIn( new PositiveInteger(m.cutIn), numDatasets, nextFilter); store.setTransmittanceRangeCutOut( new PositiveInteger(m.cutOut), numDatasets, nextFilter); store.setLightPathEmissionFilterRef( filter, numDatasets, nextChannel, 0); nextFilter++; store.setDetectorID(id, numDatasets, nextChannel); store.setDetectorType(DetectorType.PMT, numDatasets, nextChannel); store.setDetectorSettingsGain(gain, numDatasets, nextChannel); store.setDetectorSettingsOffset(offset, numDatasets, nextChannel); store.setDetectorSettingsID(id, numDatasets, nextChannel); } store.setDetectorID(id, numDatasets, nextChannel); if (detector != null) { store.setDetectorSettingsGain(gain, numDatasets, nextChannel); store.setDetectorSettingsOffset(offset, numDatasets, nextChannel); store.setDetectorSettingsID(id, numDatasets, nextChannel); try { DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler(); store.setDetectorType( (DetectorType) handler.getEnumeration(detector.type), numDatasets, nextChannel); } catch (EnumerationException e) { } store.setDetectorModel(detector.model, numDatasets, nextChannel); store.setDetectorZoom(detector.zoom, numDatasets, nextChannel); store.setDetectorOffset(detector.offset, numDatasets, nextChannel); store.setDetectorVoltage(detector.voltage, numDatasets, nextChannel); } if (laser != null && laser.intensity < 100) { store.setChannelLightSourceSettingsID(laser.id, numDatasets, nextChannel); store.setChannelLightSourceSettingsAttenuation( new PercentFraction((float) laser.intensity / 100f), numDatasets, nextChannel); store.setChannelExcitationWavelength( new PositiveInteger(laser.wavelength), numDatasets, nextChannel); } nextChannel++; } } else if (qName.equals("LaserLineSetting") && level != MetadataLevel.MINIMUM) { Laser l = new Laser(); String lineIndex = attributes.getValue("LineIndex"); String qual = attributes.getValue("Qualifier"); l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex); int qualifier = qual == null ? 0 : Integer.parseInt(qual); l.index += (2 - (qualifier / 10)); if (l.index < 0) l.index = 0; l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index); l.wavelength = new Integer(attributes.getValue("LaserLine")); while (l.index > laserCount) { String lsid = MetadataTools.createLSID("LightSource", numDatasets, laserCount); store.setLaserID(lsid, numDatasets, laserCount); laserCount++; } store.setLaserID(l.id, numDatasets, l.index); laserCount++; if (l.wavelength > 0) { store.setLaserWavelength( new PositiveInteger(l.wavelength), numDatasets, l.index); } store.setLaserType(LaserType.OTHER, numDatasets, l.index); store.setLaserLaserMedium(LaserMedium.OTHER, numDatasets, l.index); String intensity = attributes.getValue("IntensityDev"); l.intensity = intensity == null ? 0d : Double.parseDouble(intensity); if (l.intensity > 0) { l.intensity = 100d - l.intensity; lasers.add(l); } } else if (qName.equals("TimeStamp") && numDatasets >= 0) { String stampHigh = attributes.getValue("HighInteger"); String stampLow = attributes.getValue("LowInteger"); long high = stampHigh == null ? 0 : Long.parseLong(stampHigh); long low = stampLow == null ? 0 : Long.parseLong(stampLow); long ms = DateTools.getMillisFromTicks(high, low); if (count == 0) { String date = DateTools.convertDate(ms, DateTools.COBOL); if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) < System.currentTimeMillis()) { store.setImageAcquiredDate(date, numDatasets); } firstStamp = ms; store.setPlaneDeltaT(0.0, numDatasets, count); } else if (level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { ms -= firstStamp; store.setPlaneDeltaT(ms / 1000.0, numDatasets, count); } } count++; } else if (qName.equals("RelTimeStamp") && level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { Double time = new Double(attributes.getValue("Time")); store.setPlaneDeltaT(time, numDatasets, count++); } } else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) { roi = new ROI(); String type = attributes.getValue("type"); if (type != null) roi.type = Integer.parseInt(type); String color = attributes.getValue("color"); if (color != null) roi.color = Integer.parseInt(color); roi.name = attributes.getValue("name"); roi.fontName = attributes.getValue("fontName"); roi.fontSize = attributes.getValue("fontSize"); roi.transX = parseDouble(attributes.getValue("transTransX")); roi.transY = parseDouble(attributes.getValue("transTransY")); roi.scaleX = parseDouble(attributes.getValue("transScalingX")); roi.scaleY = parseDouble(attributes.getValue("transScalingY")); roi.rotation = parseDouble(attributes.getValue("transRotation")); String linewidth = attributes.getValue("linewidth"); if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth); roi.text = attributes.getValue("text"); } else if (qName.equals("Vertex") && level != MetadataLevel.MINIMUM) { String x = attributes.getValue("x"); String y = attributes.getValue("y"); if (x != null) { x = x.replaceAll(",", "."); roi.x.add(new Double(x)); } if (y != null) { y = y.replaceAll(",", "."); roi.y.add(new Double(y)); } } else if (qName.equals("ROI")) { alternateCenter = true; } else if (qName.equals("MultiBand") && level != MetadataLevel.MINIMUM) { MultiBand m = new MultiBand(); m.dyeName = attributes.getValue("DyeName"); m.channel = Integer.parseInt(attributes.getValue("Channel")); m.cutIn = (int) Math.round(Double.parseDouble(attributes.getValue("LeftWorld"))); m.cutOut = (int) Math.round(Double.parseDouble(attributes.getValue("RightWorld"))); multiBands.add(m); } else if (qName.equals("ChannelInfo")) { int index = Integer.parseInt(attributes.getValue("Index")); channels.remove(numDatasets + "-" + index); } else count = 0; if (numDatasets == oldSeriesCount) storeSeriesHashtable(numDatasets, h); }
diff --git a/src/resources/xml/src/java/org/wyona/yanel/impl/resources/XMLResource.java b/src/resources/xml/src/java/org/wyona/yanel/impl/resources/XMLResource.java index 60fbab504..eb37f08be 100644 --- a/src/resources/xml/src/java/org/wyona/yanel/impl/resources/XMLResource.java +++ b/src/resources/xml/src/java/org/wyona/yanel/impl/resources/XMLResource.java @@ -1,440 +1,440 @@ /* * Copyright 2006 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.wyona.org/licenses/APACHE-LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wyona.yanel.impl.resources; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.Topic; import org.wyona.yanel.core.Yanel; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.VersionableV2; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.versionable.RevisionInformation; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.transformation.I18nTransformer; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yarep.core.Node; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import org.wyona.yarep.core.Revision; import org.wyona.yarep.util.RepoPath; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Date; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import org.apache.log4j.Category; /** * */ public class XMLResource extends Resource implements ViewableV2, ModifiableV2, VersionableV2 { private static Category log = Category.getInstance(XMLResource.class); /** * */ public XMLResource() { } /** * */ public ViewDescriptor[] getViewDescriptors() { return null; } public View getView(String viewId) throws Exception { return getView(viewId, null); } /** * Generates view */ public View getView(String viewId, String revisionName) throws Exception { View defaultView = new View(); String mimeType = getMimeType(getPath(), viewId); defaultView.setMimeType(mimeType); String yanelPath = getProperty("yanel-path"); //if (yanelPath == null) yanelPath = path.toString(); String xsltPath = getXSLTPath(getPath()); try { Repository repo = getRealm().getRepository(); if (xsltPath != null) { TransformerFactory tf = TransformerFactory.newInstance(); //tf.setURIResolver(null); Transformer transformer = tf.newTransformer(new StreamSource(repo.getNode(xsltPath).getInputStream())); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("yanel.path", getPath()); //TODO: There seems to be a bug re back2context ... transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); String userAgent = getRequest().getHeader("User-Agent"); String os = getOS(userAgent); if (os != null) transformer.setParameter("os", os); String client = getClient(userAgent); if (client != null) transformer.setParameter("client", client); transformer.setParameter("language", getLanguage()); // TODO: Is this the best way to generate an InputStream from an OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); org.xml.sax.XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); transformer.transform(new SAXSource(xmlReader, new org.xml.sax.InputSource(getContentXML(repo, yanelPath, revisionName))), new StreamResult(baos)); InputStream inputStream = new ByteArrayInputStream(baos.toByteArray()); + defaultView.setInputStream(inputStream); // TODO: Seems to have problems accessing remote DTDs when being offline /* - I18nTransformer i18nTransformer = new I18nTransformer("global", language); + I18nTransformer i18nTransformer = new I18nTransformer("global", getLanguage()); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(inputStream, i18nTransformer); defaultView.setInputStream(i18nTransformer.getInputStream()); */ - defaultView.setInputStream(inputStream); return defaultView; } else { log.debug("Mime-Type: " + mimeType); defaultView.setInputStream(getContentXML(repo, yanelPath, revisionName)); } } catch(Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")"); throw new Exception(e); } return defaultView; } /** * Get language with the following priorization: 1) yanel.meta.language query string parameter, 2) Accept-Language header, 3) Default en */ private String getLanguage() { String language = getRequest().getParameter("yanel.meta.language"); if (language == null) { language = getRequest().getParameter("Accept-Language"); } if(language != null && language.length() > 0) return language; return "en"; } /** * */ private InputStream getContentXML(Repository repo, String yanelPath, String revisionName) throws Exception { if (yanelPath != null) { log.debug("Yanel Path: " + yanelPath); Resource res = yanel.getResourceManager().getResource(getRequest(), getResponse(), getRealm(), yanelPath); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { // TODO: Pass the request ... String viewV1path = getRealm().getMountPoint() + yanelPath.substring(1); log.debug("including document: " + viewV1path); View view = ((ViewableV1) res).getView(new Path(viewV1path), null); if (view.getMimeType().indexOf("xml") >= 0) { // TODO: Shall the mime-type be transfered? return view.getInputStream(); } else { log.warn("No XML like mime-type: " + getPath()); } } else { log.warn("Resource is not ViewableV1: " + getPath()); } } Node node; if (revisionName != null) { node = repo.getNode(getPath()).getRevision(revisionName); } else { node = repo.getNode(getPath()); } return node.getInputStream(); } /** * Get mime type */ private String getMimeType(String path, String viewId) throws Exception { String mimeType = getProperty("mime-type"); if (mimeType != null) return mimeType; String suffix = PathUtil.getSuffix(path); if (suffix != null) { log.debug("SUFFIX: " + suffix); if (suffix.equals("html")) { //mimeType = "text/html"; mimeType = "application/xhtml+xml"; } else if (suffix.equals("xhtml")) { mimeType = "application/xhtml+xml"; } else if (suffix.equals("xml")) { mimeType = "application/xml"; } else { mimeType = "application/xml"; } } else { mimeType = "application/xml"; } return mimeType; } /** * */ public Reader getReader() throws Exception { return new InputStreamReader(getInputStream(), "UTF-8"); } /** * */ public InputStream getInputStream() throws Exception { return getRealm().getRepository().getNode(getPath()).getInputStream(); } /** * */ public Writer getWriter() throws Exception { log.error("Not implemented yet!"); return null; } /** * */ public OutputStream getOutputStream() throws Exception { return getRealm().getRepository().getNode(getPath()).getOutputStream(); } /** * */ public void write(InputStream in) throws Exception { log.warn("Not implemented yet!"); } /** * */ public long getLastModified() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); long lastModified; if (node.isResource()) { lastModified = node.getLastModified(); } else { lastModified = 0; } return lastModified; } /** * Get XSLT path */ private String getXSLTPath(String path) throws Exception { String xsltPath = getProperty("xslt"); if (xsltPath != null) return xsltPath; log.info("No XSLT Path within: " + path); return null; } /** * */ private String backToRoot(String path, String backToRoot) { String parent = PathUtil.getParent(path); if (parent != null && !isRoot(parent)) { return backToRoot(parent, backToRoot + "../"); } return backToRoot; } /** * */ private boolean isRoot(String path) { if (path.equals(File.separator)) return true; return false; } /** * */ public boolean delete() throws Exception { getRealm().getRepository().getNode(getPath()).remove(); return true; } /** * */ public RevisionInformation[] getRevisions() throws Exception { Revision[] revisions = getRealm().getRepository().getNode(getPath()).getRevisions(); RevisionInformation[] revisionInfos = new RevisionInformation[revisions.length]; for (int i=0; i<revisions.length; i++) { revisionInfos[i] = new RevisionInformation(revisions[i]); } return revisionInfos; } public void checkin(String comment) throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.checkin(comment); /* if (node.isCheckedOut()) { String checkoutUserID = node.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { node.checkin(); } else { throw new Exception("Resource is checked out by another user: " + checkoutUserID); } } else { throw new Exception("Resource is not checked out."); } */ } public void checkout(String userID) throws Exception { Node node = getRealm().getRepository().getNode(getPath()); node.checkout(userID); /* if (node.isCheckedOut()) { String checkoutUserID = node.getCheckoutUserID(); if (checkoutUserID.equals(userID)) { log.warn("Resource " + getPath() + " is already checked out by this user: " + checkoutUserID); } else { throw new Exception("Resource is already checked out by another user: " + checkoutUserID); } } else { node.checkout(userID); } */ } public void restore(String revisionName) throws Exception { getRealm().getRepository().getNode(getPath()).restore(revisionName); } public Date getCheckoutDate() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); // return node.getCheckoutDate(); return null; } public String getCheckoutUserID() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); return node.getCheckoutUserID(); } public boolean isCheckedOut() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); return node.isCheckedOut(); } public boolean exists() throws Exception { log.warn("Not implemented yet!"); return true; } /** * Get size of generated page */ public long getSize() throws Exception { Node node = getRealm().getRepository().getNode(getPath()); long size; if (node.isResource()) { size = node.getSize(); } else { size = 0; } return size; } /** * Get operating system */ public String getOS(String userAgent) { if (userAgent.indexOf("Linux") > 0) { return "unix"; } else if (userAgent.indexOf("Mac OS X") > 0) { return "unix"; } else if (userAgent.indexOf("Windows") > 0) { return "windows"; } else { log.warn("Operating System could not be recognized: " + userAgent); return null; } } /** * Get client */ public String getClient(String userAgent) { if (userAgent.indexOf("Firefox") > 0) { return "firefox"; } else if (userAgent.indexOf("MSIE") > 0) { return "msie"; } else { log.warn("Client could not be recognized: " + userAgent); return null; } } /** * Get property value from resource configuration */ private String getProperty(String name) throws Exception { ResourceConfiguration rc = getConfiguration(); if (rc != null) return rc.getProperty(name); return getRTI().getProperty(name); } }
false
true
public View getView(String viewId, String revisionName) throws Exception { View defaultView = new View(); String mimeType = getMimeType(getPath(), viewId); defaultView.setMimeType(mimeType); String yanelPath = getProperty("yanel-path"); //if (yanelPath == null) yanelPath = path.toString(); String xsltPath = getXSLTPath(getPath()); try { Repository repo = getRealm().getRepository(); if (xsltPath != null) { TransformerFactory tf = TransformerFactory.newInstance(); //tf.setURIResolver(null); Transformer transformer = tf.newTransformer(new StreamSource(repo.getNode(xsltPath).getInputStream())); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("yanel.path", getPath()); //TODO: There seems to be a bug re back2context ... transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); String userAgent = getRequest().getHeader("User-Agent"); String os = getOS(userAgent); if (os != null) transformer.setParameter("os", os); String client = getClient(userAgent); if (client != null) transformer.setParameter("client", client); transformer.setParameter("language", getLanguage()); // TODO: Is this the best way to generate an InputStream from an OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); org.xml.sax.XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); transformer.transform(new SAXSource(xmlReader, new org.xml.sax.InputSource(getContentXML(repo, yanelPath, revisionName))), new StreamResult(baos)); InputStream inputStream = new ByteArrayInputStream(baos.toByteArray()); // TODO: Seems to have problems accessing remote DTDs when being offline /* I18nTransformer i18nTransformer = new I18nTransformer("global", language); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(inputStream, i18nTransformer); defaultView.setInputStream(i18nTransformer.getInputStream()); */ defaultView.setInputStream(inputStream); return defaultView; } else { log.debug("Mime-Type: " + mimeType); defaultView.setInputStream(getContentXML(repo, yanelPath, revisionName)); } } catch(Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")"); throw new Exception(e); } return defaultView; }
public View getView(String viewId, String revisionName) throws Exception { View defaultView = new View(); String mimeType = getMimeType(getPath(), viewId); defaultView.setMimeType(mimeType); String yanelPath = getProperty("yanel-path"); //if (yanelPath == null) yanelPath = path.toString(); String xsltPath = getXSLTPath(getPath()); try { Repository repo = getRealm().getRepository(); if (xsltPath != null) { TransformerFactory tf = TransformerFactory.newInstance(); //tf.setURIResolver(null); Transformer transformer = tf.newTransformer(new StreamSource(repo.getNode(xsltPath).getInputStream())); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("yanel.path", getPath()); //TODO: There seems to be a bug re back2context ... transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); String userAgent = getRequest().getHeader("User-Agent"); String os = getOS(userAgent); if (os != null) transformer.setParameter("os", os); String client = getClient(userAgent); if (client != null) transformer.setParameter("client", client); transformer.setParameter("language", getLanguage()); // TODO: Is this the best way to generate an InputStream from an OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); org.xml.sax.XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); transformer.transform(new SAXSource(xmlReader, new org.xml.sax.InputSource(getContentXML(repo, yanelPath, revisionName))), new StreamResult(baos)); InputStream inputStream = new ByteArrayInputStream(baos.toByteArray()); defaultView.setInputStream(inputStream); // TODO: Seems to have problems accessing remote DTDs when being offline /* I18nTransformer i18nTransformer = new I18nTransformer("global", getLanguage()); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(inputStream, i18nTransformer); defaultView.setInputStream(i18nTransformer.getInputStream()); */ return defaultView; } else { log.debug("Mime-Type: " + mimeType); defaultView.setInputStream(getContentXML(repo, yanelPath, revisionName)); } } catch(Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")"); throw new Exception(e); } return defaultView; }
diff --git a/src/java/org/apache/hadoop/ipc/Client.java b/src/java/org/apache/hadoop/ipc/Client.java index 484cb4668..63ddfe55a 100644 --- a/src/java/org/apache/hadoop/ipc/Client.java +++ b/src/java/org/apache/hadoop/ipc/Client.java @@ -1,531 +1,535 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.ipc; import java.net.Socket; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.io.IOException; import java.io.EOFException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.OutputStream; import java.util.Hashtable; import java.util.Iterator; import org.apache.commons.logging.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.dfs.FSConstants; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; /** A client for an IPC service. IPC calls take a single {@link Writable} as a * parameter, and return a {@link Writable} as their value. A service runs on * a port and is defined by a parameter class and a value class. * * @author Doug Cutting * @see Server */ public class Client { /** Should the client send the header on the connection? */ private static final boolean SEND_HEADER = true; private static final byte CURRENT_VERSION = 0; public static final Log LOG = LogFactory.getLog("org.apache.hadoop.ipc.Client"); private Hashtable connections = new Hashtable(); private Class valueClass; // class of call values private int timeout ;// timeout for calls private int counter; // counter for call ids private boolean running = true; // true while client runs private Configuration conf; private int maxIdleTime; //connections will be culled if it was idle for //maxIdleTime msecs private int maxRetries; //the max. no. of retries for socket connections /** A call waiting for a value. */ private class Call { int id; // call id Writable param; // parameter Writable value; // value, null if error String error; // exception, null if value String errorClass; // class of exception long lastActivity; // time of last i/o boolean done; // true when call is done protected Call(Writable param) { this.param = param; synchronized (Client.this) { this.id = counter++; } touch(); } /** Called by the connection thread when the call is complete and the * value or error string are available. Notifies by default. */ public synchronized void callComplete() { notify(); // notify caller } /** Update lastActivity with the current time. */ public synchronized void touch() { lastActivity = System.currentTimeMillis(); } /** Update lastActivity with the current time. */ public synchronized void setResult(Writable value, String errorClass, String error) { this.value = value; this.error = error; this.errorClass =errorClass; this.done = true; } } /** Thread that reads responses and notifies callers. Each connection owns a * socket connected to a remote address. Calls are multiplexed through this * socket: responses may be delivered out of order. */ private class Connection extends Thread { private InetSocketAddress address; // address of server private Socket socket = null; // connected socket private DataInputStream in; private DataOutputStream out; private Hashtable calls = new Hashtable(); // currently active calls private Call readingCall; private Call writingCall; private int inUse = 0; private long lastActivity = 0; private boolean shouldCloseConnection = false; public Connection(InetSocketAddress address) throws IOException { if (address.isUnresolved()) { throw new UnknownHostException("unknown host: " + address.getHostName()); } this.address = address; this.setName("IPC Client connection to " + address.toString()); this.setDaemon(true); } public synchronized void setupIOstreams() throws IOException { if (socket != null) { notify(); return; } short failures = 0; while (true) { try { this.socket = new Socket(); this.socket.connect(address, FSConstants.READ_TIMEOUT); break; } catch (IOException ie) { //SocketTimeoutException is also caught if (failures == maxRetries) { //reset inUse so that the culler gets a chance to throw this //connection object out of the table. We don't want to increment //inUse to infinity (everytime getConnection is called inUse is //incremented)! inUse = 0; + // set socket to null so that the next call to setupIOstreams + // can start the process of connect all over again. + socket.close(); + socket = null; throw ie; } failures++; LOG.info("Retrying connect to server: " + address + ". Already tried " + failures + " time(s)."); try { Thread.sleep(1000); } catch (InterruptedException iex){ } } } socket.setSoTimeout(timeout); this.in = new DataInputStream (new BufferedInputStream (new FilterInputStream(socket.getInputStream()) { public int read(byte[] buf, int off, int len) throws IOException { int value = super.read(buf, off, len); if (readingCall != null) { readingCall.touch(); } return value; } })); this.out = new DataOutputStream (new BufferedOutputStream (new FilterOutputStream(socket.getOutputStream()) { public void write(byte[] buf, int o, int len) throws IOException { out.write(buf, o, len); if (writingCall != null) { writingCall.touch(); } } })); if (SEND_HEADER) { out.write(Server.HEADER.array()); out.write(CURRENT_VERSION); } notify(); } private synchronized boolean waitForWork() { //wait till someone signals us to start reading RPC response or //close the connection. If we are idle long enough (blocked in wait), //the ConnectionCuller thread will wake us up and ask us to close the //connection. //We need to wait when inUse is 0 or socket is null (it may be null if //the Connection object has been created but the socket connection //has not been setup yet). We stop waiting if we have been asked to close //connection while ((inUse == 0 || socket == null) && !shouldCloseConnection) { try { wait(); } catch (InterruptedException e) {} } return !shouldCloseConnection; } private synchronized void incrementRef() { inUse++; } private synchronized void decrementRef() { lastActivity = System.currentTimeMillis(); inUse--; } public synchronized boolean isIdle() { //check whether the connection is in use or just created if (inUse != 0) return false; long currTime = System.currentTimeMillis(); if (currTime - lastActivity > maxIdleTime) return true; return false; } public InetSocketAddress getRemoteAddress() { return address; } public void setCloseConnection() { shouldCloseConnection = true; } public void run() { if (LOG.isDebugEnabled()) LOG.debug(getName() + ": starting"); try { while (running) { int id; //wait here for work - read connection or close connection if (waitForWork() == false) break; try { id = in.readInt(); // try to read an id } catch (SocketTimeoutException e) { continue; } if (LOG.isDebugEnabled()) LOG.debug(getName() + " got value #" + id); Call call = (Call)calls.remove(new Integer(id)); boolean isError = in.readBoolean(); // read if error if (isError) { call.setResult(null, WritableUtils.readString(in), WritableUtils.readString(in)); } else { Writable value = (Writable)ReflectionUtils.newInstance(valueClass, conf); try { readingCall = call; value.readFields(in); // read value } finally { readingCall = null; } call.setResult(value, null, null); } call.callComplete(); // deliver result to caller //received the response. So decrement the ref count decrementRef(); } } catch (EOFException eof) { // This is what happens when the remote side goes down } catch (Exception e) { LOG.info(StringUtils.stringifyException(e)); } finally { //If there was no exception thrown in this method, then the only //way we reached here is by breaking out of the while loop (after //waitForWork). And if we took that route to reach here, we have //already removed the connection object in the ConnectionCuller thread. //We don't want to remove this again as some other thread might have //actually put a new Connection object in the table in the meantime. synchronized (connections) { if (connections.get(address) == this) { connections.remove(address); } } close(); } } /** Initiates a call by sending the parameter to the remote server. * Note: this is not called from the Connection thread, but by other * threads. */ public void sendParam(Call call) throws IOException { boolean error = true; try { calls.put(new Integer(call.id), call); synchronized (out) { if (LOG.isDebugEnabled()) LOG.debug(getName() + " sending #" + call.id); try { writingCall = call; DataOutputBuffer d = new DataOutputBuffer(); //for serializing the //data to be written d.writeInt(call.id); call.param.write(d); byte[] data = d.getData(); int dataLength = d.getLength(); out.writeInt(dataLength); //first put the data length out.write(data, 0, dataLength);//write the data out.flush(); } finally { writingCall = null; } } error = false; } finally { if (error) { synchronized (connections) { if (connections.get(address) == this) connections.remove(address); } close(); // close on error } } } /** Close the connection. */ public void close() { //socket may be null if the connection could not be established to the //server in question, and the culler asked us to close the connection if (socket == null) return; try { socket.close(); // close socket } catch (IOException e) {} if (LOG.isDebugEnabled()) LOG.debug(getName() + ": closing"); } } /** Call implementation used for parallel calls. */ private class ParallelCall extends Call { private ParallelResults results; private int index; public ParallelCall(Writable param, ParallelResults results, int index) { super(param); this.results = results; this.index = index; } /** Deliver result to result collector. */ public void callComplete() { results.callComplete(this); } } /** Result collector for parallel calls. */ private static class ParallelResults { private Writable[] values; private int size; private int count; public ParallelResults(int size) { this.values = new Writable[size]; this.size = size; } /** Collect a result. */ public synchronized void callComplete(ParallelCall call) { values[call.index] = call.value; // store the value count++; // count it if (count == size) // if all values are in notify(); // then notify waiting caller } } private class ConnectionCuller extends Thread { public static final int MIN_SLEEP_TIME = 1000; public void run() { LOG.debug(getName() + ": starting"); while (running) { try { Thread.sleep(MIN_SLEEP_TIME); } catch (InterruptedException ie) {} synchronized (connections) { Iterator i = connections.values().iterator(); while (i.hasNext()) { Connection c = (Connection)i.next(); if (c.isIdle()) { //We don't actually close the socket here (i.e., don't invoke //the close() method). We leave that work to the response receiver //thread. The reason for that is since we have taken a lock on the //connections table object, we don't want to slow down the entire //system if we happen to talk to a slow server. i.remove(); synchronized (c) { c.setCloseConnection(); c.notify(); } } } } } } } /** Construct an IPC client whose values are of the given {@link Writable} * class. */ public Client(Class valueClass, Configuration conf) { this.valueClass = valueClass; this.timeout = conf.getInt("ipc.client.timeout",10000); this.maxIdleTime = conf.getInt("ipc.client.connection.maxidletime",1000); this.maxRetries = conf.getInt("ipc.client.connect.max.retries", 10); this.conf = conf; Thread t = new ConnectionCuller(); t.setDaemon(true); t.setName(valueClass.getName() + " Connection Culler"); LOG.debug(valueClass.getName() + "Connection culler maxidletime= " + maxIdleTime + "ms"); t.start(); } /** Stop all threads related to this client. No further calls may be made * using this client. */ public void stop() { LOG.info("Stopping client"); running = false; } /** Sets the timeout used for network i/o. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code>, returning the value. Throws exceptions if there are * network problems or if the remote code threw an exception. */ public Writable call(Writable param, InetSocketAddress address) throws IOException { Connection connection = getConnection(address); Call call = new Call(param); synchronized (call) { connection.sendParam(call); // send the parameter long wait = timeout; do { try { call.wait(wait); // wait for the result } catch (InterruptedException e) {} wait = timeout - (System.currentTimeMillis() - call.lastActivity); } while (!call.done && wait > 0); if (call.error != null) { throw new RemoteException(call.errorClass, call.error); } else if (!call.done) { throw new SocketTimeoutException("timed out waiting for rpc response"); } else { return call.value; } } } /** Makes a set of calls in parallel. Each parameter is sent to the * corresponding address. When all values are available, or have timed out * or errored, the collected results are returned in an array. The array * contains nulls for calls that timed out or errored. */ public Writable[] call(Writable[] params, InetSocketAddress[] addresses) throws IOException { if (addresses.length == 0) return new Writable[0]; ParallelResults results = new ParallelResults(params.length); synchronized (results) { for (int i = 0; i < params.length; i++) { ParallelCall call = new ParallelCall(params[i], results, i); try { Connection connection = getConnection(addresses[i]); connection.sendParam(call); // send each parameter } catch (IOException e) { LOG.info("Calling "+addresses[i]+" caught: " + StringUtils.stringifyException(e)); // log errors results.size--; // wait for one fewer result } } try { results.wait(timeout); // wait for all results } catch (InterruptedException e) {} if (results.count == 0) { throw new IOException("no responses"); } else { return results.values; } } } /** Get a connection from the pool, or create a new one and add it to the * pool. Connections to a given host/port are reused. */ private Connection getConnection(InetSocketAddress address) throws IOException { Connection connection; synchronized (connections) { connection = (Connection)connections.get(address); if (connection == null) { connection = new Connection(address); connections.put(address, connection); connection.start(); } connection.incrementRef(); } //we don't invoke the method below inside "synchronized (connections)" //block above. The reason for that is if the server happens to be slow, //it will take longer to establish a connection and that will slow the //entire system down. connection.setupIOstreams(); return connection; } }
true
true
public synchronized void setupIOstreams() throws IOException { if (socket != null) { notify(); return; } short failures = 0; while (true) { try { this.socket = new Socket(); this.socket.connect(address, FSConstants.READ_TIMEOUT); break; } catch (IOException ie) { //SocketTimeoutException is also caught if (failures == maxRetries) { //reset inUse so that the culler gets a chance to throw this //connection object out of the table. We don't want to increment //inUse to infinity (everytime getConnection is called inUse is //incremented)! inUse = 0; throw ie; } failures++; LOG.info("Retrying connect to server: " + address + ". Already tried " + failures + " time(s)."); try { Thread.sleep(1000); } catch (InterruptedException iex){ } } } socket.setSoTimeout(timeout); this.in = new DataInputStream (new BufferedInputStream (new FilterInputStream(socket.getInputStream()) { public int read(byte[] buf, int off, int len) throws IOException { int value = super.read(buf, off, len); if (readingCall != null) { readingCall.touch(); } return value; } })); this.out = new DataOutputStream (new BufferedOutputStream (new FilterOutputStream(socket.getOutputStream()) { public void write(byte[] buf, int o, int len) throws IOException { out.write(buf, o, len); if (writingCall != null) { writingCall.touch(); } } })); if (SEND_HEADER) { out.write(Server.HEADER.array()); out.write(CURRENT_VERSION); } notify(); }
public synchronized void setupIOstreams() throws IOException { if (socket != null) { notify(); return; } short failures = 0; while (true) { try { this.socket = new Socket(); this.socket.connect(address, FSConstants.READ_TIMEOUT); break; } catch (IOException ie) { //SocketTimeoutException is also caught if (failures == maxRetries) { //reset inUse so that the culler gets a chance to throw this //connection object out of the table. We don't want to increment //inUse to infinity (everytime getConnection is called inUse is //incremented)! inUse = 0; // set socket to null so that the next call to setupIOstreams // can start the process of connect all over again. socket.close(); socket = null; throw ie; } failures++; LOG.info("Retrying connect to server: " + address + ". Already tried " + failures + " time(s)."); try { Thread.sleep(1000); } catch (InterruptedException iex){ } } } socket.setSoTimeout(timeout); this.in = new DataInputStream (new BufferedInputStream (new FilterInputStream(socket.getInputStream()) { public int read(byte[] buf, int off, int len) throws IOException { int value = super.read(buf, off, len); if (readingCall != null) { readingCall.touch(); } return value; } })); this.out = new DataOutputStream (new BufferedOutputStream (new FilterOutputStream(socket.getOutputStream()) { public void write(byte[] buf, int o, int len) throws IOException { out.write(buf, o, len); if (writingCall != null) { writingCall.touch(); } } })); if (SEND_HEADER) { out.write(Server.HEADER.array()); out.write(CURRENT_VERSION); } notify(); }
diff --git a/src/main/java/net/croxis/plugins/civilmineation/CivAPI.java b/src/main/java/net/croxis/plugins/civilmineation/CivAPI.java index ede00f2..01a2a87 100644 --- a/src/main/java/net/croxis/plugins/civilmineation/CivAPI.java +++ b/src/main/java/net/croxis/plugins/civilmineation/CivAPI.java @@ -1,612 +1,612 @@ package net.croxis.plugins.civilmineation; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import net.croxis.plugins.civilmineation.components.CityComponent; import net.croxis.plugins.civilmineation.components.CivilizationComponent; import net.croxis.plugins.civilmineation.components.Ent; import net.croxis.plugins.civilmineation.components.PermissionComponent; import net.croxis.plugins.civilmineation.components.PlotComponent; import net.croxis.plugins.civilmineation.components.ResidentComponent; import net.croxis.plugins.civilmineation.components.SignComponent; import net.croxis.plugins.civilmineation.events.DeleteCityEvent; import net.croxis.plugins.civilmineation.events.DeleteCivEvent; import net.croxis.plugins.civilmineation.events.NewCityEvent; import net.croxis.plugins.civilmineation.events.NewCivEvent; import net.croxis.plugins.research.Tech; import net.croxis.plugins.research.TechManager; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.entity.Player; public class CivAPI { public static Civilmineation plugin; public static Economy econ = null; public CivAPI(Civilmineation p){ plugin = p; new PlotCache(p); } public static ResidentComponent getResident(String name){ return plugin.getDatabase().find(ResidentComponent.class).where().ieq("name", name).findUnique(); } public static ResidentComponent getResident(Player player){ return plugin.getDatabase().find(ResidentComponent.class).where().ieq("name", player.getName()).findUnique(); } public static HashSet<ResidentComponent> getResidents(CivilizationComponent civ){ Set<CityComponent> cities = plugin.getDatabase().find(CityComponent.class).where().eq("civilization", civ).findSet(); HashSet<ResidentComponent> residents = new HashSet<ResidentComponent>(); for (CityComponent city : cities){ residents.addAll(getResidents(city)); } return residents; } public static Set<ResidentComponent> getResidents(CityComponent city){ return plugin.getDatabase().find(ResidentComponent.class).where().eq("city", city).findSet(); } public static PlotComponent getPlot(Chunk chunk){ return getPlot(chunk.getWorld().getName(), chunk.getX(), chunk.getZ()); } public static PlotComponent getPlot(String world, int x, int z){ //return plugin.getDatabase().find(PlotComponent.class).where().eq("x", x).eq("z", z).findUnique(); return PlotCache.getPlot(world, x, z); } public static PlotComponent getPlot(Sign sign){ //This is a rare enough case where I don't think we need the cache to cover this. return plugin.getDatabase().find(PlotComponent.class).where() .ieq("world", sign.getWorld().getName()) .eq("signX", sign.getX()) .eq("signY", sign.getY()) .eq("signZ", sign.getZ()).findUnique(); } public static Sign getPlotSign(PlotComponent plot){ SignComponent signComp = getSign(SignType.PLOT_INFO, plot.getEntityID()); Block block = plugin.getServer().getWorld(plot.getWorld()).getBlockAt(signComp.getX(), signComp.getY(), signComp.getZ()); if(block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN || block.getType() == Material.SIGN_POST) return (Sign) block.getState(); return null; } public static PermissionComponent getPermissions(Ent ent){ return plugin.getDatabase().find(PermissionComponent.class).where().eq("entityID", ent).findUnique(); } public static CivilizationComponent getCiv(String name){ return plugin.getDatabase().find(CivilizationComponent.class).where().ieq("name", name).findUnique(); } public static CityComponent getCity(Location charterLocation){ return plugin.getDatabase().find(CityComponent.class).where().eq("charter_x", charterLocation.getX()) .eq("charter_y", charterLocation.getY()) .eq("charter_z", charterLocation.getZ()).findUnique(); } public static Set<CityComponent> getCities(){ return plugin.getDatabase().find(CityComponent.class).findSet(); } public static Set<ResidentComponent> getAssistants(CityComponent city){ return plugin.getDatabase().find(ResidentComponent.class).where().eq("city", city).eq("cityAssistant", true).findSet(); } public static Set<PlotComponent> getPlots(CityComponent city){ return plugin.getDatabase().find(PlotComponent.class).where().eq("city", city).findSet(); } public static ResidentComponent getMayor(ResidentComponent resident){ if (resident.getCity() == null) return null; return getMayor(resident.getCity()); } public static ResidentComponent getMayor(CityComponent city){ return plugin.getDatabase().find(ResidentComponent.class).where().eq("city", city).eq("mayor", true).findUnique(); } public static ResidentComponent getKing(ResidentComponent resident){ CityComponent capital = plugin.getDatabase().find(CityComponent.class).where().eq("civilization", resident.getCity().getCivilization()).eq("capital", true).findUnique(); return plugin.getDatabase().find(ResidentComponent.class).where().eq("city", capital).eq("mayor", true).findUnique(); } public static ResidentComponent getKing(CityComponent city){ CityComponent capital = plugin.getDatabase().find(CityComponent.class).where().eq("civilization", city.getCivilization()).eq("capital", true).findUnique(); return plugin.getDatabase().find(ResidentComponent.class).where().eq("city", capital).eq("mayor", true).findUnique(); } public static boolean isKing(ResidentComponent resident){ return resident.isMayor() && resident.getCity().isCapital(); } public static boolean isNationalAdmin(ResidentComponent resident){ if (resident.isCivAssistant()) return true; return isKing(resident); } public static boolean isCityAdmin(ResidentComponent resident){ if (resident.isCityAssistant()) return true; else if (resident.getCity() == null) return false; return resident.isMayor(); } public static boolean isClaimed(PlotComponent plot){ if (plot.getCity() == null){ return false; } return true; } public static void addCulture(CityComponent city, int culture){ city.setCulture(city.getCulture() + culture); plugin.getDatabase().save(city); updateCityCharter(city); } public static void addResearch(CityComponent city, int points) { CityComponent capital = plugin.getDatabase().find(CityComponent.class).where().eq("civilization", city.getCivilization()) .eq("capital", true).findUnique(); ResidentComponent king = plugin.getDatabase().find(ResidentComponent.class).where().eq("city", capital).eq("mayor", true).findUnique(); Tech learned = TechManager.addPoints(king.getName(), points); if(learned != null){ List<CityComponent> cities = plugin.getDatabase().find(CityComponent.class).where().eq("civilization", capital.getCivilization()).findList(); for (CityComponent c : cities){ List<ResidentComponent> residents = plugin.getDatabase().find(ResidentComponent.class).where().eq("city", c).findList(); for (ResidentComponent r : residents){ TechManager.addTech(r.getName(), learned); } broadcastToCity("You have learned " + ChatColor.BLUE + learned.name + "!", c); } } } public static void updateCityCharter(CityComponent city){ if (city == null){ Civilmineation.log("Error. No city at that charter"); return; } SignComponent signComp = getSign(SignType.CITY_CHARTER, city.getEntityID()); Block charter = plugin.getServer().getWorld(signComp.getWorld()).getBlockAt(signComp.getX(), signComp.getY(), signComp.getZ()); Sign charterBlock = (Sign) charter.getState(); charterBlock.setLine(0, ChatColor.DARK_AQUA + "City Charter"); charterBlock.setLine(1, city.getCivilization().getName()); charterBlock.setLine(2, city.getName()); charterBlock.setLine(3, "Mayor " + getMayor(city).getName()); charterBlock.update(); Sign block = (Sign) charter.getRelative(BlockFace.DOWN).getState(); block.setLine(0, "=Demographics="); block.setLine(1, "Population: " + Integer.toString(CivAPI.getResidents(city).size())); block.setLine(2, "=Immigration="); if (block.getLine(3).contains("Open")) block.setLine(3, ChatColor.GREEN + "Open"); else block.setLine(3, ChatColor.RED + "Closed"); block.update(); signComp = getSign(SignType.DEMOGRAPHICS, city.getEntityID()); if (signComp == null) - createSign(block.getBlock(), city.getName() + " demographics", SignType.DEMOGRAPHICS, city.getEntityID()); + signComp = createSign(block.getBlock(), city.getName() + " demographics", SignType.DEMOGRAPHICS, city.getEntityID()); if (signComp.getRotation() == 4 || signComp.getRotation() == 5){ charter.getRelative(BlockFace.EAST).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.EAST).getState(); if (TechManager.hasTech(getMayor(city).getName(), "Currency")) block.setLine(0, ChatColor.YELLOW + "Money: " + Double.toString(econ.getBalance(city.getName()))); else block.setLine(0, ChatColor.YELLOW + "Need Currency"); Tech tech = TechManager.getCurrentResearch(getKing(city).getName()); if (tech == null){ block.setLine(1, "Research:"); block.setLine(2, "None"); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + " / 0"); } else { block.setLine(1, "Research:"); block.setLine(2, ChatColor.BLUE + tech.name); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + "/" + Integer.toString(TechManager.getCurrentResearch(getKing(city).getName()).cost)); } block.update(); signComp = getSign(SignType.CITY_CHARTER_MONEY, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_MONEY, city.getEntityID()); charter.getRelative(BlockFace.WEST).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.WEST).getState(); block.setLine(1, "Plots: " + Integer.toString(getPlots(city).size())); block.setLine(2, "Culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(city.getCulture())); block.update(); signComp = getSign(SignType.CITY_CHARTER_CULTURE, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_CULTURE, city.getEntityID()); } else if (signComp.getRotation() == 2 || signComp.getRotation() == 3) { charter.getRelative(BlockFace.NORTH).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.NORTH).getState(); block.setLine(0, "Money: N/A"); Tech tech = TechManager.getCurrentResearch(getKing(city).getName()); if (tech == null){ block.setLine(1, "Research:"); block.setLine(2, "None"); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + " / 0"); } else { block.setLine(1, "Research:"); block.setLine(2, ChatColor.BLUE + tech.name); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + "/" + Integer.toString(TechManager.getCurrentResearch(getKing(city).getName()).cost)); } block.update(); signComp = getSign(SignType.CITY_CHARTER_MONEY, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_MONEY, city.getEntityID()); charter.getRelative(BlockFace.SOUTH).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.SOUTH).getState(); block.setLine(1, "Plots: N/A"); block.setLine(2, "Culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(city.getCulture())); block.update(); signComp = getSign(SignType.CITY_CHARTER_CULTURE, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_CULTURE, city.getEntityID()); } } public static void setPlotSign(Sign plotSign){ SignComponent signComp = getSign(SignType.PLOT_INFO, plotSign); if (signComp == null) signComp = createSign(plotSign.getBlock(), "unknown plot", SignType.PLOT_INFO, getPlot(plotSign).getEntityID()); signComp.setX(plotSign.getX()); signComp.setY(plotSign.getY()); signComp.setZ(plotSign.getZ()); plugin.getDatabase().save(signComp); } /*public static void updatePlotSign(String world, int x, int z) { updatePlotSign(plugin.getDatabase().find(PlotComponent.class).where().eq("x", x).eq("z", z).findUnique()); }*/ public static void updatePlotSign(PlotComponent plot) { Civilmineation.logDebug("Updating plot sign"); Sign sign = getPlotSign(plot); if(plot.getResident()!=null){ if(plugin.getServer().getPlayer(plot.getResident().getName()).isOnline()){ sign.setLine(0, ChatColor.GREEN + plot.getResident().getName()); sign.update(); Civilmineation.logDebug("a"); } else { sign.setLine(0, ChatColor.RED + plot.getResident().getName()); sign.update(); Civilmineation.logDebug("b"); } } else { sign.setLine(0, plot.getCity().getName()); sign.update(); Civilmineation.logDebug("c"); sign.update(); } Civilmineation.logDebug("New plot sign xyz: " + Integer.toString(sign.getX()) + ", " + Integer.toString(sign.getY()) + ", " + Integer.toString(sign.getZ())); sign.update(); } public static void updatePlotSign(Sign sign, PlotComponent plot) { SignComponent signComp = getSign(SignType.PLOT_INFO, plot.getEntityID()); signComp.setX(sign.getX()); signComp.setY(sign.getY()); signComp.setZ(sign.getZ()); plugin.getDatabase().save(signComp); //updatePlotSign(plot.getX(), plot.getZ()); updatePlotSign(plot); } public static boolean addResident(ResidentComponent resident, CityComponent city){ if (resident.getCity() != null) return false; resident.setCity(city); plugin.getDatabase().save(resident); HashSet<Tech> civtechs = TechManager.getResearched(getKing(resident).getName()); HashSet<Tech> restechs = TechManager.getResearched(resident.getName()); HashSet<Tech> difference = new HashSet<Tech>(restechs); difference.removeAll(civtechs); Player player = Bukkit.getServer().getPlayer(resident.getName()); restechs.addAll(civtechs); TechManager.setTech(player, restechs); HashSet<Tech> gaintech = new HashSet<Tech>(); HashSet<Tech> canResearch = TechManager.getAvailableTech(getKing(resident).getName()); for (Tech t : difference){ if(gaintech.size() > 2) break; if(canResearch.contains(t)) gaintech.add(t); } for (Tech t : gaintech){ for (ResidentComponent r : getResidents(resident.getCity().getCivilization())){ TechManager.addTech(r.getName(), t); } } updateCityCharter(city); return true; } public static CityComponent createCity(String name, Player player, ResidentComponent mayor, Block charter, CivilizationComponent civ, boolean capital) { Ent cityEntity = createEntity("City " + name); PermissionComponent cityPerm = new PermissionComponent(); cityPerm.setAll(false); cityPerm.setResidentBuild(true); cityPerm.setResidentDestroy(true); cityPerm.setResidentItemUse(true); cityPerm.setResidentSwitch(true); cityPerm.setName(name + " permissions"); //addComponent(cityEntity, cityPerm); cityPerm.setEntityID(cityEntity); plugin.getDatabase().save(cityPerm); CityComponent city = new CityComponent(); //addComponent(cityEntity, city); city.setEntityID(cityEntity); city.setName(name); city.setCivilization(civ); city.setCapital(capital); city.setTaxes(0); city.setRegistered(System.currentTimeMillis()); city.setTownBoard("Change me"); city.setCulture(10); city.setSpawn_x(player.getLocation().getX()); city.setSpawn_y(player.getLocation().getY()); city.setSpawn_z(player.getLocation().getZ()); plugin.getDatabase().save(city); mayor.setCity(city); mayor.setMayor(true); plugin.getDatabase().save(mayor); NewCityEvent nce = new NewCityEvent(city.getName(), city.getEntityID().getId()); Bukkit.getServer().getPluginManager().callEvent(nce); return city; } public static CivilizationComponent createCiv(String name){ Ent civEntity = createEntity("Civ " + name); CivilizationComponent civ = new CivilizationComponent(); civ.setName(name); //addComponent(civEntity, civ); civ.setEntityID(civEntity); civ.setRegistered(System.currentTimeMillis()); civ.setTaxes(0); plugin.getDatabase().save(civ); PermissionComponent civPerm = new PermissionComponent(); civPerm.setAll(false); civPerm.setResidentBuild(true); civPerm.setResidentDestroy(true); civPerm.setResidentItemUse(true); civPerm.setResidentSwitch(true); civPerm.setName(name + " permissions"); //addComponent(civEntity, civPerm); civPerm.setEntityID(civEntity); plugin.getDatabase().save(civPerm); NewCivEvent nce = new NewCivEvent(civ.getName(), civ.getEntityID().getId()); Bukkit.getServer().getPluginManager().callEvent(nce); return civ; } public static void claimPlot(String world, int x, int z, Block plotSign, CityComponent city){ claimPlot(world, x, z, city.getName(), plotSign, city); } public static void claimPlot(String world, int x, int z, String name, Block plotSign, CityComponent city){ PlotCache.dirtyPlot(world, x, z); PlotComponent plot = getPlot(world, x, z); if (plot.getCity() == null){ Ent plotEnt = createEntity(); plot.setEntityID(plotEnt); } plot.setCity(city); plot.setName(name); plot.setWorld(plotSign.getWorld().getName()); plot.setType(CityPlotType.RESIDENTIAL); save(plot); createSign(plotSign, city.getName() + " plot", SignType.PLOT_INFO, plot.getEntityID()); } public static void broadcastToCity(String message, CityComponent city){ Set<ResidentComponent> residents = CivAPI.getResidents(city); for (ResidentComponent resident : residents){ Player player = plugin.getServer().getPlayer(resident.getName()); if (player != null) player.sendMessage(message); } } public static void broadcastToCiv(String message, CivilizationComponent civ){ List<CityComponent> cities = plugin.getDatabase().find(CityComponent.class).where().eq("civilization", civ).findList(); for (CityComponent city : cities){ broadcastToCity(message, city); } } public static void loseTechs(ResidentComponent resident){ HashSet<Tech> techs = TechManager.getResearched(resident.getName()); System.out.println("Player leaving"); System.out.println("Known techs: " + Integer.toString(techs.size())); HashSet<Tech> fiveToLose = new HashSet<Tech>(); HashSet<Tech> available; try { available = TechManager.getAvailableTech(resident.getName()); for (Tech t : available){ for (Tech c : t.children){ if (fiveToLose.size() >= 5) break; fiveToLose.add(c); } } if (fiveToLose.size() < 5){ for (Tech t : fiveToLose){ for (Tech c : t.children){ if (fiveToLose.size() >= 5) break; fiveToLose.add(c); } } } techs.removeAll(fiveToLose); OfflinePlayer player = Bukkit.getServer().getOfflinePlayer(resident.getName()); TechManager.setTech((Player) player, techs); } catch (Exception e) { e.printStackTrace(); } } public static void disbandCity(CityComponent city) { broadcastToCity("City disbanding", city); String name = city.getName(); for (ResidentComponent resident : CivAPI.getResidents(city)){ resident.setCity(null); resident.setMayor(false); resident.setCityAssistant(false); resident.setCivAssistant(false); loseTechs(resident); plugin.getDatabase().save(resident); } for (PlotComponent plot : getPlots(city)){ plot.setCity(null); plot.setResident(null); save(plot); } Ent civEnt = city.getCivilization().getEntityID(); CivilizationComponent civ = city.getCivilization(); Ent cityEnt = city.getEntityID(); Bukkit.getServer().getPluginManager().callEvent(new DeleteCityEvent(city.getName(), city.getEntityID().getId())); plugin.getDatabase().delete(city); plugin.getDatabase().delete(plugin.getDatabase().find(PermissionComponent.class).where().eq("entityID", cityEnt).findUnique()); try{ plugin.getDatabase().delete(cityEnt); } catch (Exception e){ Civilmineation.log(Level.WARNING, "A plugin did not properly let go of city entity " + Integer.toString(cityEnt.getId())); Civilmineation.log(Level.WARNING, "Database maintenence will probably be needed"); e.printStackTrace(); } city = plugin.getDatabase().find(CityComponent.class).where().eq("civ", civ).findUnique(); if (city == null){ Bukkit.getServer().getPluginManager().callEvent(new DeleteCivEvent(civ.getName(), civ.getEntityID().getId())); plugin.getDatabase().delete(civ); plugin.getDatabase().delete(plugin.getDatabase().find(PermissionComponent.class).where().eq("entityID", civEnt).findUnique()); try{ plugin.getDatabase().delete(civEnt); } catch (Exception e){ Civilmineation.log(Level.WARNING, "A plugin did not properly let go of civ entity " + Integer.toString(civEnt.getId())); Civilmineation.log(Level.WARNING, "Database maintenence will probably be needed"); e.printStackTrace(); } } else { city.setCapital(true); plugin.getDatabase().save(city); broadcastToCiv(city.getName() + " is now the Capital City!", civ); } plugin.getServer().broadcastMessage(name + " has fallen to dust!"); } public static void removeResident(ResidentComponent resident){ if (getResidents(resident.getCity()).size() == 1){ disbandCity(resident.getCity()); return; } loseTechs(resident); CityComponent city = resident.getCity(); Set<PlotComponent> plots = plugin.getDatabase().find(PlotComponent.class).where().eq("city", city).eq("resident", resident).findSet(); for (PlotComponent plot : plots){ plot.setResident(null); save(plot); updatePlotSign(plot); } resident.setCity(null); plugin.getDatabase().save(resident); broadcastToCity(resident.getName() + " has left our city!", city); } public static SignComponent createSign(Block block, String name, SignType type, Ent entity){ SignComponent sign = new SignComponent(); sign.setEntityID(entity); sign.setName(name); sign.setRotation(block.getData()); sign.setType(type); sign.setWorld(block.getWorld().getName()); sign.setX(block.getX()); sign.setY(block.getY()); sign.setZ(block.getZ()); plugin.getDatabase().save(sign); return sign; } public static SignComponent getSign(SignType type, Ent entity){ return plugin.getDatabase().find(SignComponent.class).where().eq("entityID", entity).eq("type", type).findUnique(); } public static SignComponent getSign(SignType type, Block block){ return plugin.getDatabase().find(SignComponent.class).where() .eq("world", block.getWorld().getName()) .eq("x", block.getX()) .eq("y", block.getX()) .eq("z", block.getX()) .eq("type", type).findUnique(); } public static SignComponent getSign(SignType type, Sign block){ return plugin.getDatabase().find(SignComponent.class).where() .eq("world", block.getWorld().getName()) .eq("x", block.getX()) .eq("y", block.getX()) .eq("z", block.getX()) .eq("type", type).findUnique(); } public static Ent createEntity(){ Ent ent = new Ent(); plugin.getDatabase().save(ent); return ent; } public static Ent createEntity(String name){ Ent ent = new Ent(); ent.setDebugName(name); plugin.getDatabase().save(ent); return ent; } public static void save(PlotComponent plot){ PlotCache.dirtyPlot(plot); plugin.getDatabase().save(plot); } }
true
true
public static void updateCityCharter(CityComponent city){ if (city == null){ Civilmineation.log("Error. No city at that charter"); return; } SignComponent signComp = getSign(SignType.CITY_CHARTER, city.getEntityID()); Block charter = plugin.getServer().getWorld(signComp.getWorld()).getBlockAt(signComp.getX(), signComp.getY(), signComp.getZ()); Sign charterBlock = (Sign) charter.getState(); charterBlock.setLine(0, ChatColor.DARK_AQUA + "City Charter"); charterBlock.setLine(1, city.getCivilization().getName()); charterBlock.setLine(2, city.getName()); charterBlock.setLine(3, "Mayor " + getMayor(city).getName()); charterBlock.update(); Sign block = (Sign) charter.getRelative(BlockFace.DOWN).getState(); block.setLine(0, "=Demographics="); block.setLine(1, "Population: " + Integer.toString(CivAPI.getResidents(city).size())); block.setLine(2, "=Immigration="); if (block.getLine(3).contains("Open")) block.setLine(3, ChatColor.GREEN + "Open"); else block.setLine(3, ChatColor.RED + "Closed"); block.update(); signComp = getSign(SignType.DEMOGRAPHICS, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.DEMOGRAPHICS, city.getEntityID()); if (signComp.getRotation() == 4 || signComp.getRotation() == 5){ charter.getRelative(BlockFace.EAST).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.EAST).getState(); if (TechManager.hasTech(getMayor(city).getName(), "Currency")) block.setLine(0, ChatColor.YELLOW + "Money: " + Double.toString(econ.getBalance(city.getName()))); else block.setLine(0, ChatColor.YELLOW + "Need Currency"); Tech tech = TechManager.getCurrentResearch(getKing(city).getName()); if (tech == null){ block.setLine(1, "Research:"); block.setLine(2, "None"); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + " / 0"); } else { block.setLine(1, "Research:"); block.setLine(2, ChatColor.BLUE + tech.name); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + "/" + Integer.toString(TechManager.getCurrentResearch(getKing(city).getName()).cost)); } block.update(); signComp = getSign(SignType.CITY_CHARTER_MONEY, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_MONEY, city.getEntityID()); charter.getRelative(BlockFace.WEST).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.WEST).getState(); block.setLine(1, "Plots: " + Integer.toString(getPlots(city).size())); block.setLine(2, "Culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(city.getCulture())); block.update(); signComp = getSign(SignType.CITY_CHARTER_CULTURE, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_CULTURE, city.getEntityID()); } else if (signComp.getRotation() == 2 || signComp.getRotation() == 3) { charter.getRelative(BlockFace.NORTH).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.NORTH).getState(); block.setLine(0, "Money: N/A"); Tech tech = TechManager.getCurrentResearch(getKing(city).getName()); if (tech == null){ block.setLine(1, "Research:"); block.setLine(2, "None"); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + " / 0"); } else { block.setLine(1, "Research:"); block.setLine(2, ChatColor.BLUE + tech.name); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + "/" + Integer.toString(TechManager.getCurrentResearch(getKing(city).getName()).cost)); } block.update(); signComp = getSign(SignType.CITY_CHARTER_MONEY, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_MONEY, city.getEntityID()); charter.getRelative(BlockFace.SOUTH).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.SOUTH).getState(); block.setLine(1, "Plots: N/A"); block.setLine(2, "Culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(city.getCulture())); block.update(); signComp = getSign(SignType.CITY_CHARTER_CULTURE, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_CULTURE, city.getEntityID()); } }
public static void updateCityCharter(CityComponent city){ if (city == null){ Civilmineation.log("Error. No city at that charter"); return; } SignComponent signComp = getSign(SignType.CITY_CHARTER, city.getEntityID()); Block charter = plugin.getServer().getWorld(signComp.getWorld()).getBlockAt(signComp.getX(), signComp.getY(), signComp.getZ()); Sign charterBlock = (Sign) charter.getState(); charterBlock.setLine(0, ChatColor.DARK_AQUA + "City Charter"); charterBlock.setLine(1, city.getCivilization().getName()); charterBlock.setLine(2, city.getName()); charterBlock.setLine(3, "Mayor " + getMayor(city).getName()); charterBlock.update(); Sign block = (Sign) charter.getRelative(BlockFace.DOWN).getState(); block.setLine(0, "=Demographics="); block.setLine(1, "Population: " + Integer.toString(CivAPI.getResidents(city).size())); block.setLine(2, "=Immigration="); if (block.getLine(3).contains("Open")) block.setLine(3, ChatColor.GREEN + "Open"); else block.setLine(3, ChatColor.RED + "Closed"); block.update(); signComp = getSign(SignType.DEMOGRAPHICS, city.getEntityID()); if (signComp == null) signComp = createSign(block.getBlock(), city.getName() + " demographics", SignType.DEMOGRAPHICS, city.getEntityID()); if (signComp.getRotation() == 4 || signComp.getRotation() == 5){ charter.getRelative(BlockFace.EAST).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.EAST).getState(); if (TechManager.hasTech(getMayor(city).getName(), "Currency")) block.setLine(0, ChatColor.YELLOW + "Money: " + Double.toString(econ.getBalance(city.getName()))); else block.setLine(0, ChatColor.YELLOW + "Need Currency"); Tech tech = TechManager.getCurrentResearch(getKing(city).getName()); if (tech == null){ block.setLine(1, "Research:"); block.setLine(2, "None"); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + " / 0"); } else { block.setLine(1, "Research:"); block.setLine(2, ChatColor.BLUE + tech.name); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + "/" + Integer.toString(TechManager.getCurrentResearch(getKing(city).getName()).cost)); } block.update(); signComp = getSign(SignType.CITY_CHARTER_MONEY, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_MONEY, city.getEntityID()); charter.getRelative(BlockFace.WEST).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.WEST).getState(); block.setLine(1, "Plots: " + Integer.toString(getPlots(city).size())); block.setLine(2, "Culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(city.getCulture())); block.update(); signComp = getSign(SignType.CITY_CHARTER_CULTURE, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_CULTURE, city.getEntityID()); } else if (signComp.getRotation() == 2 || signComp.getRotation() == 3) { charter.getRelative(BlockFace.NORTH).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.NORTH).getState(); block.setLine(0, "Money: N/A"); Tech tech = TechManager.getCurrentResearch(getKing(city).getName()); if (tech == null){ block.setLine(1, "Research:"); block.setLine(2, "None"); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + " / 0"); } else { block.setLine(1, "Research:"); block.setLine(2, ChatColor.BLUE + tech.name); block.setLine(3, ChatColor.BLUE + Integer.toString(TechManager.getPoints(getKing(city).getName())) + "/" + Integer.toString(TechManager.getCurrentResearch(getKing(city).getName()).cost)); } block.update(); signComp = getSign(SignType.CITY_CHARTER_MONEY, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_MONEY, city.getEntityID()); charter.getRelative(BlockFace.SOUTH).setTypeIdAndData(68, signComp.getRotation(), true); block = (Sign) charter.getRelative(BlockFace.SOUTH).getState(); block.setLine(1, "Plots: N/A"); block.setLine(2, "Culture: " + ChatColor.LIGHT_PURPLE + Integer.toString(city.getCulture())); block.update(); signComp = getSign(SignType.CITY_CHARTER_CULTURE, city.getEntityID()); if (signComp == null) createSign(block.getBlock(), city.getName() + " demographics", SignType.CITY_CHARTER_CULTURE, city.getEntityID()); } }
diff --git a/src/com/android/gallery3d/app/OrientationManager.java b/src/com/android/gallery3d/app/OrientationManager.java index a8ef99ad..0e033ebe 100644 --- a/src/com/android/gallery3d/app/OrientationManager.java +++ b/src/com/android/gallery3d/app/OrientationManager.java @@ -1,215 +1,223 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.provider.Settings; import android.view.OrientationEventListener; import android.view.Surface; import com.android.gallery3d.ui.OrientationSource; import java.util.ArrayList; public class OrientationManager implements OrientationSource { private static final String TAG = "OrientationManager"; public interface Listener { public void onOrientationCompensationChanged(); } // Orientation hysteresis amount used in rounding, in degrees private static final int ORIENTATION_HYSTERESIS = 5; private Activity mActivity; private ArrayList<Listener> mListeners; private MyOrientationEventListener mOrientationListener; // The degrees of the device rotated clockwise from its natural orientation. private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; // If the framework orientation is locked. private boolean mOrientationLocked = false; // The orientation compensation: if the framwork orientation is locked, the // device orientation and the framework orientation may be different, so we // need to rotate the UI. For example, if this value is 90, the UI // components should be rotated 90 degrees counter-clockwise. private int mOrientationCompensation = 0; // This is true if "Settings -> Display -> Rotation Lock" is checked. We // don't allow the orientation to be unlocked if the value is true. private boolean mRotationLockedSetting = false; public OrientationManager(Activity activity) { mActivity = activity; mListeners = new ArrayList<Listener>(); mOrientationListener = new MyOrientationEventListener(activity); } public void resume() { ContentResolver resolver = mActivity.getContentResolver(); mRotationLockedSetting = Settings.System.getInt( resolver, Settings.System.ACCELEROMETER_ROTATION, 0) != 1; mOrientationListener.enable(); } public void pause() { mOrientationListener.disable(); } public void addListener(Listener listener) { synchronized (mListeners) { mListeners.add(listener); } } public void removeListener(Listener listener) { synchronized (mListeners) { mListeners.remove(listener); } } //////////////////////////////////////////////////////////////////////////// // Orientation handling // // We can choose to lock the framework orientation or not. If we lock the // framework orientation, we calculate a a compensation value according to // current device orientation and send it to listeners. If we don't lock // the framework orientation, we always set the compensation value to 0. //////////////////////////////////////////////////////////////////////////// // Lock the framework orientation to the current device orientation public void lockOrientation() { if (mOrientationLocked) return; mOrientationLocked = true; + int displayRotation = getDisplayRotation(); // Display rotation >= 180 means we need to use the REVERSE landscape/portrait - boolean standard = getDisplayRotation() < 180; + boolean standard = displayRotation < 180; if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(TAG, "lock orientation to landscape"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } else { + if (displayRotation == 90 || displayRotation == 270) { + // If displayRotation = 90 or 270 then we are on a landscape + // device. On landscape devices, portrait is a 90 degree + // clockwise rotation from landscape, so we need + // to flip which portrait we pick as display rotation is counter clockwise + standard = !standard; + } Log.d(TAG, "lock orientation to portrait"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } updateCompensation(); } // Unlock the framework orientation, so it can change when the device // rotates. public void unlockOrientation() { if (!mOrientationLocked) return; if (mRotationLockedSetting) return; mOrientationLocked = false; Log.d(TAG, "unlock orientation"); mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); disableCompensation(); } // Calculate the compensation value and send it to listeners. private void updateCompensation() { if (mOrientation == OrientationEventListener.ORIENTATION_UNKNOWN) { return; } int orientationCompensation = (mOrientation + getDisplayRotation(mActivity)) % 360; if (mOrientationCompensation != orientationCompensation) { mOrientationCompensation = orientationCompensation; notifyListeners(); } } // Make the compensation value 0 and send it to listeners. private void disableCompensation() { if (mOrientationCompensation != 0) { mOrientationCompensation = 0; notifyListeners(); } } private void notifyListeners() { synchronized (mListeners) { for (int i = 0, n = mListeners.size(); i < n; i++) { mListeners.get(i).onOrientationCompensationChanged(); } } } // This listens to the device orientation, so we can update the compensation. private class MyOrientationEventListener extends OrientationEventListener { public MyOrientationEventListener(Context context) { super(context); } @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user first orient // the camera then point the camera to floor or sky, we still have // the correct orientation. if (orientation == ORIENTATION_UNKNOWN) return; mOrientation = roundOrientation(orientation, mOrientation); // If the framework orientation is locked, we update the // compensation value and notify the listeners. if (mOrientationLocked) updateCompensation(); } } @Override public int getDisplayRotation() { return getDisplayRotation(mActivity); } @Override public int getCompensation() { return mOrientationCompensation; } private static int roundOrientation(int orientation, int orientationHistory) { boolean changeOrientation = false; if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) { changeOrientation = true; } else { int dist = Math.abs(orientation - orientationHistory); dist = Math.min(dist, 360 - dist); changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS); } if (changeOrientation) { return ((orientation + 45) / 90 * 90) % 360; } return orientationHistory; } private static int getDisplayRotation(Activity activity) { int rotation = activity.getWindowManager().getDefaultDisplay() .getRotation(); switch (rotation) { case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; } return 0; } }
false
true
public void lockOrientation() { if (mOrientationLocked) return; mOrientationLocked = true; // Display rotation >= 180 means we need to use the REVERSE landscape/portrait boolean standard = getDisplayRotation() < 180; if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(TAG, "lock orientation to landscape"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } else { Log.d(TAG, "lock orientation to portrait"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } updateCompensation(); }
public void lockOrientation() { if (mOrientationLocked) return; mOrientationLocked = true; int displayRotation = getDisplayRotation(); // Display rotation >= 180 means we need to use the REVERSE landscape/portrait boolean standard = displayRotation < 180; if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d(TAG, "lock orientation to landscape"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); } else { if (displayRotation == 90 || displayRotation == 270) { // If displayRotation = 90 or 270 then we are on a landscape // device. On landscape devices, portrait is a 90 degree // clockwise rotation from landscape, so we need // to flip which portrait we pick as display rotation is counter clockwise standard = !standard; } Log.d(TAG, "lock orientation to portrait"); mActivity.setRequestedOrientation(standard ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); } updateCompensation(); }
diff --git a/bpm/bonita-core/bonita-process-comment/bonita-process-comment-model-impl/src/main/java/org/bonitasoft/engine/core/process/comment/model/builder/impl/SCommentLogBuilderImpl.java b/bpm/bonita-core/bonita-process-comment/bonita-process-comment-model-impl/src/main/java/org/bonitasoft/engine/core/process/comment/model/builder/impl/SCommentLogBuilderImpl.java index 7e86686fbf..2929e38a55 100644 --- a/bpm/bonita-core/bonita-process-comment/bonita-process-comment-model-impl/src/main/java/org/bonitasoft/engine/core/process/comment/model/builder/impl/SCommentLogBuilderImpl.java +++ b/bpm/bonita-core/bonita-process-comment/bonita-process-comment-model-impl/src/main/java/org/bonitasoft/engine/core/process/comment/model/builder/impl/SCommentLogBuilderImpl.java @@ -1,58 +1,58 @@ /** * Copyright (C) 2011-2013 BonitaSoft S.A. * BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2.0 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.engine.core.process.comment.model.builder.impl; import org.bonitasoft.engine.core.process.comment.model.builder.SCommmentLogBuilder; import org.bonitasoft.engine.queriablelogger.model.SQueriableLog; import org.bonitasoft.engine.queriablelogger.model.builder.SPersistenceLogBuilder; import org.bonitasoft.engine.queriablelogger.model.builder.impl.CRUDELogBuilder; import org.bonitasoft.engine.queriablelogger.model.builder.impl.MissingMandatoryFieldsException; /** * @author Hongwen Zang * @author Matthieu Chaffotte */ public class SCommentLogBuilderImpl extends CRUDELogBuilder implements SCommmentLogBuilder { private static final String COMMENT = "COMMENT"; private static final int COMMENT_INDEX = 0; private static final String COMMENT_INDEX_NAME = "numericIndex1"; @Override public SPersistenceLogBuilder objectId(final long objectId) { queriableLogBuilder.numericIndex(COMMENT_INDEX, objectId); return this; } @Override public String getObjectIdKey() { return COMMENT_INDEX_NAME; } @Override protected String getActionTypePrefix() { return COMMENT; } @Override protected void checkExtraRules(final SQueriableLog log) { if (log.getActionStatus() != SQueriableLog.STATUS_FAIL && log.getNumericIndex(COMMENT_INDEX) == 0L) { - throw new MissingMandatoryFieldsException("Some mandatoryFildes are missing: " + "comment Id"); + throw new MissingMandatoryFieldsException("Some mandatory fields are missing: " + "comment Id"); } } }
true
true
protected void checkExtraRules(final SQueriableLog log) { if (log.getActionStatus() != SQueriableLog.STATUS_FAIL && log.getNumericIndex(COMMENT_INDEX) == 0L) { throw new MissingMandatoryFieldsException("Some mandatoryFildes are missing: " + "comment Id"); } }
protected void checkExtraRules(final SQueriableLog log) { if (log.getActionStatus() != SQueriableLog.STATUS_FAIL && log.getNumericIndex(COMMENT_INDEX) == 0L) { throw new MissingMandatoryFieldsException("Some mandatory fields are missing: " + "comment Id"); } }
diff --git a/AndBible/src/net/bible/service/format/osistohtml/NoteAndReferenceHandler.java b/AndBible/src/net/bible/service/format/osistohtml/NoteAndReferenceHandler.java index a989e33d..87c10af3 100644 --- a/AndBible/src/net/bible/service/format/osistohtml/NoteAndReferenceHandler.java +++ b/AndBible/src/net/bible/service/format/osistohtml/NoteAndReferenceHandler.java @@ -1,222 +1,222 @@ package net.bible.service.format.osistohtml; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.bible.service.common.Constants; import net.bible.service.common.Logger; import net.bible.service.format.Note; import net.bible.service.format.Note.NoteType; import org.apache.commons.lang.StringUtils; import org.crosswire.jsword.book.OSISUtil; import org.crosswire.jsword.passage.Key; import org.crosswire.jsword.passage.Passage; import org.crosswire.jsword.passage.PassageKeyFactory; import org.crosswire.jsword.passage.RestrictionType; import org.xml.sax.Attributes; /** * Convert OSIS tags into html tags * * Example OSIS tags from KJV Ps 119 v1 showing title, w, note <title canonical="true" subType="x-preverse" type="section"> <foreign n="?">ALEPH.</foreign> </title> <w lemma="strong:H0835">Blessed</w> <transChange type="added">are</transChange> <w lemma="strong:H08549">the undefiled</w> ... <w lemma="strong:H01980" morph="strongMorph:TH8802">who walk</w> ... <w lemma="strong:H03068">of the <seg><divineName>Lord</divineName></seg></w>. <note type="study">undefiled: or, perfect, or, sincere</note> Example of notes cross references from ESV In the <note n="a" osisID="Gen.1.1!crossReference.a" osisRef="Gen.1.1" type="crossReference"><reference osisRef="Job.38.4-Job.38.7">Job 38:4-7</reference>; <reference osisRef="Ps.33.6">Ps. 33:6</reference>; <reference osisRef="Ps.136.5">136:5</reference>; <reference osisRef="Isa.42.5">Isa. 42:5</reference>; <reference osisRef="Isa.45.18">45:18</reference>; <reference osisRef="John.1.1-John.1.3">John 1:1-3</reference>; <reference osisRef="Acts.14.15">Acts 14:15</reference>; <reference osisRef="Acts.17.24">17:24</reference>; <reference osisRef="Col.1.16-Col.1.17">Col. 1:16, 17</reference>; <reference osisRef="Heb.1.10">Heb. 1:10</reference>; <reference osisRef="Heb.11.3">11:3</reference>; <reference osisRef="Rev.4.11">Rev. 4:11</reference></note>beginning * * @author Martin Denham [mjdenham at gmail dot com] * @see gnu.lgpl.License for license details.<br> * The copyright to this program is held by it's author. */ public class NoteAndReferenceHandler { private OsisToHtmlParameters parameters; private int noteCount = 0; //todo temporarily use a string but later switch to Map<int,String> of verse->note private List<Note> notesList = new ArrayList<Note>(); private boolean isInNote = false; private String currentNoteRef; private String currentRefOsisRef; private HtmlTextWriter writer; private static final Logger log = new Logger("NoteAndReferenceHandler"); public NoteAndReferenceHandler(OsisToHtmlParameters osisToHtmlParameters, HtmlTextWriter theWriter) { this.parameters = osisToHtmlParameters; this.writer = theWriter; } public void startNote(Attributes attrs) { isInNote = true; currentNoteRef = getNoteRef(attrs); writeNoteRef(currentNoteRef); // prepare to fetch the actual note into the notes repo writer.writeToTempStore(); } public void startReference(Attributes attrs) { // don't need to do anything until closing reference tag except.. // delete separators like ';' that sometimes occur between reference tags writer.clearTempStore(); writer.writeToTempStore(); // store the osisRef attribute for use with the note this.currentRefOsisRef = attrs.getValue(OSISUtil.OSIS_ATTR_REF); } /* * Called when the Ending of the current Element is reached. For example in the * above explanation, this method is called when </Title> tag is reached */ public void endNote(int currentVerseNo) { String noteText = writer.getTempStoreString(); if (noteText.length()>0) { if (!StringUtils.containsOnly(noteText, "[];().,")) { Note note = new Note(currentVerseNo, currentNoteRef, noteText, NoteType.TYPE_GENERAL, null); notesList.add(note); } // and clear the buffer writer.clearTempStore(); } isInNote = false; writer.finishWritingToTempStore(); } public void endReference(int currentVerseNo) { writer.finishWritingToTempStore(); // a few modules like HunUj have refs in the text but not surrounded by a Note tag (like esv) so need to add Note here // special code to cope with HunUj problem if (parameters.isAutoWrapUnwrappedRefsInNote() && !isInNote ) { currentNoteRef = createNoteRef(); writeNoteRef(currentNoteRef); } if (isInNote || parameters.isAutoWrapUnwrappedRefsInNote()) { Note note = new Note(currentVerseNo, currentNoteRef, writer.getTempStoreString(), NoteType.TYPE_REFERENCE, currentRefOsisRef); notesList.add(note); } else { String refText = writer.getTempStoreString(); writer.write(getReferenceTag(currentRefOsisRef, refText)); } // and clear the buffer writer.clearTempStore(); currentRefOsisRef = null; } /** either use the 'n' attribute for the note ref or just get the next character in a list a-z * * @return a single char to use as a note ref */ private String getNoteRef(Attributes attrs) { // if the ref is specified as an attribute then use that String noteRef = attrs.getValue("n"); if (StringUtils.isEmpty(noteRef)) { noteRef = createNoteRef(); } return noteRef; } /** either use the character passed in or get the next character in a list a-z * * @return a single char to use as a note ref */ private String createNoteRef() { // else just get the next char int inta = (int)'a'; char nextNoteChar = (char)(inta+(noteCount++ % 26)); return String.valueOf(nextNoteChar); } /** write noteref html to outputstream */ private void writeNoteRef(String noteRef) { if (parameters.isShowNotes()) { writer.write("<span class='noteRef'>" + noteRef + "</span> "); } } /** create a link tag from an OSISref and the content of the tag */ private String getReferenceTag(String reference, String content) { log.debug("Ref:"+reference+" Content:"+content); StringBuilder result = new StringBuilder(); try { //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa if (reference==null && content!=null && content.length()>0 && StringUtils.isNumeric(content.subSequence(0,1)) && (content.length()<2 || !StringUtils.isAlphaSpace(content.subSequence(1,2)))) { // maybe should use VerseRangeFactory.fromstring(orig, basis) // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix int firstColonPos = content.indexOf(":"); boolean isVerseAndChapter = firstColonPos>0 && firstColonPos<4; if (isVerseAndChapter) { reference = parameters.getBasisRef().getBook().getOSIS()+" "+content; } else { reference = parameters.getBasisRef().getBook().getOSIS()+" "+parameters.getBasisRef().getChapter()+":"+content; } log.debug("Patched reference:"+reference); } else if (reference==null) { reference = content; } boolean isFullSwordUrn = reference.contains("/") && reference.contains(":"); if (isFullSwordUrn) { // e.g. sword://StrongsRealGreek/01909 // don't play with the reference - just assume it is correct result.append("<a href='").append(reference).append("'>"); result.append(content); result.append("</a>"); } else { Passage ref = (Passage) PassageKeyFactory.instance().getKey(reference); boolean isSingleVerse = ref.countVerses()==1; boolean isSimpleContent = content.length()<3 && content.length()>0; Iterator<Key> it = ref.rangeIterator(RestrictionType.CHAPTER); if (isSingleVerse && isSimpleContent) { // simple verse no e.g. 1 or 2 preceding the actual verse in TSK result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":").append(it.next().getOsisRef()).append("'>"); result.append(content); result.append("</a>"); } else { // multiple complex references boolean isFirst = true; while (it.hasNext()) { Key key = it.next(); if (!isFirst) { result.append(" "); } result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":").append(key.iterator().next().getOsisRef()).append("'>"); result.append(key); result.append("</a>"); isFirst = false; } } } } catch (Exception e) { - log.error("Error parsing OSIS reference:"+reference, e); + log.error("Error parsing OSIS reference:"+reference); // just return the content with no html markup result.append(content); } return result.toString(); } public List<Note> getNotesList() { return notesList; } }
true
true
private String getReferenceTag(String reference, String content) { log.debug("Ref:"+reference+" Content:"+content); StringBuilder result = new StringBuilder(); try { //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa if (reference==null && content!=null && content.length()>0 && StringUtils.isNumeric(content.subSequence(0,1)) && (content.length()<2 || !StringUtils.isAlphaSpace(content.subSequence(1,2)))) { // maybe should use VerseRangeFactory.fromstring(orig, basis) // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix int firstColonPos = content.indexOf(":"); boolean isVerseAndChapter = firstColonPos>0 && firstColonPos<4; if (isVerseAndChapter) { reference = parameters.getBasisRef().getBook().getOSIS()+" "+content; } else { reference = parameters.getBasisRef().getBook().getOSIS()+" "+parameters.getBasisRef().getChapter()+":"+content; } log.debug("Patched reference:"+reference); } else if (reference==null) { reference = content; } boolean isFullSwordUrn = reference.contains("/") && reference.contains(":"); if (isFullSwordUrn) { // e.g. sword://StrongsRealGreek/01909 // don't play with the reference - just assume it is correct result.append("<a href='").append(reference).append("'>"); result.append(content); result.append("</a>"); } else { Passage ref = (Passage) PassageKeyFactory.instance().getKey(reference); boolean isSingleVerse = ref.countVerses()==1; boolean isSimpleContent = content.length()<3 && content.length()>0; Iterator<Key> it = ref.rangeIterator(RestrictionType.CHAPTER); if (isSingleVerse && isSimpleContent) { // simple verse no e.g. 1 or 2 preceding the actual verse in TSK result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":").append(it.next().getOsisRef()).append("'>"); result.append(content); result.append("</a>"); } else { // multiple complex references boolean isFirst = true; while (it.hasNext()) { Key key = it.next(); if (!isFirst) { result.append(" "); } result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":").append(key.iterator().next().getOsisRef()).append("'>"); result.append(key); result.append("</a>"); isFirst = false; } } } } catch (Exception e) { log.error("Error parsing OSIS reference:"+reference, e); // just return the content with no html markup result.append(content); } return result.toString(); }
private String getReferenceTag(String reference, String content) { log.debug("Ref:"+reference+" Content:"+content); StringBuilder result = new StringBuilder(); try { //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa if (reference==null && content!=null && content.length()>0 && StringUtils.isNumeric(content.subSequence(0,1)) && (content.length()<2 || !StringUtils.isAlphaSpace(content.subSequence(1,2)))) { // maybe should use VerseRangeFactory.fromstring(orig, basis) // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix int firstColonPos = content.indexOf(":"); boolean isVerseAndChapter = firstColonPos>0 && firstColonPos<4; if (isVerseAndChapter) { reference = parameters.getBasisRef().getBook().getOSIS()+" "+content; } else { reference = parameters.getBasisRef().getBook().getOSIS()+" "+parameters.getBasisRef().getChapter()+":"+content; } log.debug("Patched reference:"+reference); } else if (reference==null) { reference = content; } boolean isFullSwordUrn = reference.contains("/") && reference.contains(":"); if (isFullSwordUrn) { // e.g. sword://StrongsRealGreek/01909 // don't play with the reference - just assume it is correct result.append("<a href='").append(reference).append("'>"); result.append(content); result.append("</a>"); } else { Passage ref = (Passage) PassageKeyFactory.instance().getKey(reference); boolean isSingleVerse = ref.countVerses()==1; boolean isSimpleContent = content.length()<3 && content.length()>0; Iterator<Key> it = ref.rangeIterator(RestrictionType.CHAPTER); if (isSingleVerse && isSimpleContent) { // simple verse no e.g. 1 or 2 preceding the actual verse in TSK result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":").append(it.next().getOsisRef()).append("'>"); result.append(content); result.append("</a>"); } else { // multiple complex references boolean isFirst = true; while (it.hasNext()) { Key key = it.next(); if (!isFirst) { result.append(" "); } result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":").append(key.iterator().next().getOsisRef()).append("'>"); result.append(key); result.append("</a>"); isFirst = false; } } } } catch (Exception e) { log.error("Error parsing OSIS reference:"+reference); // just return the content with no html markup result.append(content); } return result.toString(); }
diff --git a/forums/forums-ejb/src/main/java/com/stratelia/webactiv/forums/ForumsStatistics.java b/forums/forums-ejb/src/main/java/com/stratelia/webactiv/forums/ForumsStatistics.java index b8687e30b..211dde809 100644 --- a/forums/forums-ejb/src/main/java/com/stratelia/webactiv/forums/ForumsStatistics.java +++ b/forums/forums-ejb/src/main/java/com/stratelia/webactiv/forums/ForumsStatistics.java @@ -1,108 +1,108 @@ /** * Copyright (C) 2000 - 2009 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ package com.stratelia.webactiv.forums; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import com.stratelia.silverpeas.silverstatistics.control.ComponentStatisticsInterface; import com.stratelia.silverpeas.silverstatistics.control.UserIdCountVolumeCouple; import com.stratelia.webactiv.forums.forumEntity.ejb.ForumPK; import com.stratelia.webactiv.forums.forumsManager.ejb.ForumsBM; import com.stratelia.webactiv.forums.forumsManager.ejb.ForumsBMHome; import com.stratelia.webactiv.forums.models.Forum; import com.stratelia.webactiv.util.EJBUtilitaire; import com.stratelia.webactiv.util.JNDINames; /* * CVS Informations * * $Id: ForumsStatistics.java,v 1.3 2009/03/31 08:10:57 neysseri Exp $ * * $Log: ForumsStatistics.java,v $ * Revision 1.3 2009/03/31 08:10:57 neysseri * eShop : Livraison 2 * * Revision 1.2 2004/06/22 16:26:10 neysseri * implements new SilverContentInterface + nettoyage eclipse * * Revision 1.1.1.1 2002/08/06 14:47:57 nchaix * no message * * Revision 1.1 2002/04/17 17:20:34 mguillem * alimentation des stats de volume * * Revision 1.1 2002/04/05 16:58:24 mguillem * alimentation des stats de volume * */ /** * Class declaration * @author */ public class ForumsStatistics implements ComponentStatisticsInterface { private ForumsBM forumsBM = null; public Collection getVolume(String spaceId, String componentId) throws Exception { ArrayList couples = new ArrayList(); ArrayList forums = getForums(spaceId, componentId); Forum forum; for (int i = 0, n = forums.size(); i < n; i++) { forum = (Forum) forums.get(i); UserIdCountVolumeCouple couple = new UserIdCountVolumeCouple(); - couple.setUserId(forum.getCategory()); + couple.setUserId(Integer.toString(forum.getId())); couple.setCountVolume(1); couples.add(couple); } return couples; } private ForumsBM getForumsBM() { if (forumsBM == null) { try { ForumsBMHome forumsBMHome = (ForumsBMHome) EJBUtilitaire .getEJBObjectRef(JNDINames.FORUMSBM_EJBHOME, ForumsBMHome.class); forumsBM = forumsBMHome.create(); } catch (Exception e) { throw new EJBException(e); } } return forumsBM; } public ArrayList getForums(String spaceId, String componentId) throws RemoteException { return getForumsBM().getForums(new ForumPK(componentId, spaceId)); } }
true
true
public Collection getVolume(String spaceId, String componentId) throws Exception { ArrayList couples = new ArrayList(); ArrayList forums = getForums(spaceId, componentId); Forum forum; for (int i = 0, n = forums.size(); i < n; i++) { forum = (Forum) forums.get(i); UserIdCountVolumeCouple couple = new UserIdCountVolumeCouple(); couple.setUserId(forum.getCategory()); couple.setCountVolume(1); couples.add(couple); } return couples; }
public Collection getVolume(String spaceId, String componentId) throws Exception { ArrayList couples = new ArrayList(); ArrayList forums = getForums(spaceId, componentId); Forum forum; for (int i = 0, n = forums.size(); i < n; i++) { forum = (Forum) forums.get(i); UserIdCountVolumeCouple couple = new UserIdCountVolumeCouple(); couple.setUserId(Integer.toString(forum.getId())); couple.setCountVolume(1); couples.add(couple); } return couples; }
diff --git a/server/src/main/java/org/uiautomation/ios/server/application/APPIOSApplication.java b/server/src/main/java/org/uiautomation/ios/server/application/APPIOSApplication.java index d2ee9730..54b0826b 100644 --- a/server/src/main/java/org/uiautomation/ios/server/application/APPIOSApplication.java +++ b/server/src/main/java/org/uiautomation/ios/server/application/APPIOSApplication.java @@ -1,515 +1,515 @@ /* * Copyright 2012 ios-driver committers. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.uiautomation.ios.server.application; import com.dd.plist.ASCIIPropertyListParser; import com.dd.plist.BinaryPropertyListParser; import com.dd.plist.BinaryPropertyListWriter; import com.dd.plist.NSArray; import com.dd.plist.NSDictionary; import com.dd.plist.NSNumber; import com.dd.plist.NSObject; import com.dd.plist.PropertyListParser; import com.dd.plist.XMLPropertyListParser; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.openqa.selenium.SessionNotCreatedException; import org.openqa.selenium.WebDriverException; import org.uiautomation.ios.IOSCapabilities; import org.uiautomation.ios.communication.device.DeviceType; import org.uiautomation.ios.server.utils.ZipUtils; import org.uiautomation.ios.utils.PlistFileUtils; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import static org.uiautomation.ios.IOSCapabilities.*; // TODO freynaud create IOSApp vs Running App that has locale + language public class APPIOSApplication { private static final Logger log = Logger.getLogger(APPIOSApplication.class.getName()); private final JSONObject metadata; private final File app; private final List<LanguageDictionary> dictionaries = new ArrayList<LanguageDictionary>(); /** * @param pathToApp * @throws WebDriverException */ public APPIOSApplication(String pathToApp) { this.app = new File(pathToApp); if (!app.exists()) { throw new WebDriverException(pathToApp + "isn't an IOS app."); } loadAllContent(); try { metadata = getFullPlist(); } catch (Exception e) { throw new WebDriverException( "cannot load the metadata from the Info.plist file for " + pathToApp); } } public String toString() { return ".APP:" + getApplicationPath().getAbsolutePath(); } /** * the content of the Info.plist for the app, as a json object. */ public JSONObject getMetadata() { return metadata; } public List<String> getSupportedLanguagesCodes() { List<AppleLanguage> list = getSupportedLanguages(); List<String> res = new ArrayList<String>(); for (AppleLanguage lang : list) { res.add(lang.getIsoCode()); } return res; } /** * get the list of languages the application if localized to. */ List<AppleLanguage> getSupportedLanguages() { if (dictionaries.isEmpty()) { loadAllContent(); } /* * Set<Localizable> res = new HashSet<Localizable>(); List<File> l10ns = * LanguageDictionary.getL10NFiles(app); for (File f : l10ns) { String name * = LanguageDictionary.extractLanguageName(f); res.add(new * LanguageDictionary(name).getLanguage()); } return new * ArrayList<Localizable>(res); */ List<AppleLanguage> res = new ArrayList<AppleLanguage>(); for (LanguageDictionary dict : dictionaries) { res.add(dict.getLanguage()); } return res; } public AppleLanguage getLanguage(String languageCode) { if (getSupportedLanguages().isEmpty()) { return AppleLanguage.emptyLocale(languageCode); } if (languageCode == null) { // default to english if none specified languageCode = "en"; } for (AppleLanguage loc : getSupportedLanguages()) { if (languageCode.equals(loc.getIsoCode())) { return loc; } } throw new WebDriverException("Cannot find AppleLocale for " + languageCode); } public LanguageDictionary getDictionary(String languageCode) throws WebDriverException { return getDictionary(AppleLanguage.valueOf(languageCode)); } public LanguageDictionary getDictionary(AppleLanguage language) throws WebDriverException { if (!language.exists()) { throw new WebDriverException("The application doesn't have any content files.The l10n " + "features cannot be used."); } for (LanguageDictionary dict : dictionaries) { if (dict.getLanguage() == language) { return dict; } } throw new WebDriverException("Cannot find dictionary for " + language); } /** * Load all the dictionaries for the application. */ private void loadAllContent() throws WebDriverException { if (!dictionaries.isEmpty()) { throw new WebDriverException("Content already present."); } Map<String, LanguageDictionary> dicts = new HashMap<String, LanguageDictionary>(); List<File> l10nFiles = LanguageDictionary.getL10NFiles(app); for (File f : l10nFiles) { String name = LanguageDictionary.extractLanguageName(f); LanguageDictionary res = dicts.get(name); if (res == null) { res = new LanguageDictionary(name); dicts.put(name, res); } try { // and load the content. JSONObject content = res.readContentFromBinaryFile(f); res.addJSONContent(content); } catch (Exception e) { throw new WebDriverException("error loading content for l10n", e); } } dictionaries.addAll(dicts.values()); } public String translate(ContentResult res, AppleLanguage language) throws WebDriverException { LanguageDictionary destinationLanguage = getDictionary(language); return destinationLanguage.translate(res); } public void addDictionary(LanguageDictionary dict) { dictionaries.add(dict); } public String getBundleId() { return getMetadata("CFBundleIdentifier"); } public File getApplicationPath() { return app; } /** * the list of resources to publish via http. */ public Map<String, String> getResources() { Map<String, String> resourceByResourceName = new HashMap<String, String>(); String metadata = getMetadata(ICON); if(metadata.equals("")){ metadata = getFirstIconFile(BUNDLE_ICONS); } resourceByResourceName.put(ICON, metadata); return resourceByResourceName; } private String getFirstIconFile(String bundleIcons){ if(!metadata.has(bundleIcons)){ return ""; } try{ HashMap icons = (HashMap)metadata.get(bundleIcons); HashMap primaryIcon = (HashMap)icons.get("CFBundlePrimaryIcon"); ArrayList iconFiles = (ArrayList)primaryIcon.get("CFBundleIconFiles"); return iconFiles.get(0).toString(); } catch (JSONException e) { throw new WebDriverException("property 'CFBundleIcons' can't be returned. " + e.getMessage(), e); } } private JSONObject getFullPlist() throws Exception { File plist = new File(app, "Info.plist"); PlistFileUtils util = new PlistFileUtils(plist); return util.toJSON(); } public String getMetadata(String key) { if (!metadata.has(key)) { return ""; // throw new WebDriverException("no property " + key + // " for this app."); } try { return metadata.getString(key); } catch (JSONException e) { throw new WebDriverException("property " + key + " can't be returned. " + e.getMessage(), e); } } public List<Integer> getDeviceFamily() { try { JSONArray array = metadata.getJSONArray(DEVICE_FAMILLY); List<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < array.length(); i++) { res.add(array.getInt(i)); } return res; } catch (JSONException e) { throw new WebDriverException("Cannot load device family", e); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((app == null) ? 0 : app.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } APPIOSApplication other = (APPIOSApplication) obj; if (app == null) { if (other.app != null) { return false; } } else if (!app.equals(other.app)) { return false; } return true; } public static APPIOSApplication findSafariLocation(File xcodeInstall, String sdkVersion) { File app = new File(xcodeInstall, "/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" + sdkVersion + ".sdk/Applications/MobileSafari.app"); if (!app.exists()) { throw new WebDriverException(app + " should be the safari app, but doesn't exist."); } return new APPIOSApplication(app.getAbsolutePath()); } public void setDefaultDevice(DeviceType device) { try { File plist = new File(app, "Info.plist"); PListFormat format = getFormat(plist); NSDictionary root = (NSDictionary) PropertyListParser.parse(new FileInputStream(plist)); NSArray devices = (NSArray) root.objectForKey("UIDeviceFamily"); int length = devices.getArray().length; if (length == 1) { return; } NSArray rearrangedArray = new NSArray(length); NSNumber last = null; int index = 0; for (int i = 0; i < length; i++) { NSNumber d = (NSNumber) devices.objectAtIndex(i); if (d.intValue() == device.getDeviceFamily()) { last = d; } else { rearrangedArray.setValue(index, d); index++; } } if (last == null) { throw new WebDriverException( "Cannot find device " + device + " in the supported device list."); } rearrangedArray.setValue(index, last); root.put("UIDeviceFamily", rearrangedArray); write(plist,root,format); } catch (Exception e) { throw new WebDriverException("Cannot change the default device for the app." + e.getMessage(), e); } } enum PListFormat{ binary,text,xml; } private void write(File dest,NSDictionary content,PListFormat format) throws IOException { switch (format){ case binary: BinaryPropertyListWriter.write(dest,content); case xml: PropertyListParser.saveAsXML(content,dest); case text: PropertyListParser.saveAsASCII(content,dest); } } private PListFormat getFormat(File f) throws IOException { FileInputStream fis = new FileInputStream(f); byte b[] = new byte[8]; fis.read(b,0,8); String magicString = new String(b); fis.close(); if (magicString.startsWith("bplist")) { return PListFormat.binary; } else if (magicString.trim().startsWith("(") || magicString.trim().startsWith("{") || magicString.trim().startsWith("/")) { return PListFormat.text; } else { return PListFormat.xml; } } public IOSCapabilities getCapabilities() { IOSCapabilities cap = new IOSCapabilities(); cap.setSupportedLanguages(getSupportedLanguagesCodes()); cap.setCapability("applicationPath", getApplicationPath().getAbsoluteFile()); List<DeviceType> supported = getSupportedDevices(); if (supported.contains(DeviceType.iphone)) { cap.setDevice(DeviceType.iphone); } else { cap.setDevice(DeviceType.ipad); } if (this instanceof IPAApplication) { cap.setCapability(IOSCapabilities.SIMULATOR, false); } else { cap.setCapability(IOSCapabilities.SIMULATOR, true); } cap.setCapability(IOSCapabilities.SUPPORTED_DEVICES, supported); for (Iterator iterator = getMetadata().keys(); iterator.hasNext(); ) { String key = (String) iterator.next(); try { Object value = getMetadata().get(key); cap.setCapability(key, value); } catch (JSONException e) { throw new WebDriverException("cannot get metadata", e); } } return cap; } public static boolean canRun(IOSCapabilities desiredCapabilities, IOSCapabilities appCapability) { if (desiredCapabilities.isSimulator() != null && desiredCapabilities.isSimulator() != appCapability.isSimulator()) { return false; } if (desiredCapabilities.getBundleName() == null) { throw new WebDriverException("you need to specify the bundle to test."); } String desired = desiredCapabilities.getBundleName(); String bundleName = (String) appCapability.getCapability(IOSCapabilities.BUNDLE_NAME); String displayName = (String) appCapability.getCapability(IOSCapabilities.BUNDLE_DISPLAY_NAME); String name = bundleName != null ? bundleName : displayName; if (!desired.equals(name)) { return false; } if (desiredCapabilities.getBundleVersion() != null && !desiredCapabilities.getBundleVersion() .equals(appCapability.getBundleVersion())) { return false; } if (desiredCapabilities.getDevice() == null) { throw new WebDriverException("you need to specify the device."); } if (!(appCapability.getSupportedDevices() .contains(desiredCapabilities.getDevice()))) { return false; } // check any extra capability starting with plist_ for (String key : desiredCapabilities.getRawCapabilities().keySet()) { if (key.startsWith(IOSCapabilities.MAGIC_PREFIX)) { String realKey = key.replace(MAGIC_PREFIX, ""); if (!desiredCapabilities.getRawCapabilities().get(key) .equals(appCapability.getRawCapabilities().get(realKey))) { return false; } } } String l = desiredCapabilities.getLanguage(); if (appCapability.getSupportedLanguages().isEmpty()) { log.info( "The application doesn't have any content files." - + "The localization related features won't be availabled."); + + " Localization related features won't be available."); } else if (l != null && !appCapability.getSupportedLanguages().contains(l)) { throw new SessionNotCreatedException( "Language requested, " + l + " ,isn't supported.Supported are : " + appCapability.getSupportedLanguages()); } return true; } public String getBundleVersion() { return getMetadata(IOSCapabilities.BUNDLE_VERSION); } public String getApplicationName() { String name = getMetadata(IOSCapabilities.BUNDLE_NAME); String displayName = getMetadata(IOSCapabilities.BUNDLE_DISPLAY_NAME); return (name != null) && ! name.trim().isEmpty() ? name : displayName; } public List<DeviceType> getSupportedDevices() { List<DeviceType> families = new ArrayList<DeviceType>(); String s = (String) getMetadata(IOSCapabilities.DEVICE_FAMILLY); try { JSONArray ar = new JSONArray(s); for (int i = 0; i < ar.length(); i++) { int f = ar.getInt(i); if (f == 1) { families.add(DeviceType.iphone); families.add(DeviceType.ipod); } else { families.add(DeviceType.ipad); } } return families; } catch (JSONException e) { throw new WebDriverException(e); } } public boolean isSimulator() { return "iphonesimulator".equals(getMetadata("DTPlatformName")); } public IOSRunningApplication createInstance(AppleLanguage language) { return new IOSRunningApplication(language, this); } public static APPIOSApplication createFrom(File app) { if (app == null || !app.exists()) { return null; } else if (app.getAbsolutePath().endsWith(".ipa")) { return IPAApplication.createFrom(app); } else if (app.getAbsolutePath().endsWith(".app")) { return new APPIOSApplication(app.getAbsolutePath()); } else { return null; } } }
true
true
public static boolean canRun(IOSCapabilities desiredCapabilities, IOSCapabilities appCapability) { if (desiredCapabilities.isSimulator() != null && desiredCapabilities.isSimulator() != appCapability.isSimulator()) { return false; } if (desiredCapabilities.getBundleName() == null) { throw new WebDriverException("you need to specify the bundle to test."); } String desired = desiredCapabilities.getBundleName(); String bundleName = (String) appCapability.getCapability(IOSCapabilities.BUNDLE_NAME); String displayName = (String) appCapability.getCapability(IOSCapabilities.BUNDLE_DISPLAY_NAME); String name = bundleName != null ? bundleName : displayName; if (!desired.equals(name)) { return false; } if (desiredCapabilities.getBundleVersion() != null && !desiredCapabilities.getBundleVersion() .equals(appCapability.getBundleVersion())) { return false; } if (desiredCapabilities.getDevice() == null) { throw new WebDriverException("you need to specify the device."); } if (!(appCapability.getSupportedDevices() .contains(desiredCapabilities.getDevice()))) { return false; } // check any extra capability starting with plist_ for (String key : desiredCapabilities.getRawCapabilities().keySet()) { if (key.startsWith(IOSCapabilities.MAGIC_PREFIX)) { String realKey = key.replace(MAGIC_PREFIX, ""); if (!desiredCapabilities.getRawCapabilities().get(key) .equals(appCapability.getRawCapabilities().get(realKey))) { return false; } } } String l = desiredCapabilities.getLanguage(); if (appCapability.getSupportedLanguages().isEmpty()) { log.info( "The application doesn't have any content files." + "The localization related features won't be availabled."); } else if (l != null && !appCapability.getSupportedLanguages().contains(l)) { throw new SessionNotCreatedException( "Language requested, " + l + " ,isn't supported.Supported are : " + appCapability.getSupportedLanguages()); } return true; }
public static boolean canRun(IOSCapabilities desiredCapabilities, IOSCapabilities appCapability) { if (desiredCapabilities.isSimulator() != null && desiredCapabilities.isSimulator() != appCapability.isSimulator()) { return false; } if (desiredCapabilities.getBundleName() == null) { throw new WebDriverException("you need to specify the bundle to test."); } String desired = desiredCapabilities.getBundleName(); String bundleName = (String) appCapability.getCapability(IOSCapabilities.BUNDLE_NAME); String displayName = (String) appCapability.getCapability(IOSCapabilities.BUNDLE_DISPLAY_NAME); String name = bundleName != null ? bundleName : displayName; if (!desired.equals(name)) { return false; } if (desiredCapabilities.getBundleVersion() != null && !desiredCapabilities.getBundleVersion() .equals(appCapability.getBundleVersion())) { return false; } if (desiredCapabilities.getDevice() == null) { throw new WebDriverException("you need to specify the device."); } if (!(appCapability.getSupportedDevices() .contains(desiredCapabilities.getDevice()))) { return false; } // check any extra capability starting with plist_ for (String key : desiredCapabilities.getRawCapabilities().keySet()) { if (key.startsWith(IOSCapabilities.MAGIC_PREFIX)) { String realKey = key.replace(MAGIC_PREFIX, ""); if (!desiredCapabilities.getRawCapabilities().get(key) .equals(appCapability.getRawCapabilities().get(realKey))) { return false; } } } String l = desiredCapabilities.getLanguage(); if (appCapability.getSupportedLanguages().isEmpty()) { log.info( "The application doesn't have any content files." + " Localization related features won't be available."); } else if (l != null && !appCapability.getSupportedLanguages().contains(l)) { throw new SessionNotCreatedException( "Language requested, " + l + " ,isn't supported.Supported are : " + appCapability.getSupportedLanguages()); } return true; }
diff --git a/src/com/facebook/buck/event/LogEvent.java b/src/com/facebook/buck/event/LogEvent.java index 77fe6c53cb..0156a18028 100644 --- a/src/com/facebook/buck/event/LogEvent.java +++ b/src/com/facebook/buck/event/LogEvent.java @@ -1,88 +1,88 @@ /* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.event; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.util.logging.Level; /** * Event for messages. Post LogEvents to the event bus where you would normally use * {@link java.util.logging}. */ @SuppressWarnings("PMD.OverrideBothEqualsAndHashcode") public class LogEvent extends AbstractBuckEvent { private final Level level; private final String message; protected LogEvent(Level level, String message) { this.level = Preconditions.checkNotNull(level); this.message = Preconditions.checkNotNull(message); } public Level getLevel() { return level; } public String getMessage() { return message; } public static LogEvent create(Level level, String message, Object... args) { return new LogEvent(level, String.format(message, args)); } public static LogEvent info(String message, Object... args) { return LogEvent.create(Level.INFO, message, args); } public static LogEvent warning(String message, Object... args) { return LogEvent.create(Level.WARNING, message, args); } public static LogEvent severe(String message, Object... args) { return LogEvent.create(Level.SEVERE, message, args); } @Override protected String getEventName() { return "LogEvent"; } @Override protected String getValueString() { return String.format("%s: %s", getLevel(), getMessage()); } @Override public int hashCode() { return Objects.hashCode(getLevel(), getMessage()); } @Override public boolean eventsArePair(BuckEvent event) { - if (!(event instanceof BuckEvent)) { + if (!(event instanceof LogEvent)) { return false; } LogEvent that = (LogEvent)event; return Objects.equal(getLevel(), that.getLevel()) && Objects.equal(getMessage(), that.getMessage()); } }
true
true
public boolean eventsArePair(BuckEvent event) { if (!(event instanceof BuckEvent)) { return false; } LogEvent that = (LogEvent)event; return Objects.equal(getLevel(), that.getLevel()) && Objects.equal(getMessage(), that.getMessage()); }
public boolean eventsArePair(BuckEvent event) { if (!(event instanceof LogEvent)) { return false; } LogEvent that = (LogEvent)event; return Objects.equal(getLevel(), that.getLevel()) && Objects.equal(getMessage(), that.getMessage()); }
diff --git a/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java b/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java index c776fc057..1b2bcd5d2 100644 --- a/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java +++ b/manual-layout-impl/src/main/java/org/cytoscape/view/manual/internal/control/actions/align/HAlignLeft.java @@ -1,62 +1,62 @@ package org.cytoscape.view.manual.internal.control.actions.align; /* * #%L * Cytoscape Manual Layout Impl (manual-layout-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2006 - 2013 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import javax.swing.Icon; import org.cytoscape.view.manual.internal.control.actions.AbstractControlAction; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.model.CyNode; import org.cytoscape.view.model.View; import org.cytoscape.view.presentation.property.BasicVisualLexicon; /** * */ public class HAlignLeft extends AbstractControlAction { private static final long serialVersionUID = 6744254664976466345L; public HAlignLeft(Icon i,CyApplicationManager appMgr) { super("",i,appMgr); } protected void control(List<View<CyNode>> nodes) { for ( View<CyNode> n : nodes ) { - double w = n.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION) / 2; + double w = n.getVisualProperty(BasicVisualLexicon.NODE_WIDTH) / 2; n.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, X_min + w); } } protected double getX(View<CyNode> n) { double x = n.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION); double w = n.getVisualProperty(BasicVisualLexicon.NODE_WIDTH) / 2; return x - w; } }
true
true
protected void control(List<View<CyNode>> nodes) { for ( View<CyNode> n : nodes ) { double w = n.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION) / 2; n.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, X_min + w); } }
protected void control(List<View<CyNode>> nodes) { for ( View<CyNode> n : nodes ) { double w = n.getVisualProperty(BasicVisualLexicon.NODE_WIDTH) / 2; n.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, X_min + w); } }
diff --git a/components/common/src/main/java/org/openengsb/core/common/util/ModelProxyHandler.java b/components/common/src/main/java/org/openengsb/core/common/util/ModelProxyHandler.java index 9dc9ef492..632cead40 100644 --- a/components/common/src/main/java/org/openengsb/core/common/util/ModelProxyHandler.java +++ b/components/common/src/main/java/org/openengsb/core/common/util/ModelProxyHandler.java @@ -1,166 +1,167 @@ /** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openengsb.core.common.util; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openengsb.core.api.model.OpenEngSBModel; import org.openengsb.core.api.model.OpenEngSBModelEntry; import org.openengsb.core.api.model.OpenEngSBModelId; import org.openengsb.core.common.AbstractOpenEngSBInvocationHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simulates an implementation for a model interface. This class is only able to handle getters and setters, toString * and getOpenEngSBModelEntries of domain models. */ public class ModelProxyHandler extends AbstractOpenEngSBInvocationHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ModelProxyHandler.class); private Map<String, OpenEngSBModelEntry> objects; public ModelProxyHandler(Class<?> model, OpenEngSBModelEntry... entries) { objects = new HashMap<String, OpenEngSBModelEntry>(); fillModelWithNullValues(model); for (OpenEngSBModelEntry entry : entries) { if (objects.containsKey(entry.getKey())) { objects.put(entry.getKey(), entry); } else { LOGGER.error("entry \"{}\" can not be set because the interface doesn't contain this field!", entry.getKey()); } } } private void fillModelWithNullValues(Class<?> model) { for (PropertyDescriptor propertyDescriptor : ModelUtils.getPropertyDescriptorsForClass(model)) { String propertyName = propertyDescriptor.getName(); Class<?> clasz = propertyDescriptor.getPropertyType(); objects.put(propertyName, new OpenEngSBModelEntry(propertyName, null, clasz)); } } @Override protected Object handleInvoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getOpenEngSBModelEntries")) { LOGGER.debug("getOpenEngSBModelEntries was called"); return handleGetOpenEngSBModelEntries(); } else if (method.getName().startsWith("set")) { LOGGER.debug("setter method \"{}\" was called with parameter {}", method.getName(), args[0]); handleSetMethod(method, args); return null; } else if (method.getName().startsWith("get")) { LOGGER.debug("called getter method \"{}\" was called", method.getName()); return handleGetMethod(method); } else if (method.getName().equals("toString")) { LOGGER.debug("toString() was called"); return handleToString(); } else if (method.getName().equals("addOpenEngSBModelEntry")) { OpenEngSBModelEntry entry = (OpenEngSBModelEntry) args[0]; LOGGER.debug("addOpenEngSBModelEntry was called with entry {} with the value {}", entry.getKey(), entry.getValue()); handleAddEntry(entry); return null; } else if (method.getName().equals("removeOpenEngSBModelEntry")) { LOGGER.debug("removeOpenEngSBModelEntry was called with key {} ", args[0]); handleRemoveEntry((String) args[0]); return null; } else { - LOGGER.error("EKBProxyHandler is only able to handle getters and setters"); - throw new IllegalArgumentException("EKBProxyHandler is only able to handle getters and setters"); + LOGGER.error("{} is only able to handle getters and setters", this.getClass().getSimpleName()); + throw new IllegalArgumentException(this.getClass().getSimpleName() + + " is only able to handle getters and setters"); } } private void handleAddEntry(OpenEngSBModelEntry entry) { objects.put(entry.getKey(), entry); } private void handleRemoveEntry(String key) { objects.remove(key); } private void handleSetMethod(Method method, Object[] args) throws Throwable { String propertyName = ModelUtils.getPropertyName(method); if (method.isAnnotationPresent(OpenEngSBModelId.class) && args[0] != null) { objects.put("edbId", new OpenEngSBModelEntry("edbId", args[0].toString(), String.class)); } Class<?> clasz = method.getParameterTypes()[0]; objects.put(propertyName, new OpenEngSBModelEntry(propertyName, args[0], clasz)); } private Object handleGetMethod(Method method) throws Throwable { String propertyName = ModelUtils.getPropertyName(method); return objects.get(propertyName).getValue(); } private String handleToString() { StringBuilder builder = new StringBuilder(); boolean first = true; builder.append("{ "); for (OpenEngSBModelEntry entry : objects.values()) { if (!first) { builder.append(", "); } builder.append(entry.getKey()).append(" == ").append(entry.getValue()); first = false; } builder.append(" }"); return builder.toString(); } private Object handleGetOpenEngSBModelEntries() throws Throwable { List<OpenEngSBModelEntry> entries = new ArrayList<OpenEngSBModelEntry>(); for (OpenEngSBModelEntry entry : objects.values()) { Class<?> clasz = entry.getType(); if (clasz.isEnum() && entry.getValue() != null) { entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue().toString(), String.class)); } else if (List.class.isAssignableFrom(clasz) && entry.getValue() != null) { List<?> list = (List<?>) entry.getValue(); if (list.size() == 0) { continue; } Class<?> clazz = list.get(0).getClass(); if (OpenEngSBModel.class.isAssignableFrom(clazz)) { entries.add(entry); } else { entries.addAll(createListElements((List<?>) entry.getValue(), entry.getKey())); } } else { entries.add(entry); } } return entries; } private List<OpenEngSBModelEntry> createListElements(List<?> list, String propertyName) { List<OpenEngSBModelEntry> entries = new ArrayList<OpenEngSBModelEntry>(); if (list == null) { return entries; } for (int i = 0; i < list.size(); i++) { entries.add(new OpenEngSBModelEntry(propertyName + i, list.get(i), list.get(i).getClass())); } return entries; } }
true
true
protected Object handleInvoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getOpenEngSBModelEntries")) { LOGGER.debug("getOpenEngSBModelEntries was called"); return handleGetOpenEngSBModelEntries(); } else if (method.getName().startsWith("set")) { LOGGER.debug("setter method \"{}\" was called with parameter {}", method.getName(), args[0]); handleSetMethod(method, args); return null; } else if (method.getName().startsWith("get")) { LOGGER.debug("called getter method \"{}\" was called", method.getName()); return handleGetMethod(method); } else if (method.getName().equals("toString")) { LOGGER.debug("toString() was called"); return handleToString(); } else if (method.getName().equals("addOpenEngSBModelEntry")) { OpenEngSBModelEntry entry = (OpenEngSBModelEntry) args[0]; LOGGER.debug("addOpenEngSBModelEntry was called with entry {} with the value {}", entry.getKey(), entry.getValue()); handleAddEntry(entry); return null; } else if (method.getName().equals("removeOpenEngSBModelEntry")) { LOGGER.debug("removeOpenEngSBModelEntry was called with key {} ", args[0]); handleRemoveEntry((String) args[0]); return null; } else { LOGGER.error("EKBProxyHandler is only able to handle getters and setters"); throw new IllegalArgumentException("EKBProxyHandler is only able to handle getters and setters"); } }
protected Object handleInvoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getOpenEngSBModelEntries")) { LOGGER.debug("getOpenEngSBModelEntries was called"); return handleGetOpenEngSBModelEntries(); } else if (method.getName().startsWith("set")) { LOGGER.debug("setter method \"{}\" was called with parameter {}", method.getName(), args[0]); handleSetMethod(method, args); return null; } else if (method.getName().startsWith("get")) { LOGGER.debug("called getter method \"{}\" was called", method.getName()); return handleGetMethod(method); } else if (method.getName().equals("toString")) { LOGGER.debug("toString() was called"); return handleToString(); } else if (method.getName().equals("addOpenEngSBModelEntry")) { OpenEngSBModelEntry entry = (OpenEngSBModelEntry) args[0]; LOGGER.debug("addOpenEngSBModelEntry was called with entry {} with the value {}", entry.getKey(), entry.getValue()); handleAddEntry(entry); return null; } else if (method.getName().equals("removeOpenEngSBModelEntry")) { LOGGER.debug("removeOpenEngSBModelEntry was called with key {} ", args[0]); handleRemoveEntry((String) args[0]); return null; } else { LOGGER.error("{} is only able to handle getters and setters", this.getClass().getSimpleName()); throw new IllegalArgumentException(this.getClass().getSimpleName() + " is only able to handle getters and setters"); } }
diff --git a/src/uk/ac/horizon/ug/hyperplace/proxy/Main.java b/src/uk/ac/horizon/ug/hyperplace/proxy/Main.java index 595c5f5..eeacca9 100755 --- a/src/uk/ac/horizon/ug/hyperplace/proxy/Main.java +++ b/src/uk/ac/horizon/ug/hyperplace/proxy/Main.java @@ -1,167 +1,167 @@ /** * */ package uk.ac.horizon.ug.hyperplace.proxy; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** An exploration of using the Hyperplace Android client (currently the one from HP/Pyramid) * with the drools-based game server. * * @author cmg * */ public class Main implements Runnable { static Logger logger = Logger.getLogger(Main.class.getName()); static final int DEFAULT_PORT = 7474; /** server socket */ protected ServerSocket serverSocket; public Main(int defaultPort) { try { // TODO Auto-generated constructor stub serverSocket = new ServerSocket(defaultPort); } catch (Exception e) { logger.log(Level.WARNING, "Error starting proxy on port "+defaultPort, e); } } /** run - accept thread */ public void run() { try { logger.info("Accepting connections on "+serverSocket); while (true) { Socket socket = serverSocket.accept(); try { handleClient(socket); } catch (Exception e) { logger.log(Level.WARNING, "Error with new client on "+socket, e); } } } catch (Exception e) { logger.log(Level.WARNING, "Error accept new connections - stopping", e); } } private void handleClient(Socket socket) { new ClientHandler(socket); } /** client handler */ static class ClientHandler { protected Socket socket; protected boolean dead; protected boolean registered = false; protected String deviceType; protected String deviceId; protected BufferedWriter out; ClientHandler(Socket socket) { this.socket = socket; // read thread new Thread() { public void run() { doSocketInput(); } }.start(); } protected void doSocketInput() { try { BufferedReader stdIn = new BufferedReader( new InputStreamReader( socket.getInputStream() )); String input; while ( ( input = stdIn.readLine() ) != null) { JSONObject json = new JSONObject(input); logger.info("Read message from "+socket+": "+input); String msgName = json.getString("__name"); if ("REGISTER".equals(msgName)) { if (registered) throw new IOException("Duplicate REGISTER from client "+socket+": "+json); handleRegister(json); } else if (!registered) throw new IOException("Message when not registered from client "+socket+": "+json); else { // TODO } } logger.info("Client "+socket+" disconnected"); dead = true; socket.close(); } catch (Exception e) { logger.log(Level.WARNING, "Error in client input for "+socket, e); try { socket.close(); } catch (Exception e2) {/*ignore*/} } } private void handleRegister(JSONObject json) throws JSONException, IOException { // TODO Auto-generated method stub JSONObject data = json.getJSONObject("__data"); deviceType = data.getString("deviceType"); if (data.has("deviceId")) deviceId = data.getString("deviceId"); else { logger.log(Level.WARNING, "Client "+socket+" did not provide deviceId on registration; assuming default"); deviceId = "000000000000000"; } registered = true; logger.info("Registered "+deviceType+":"+deviceId+" as "+socket); // return success JSONObject resp = new JSONObject(); resp.put("__type", "HPUpdate"); resp.put("__timestamp", System.currentTimeMillis()); JSONObject rdata = new JSONObject(); resp.put("__data", rdata); JSONObject response = new JSONObject(); response.put("action", "REGISTER"); response.put("success", true); response.put("text", "Registered with hyperplace proxy"); rdata.put("__responseUpdate", response); JSONObject mainState = new JSONObject(); - mainState.put("__name", "ProxyState"); + mainState.put("__name", "PyramidMainState"); mainState.put("__type", "HPMainState"); mainState.put("__completed", true); mainState.put("__errorMessage", (Object)null); mainState.put("assets", new JSONArray()); mainState.put("tabs", new JSONArray()); JSONArray stateUpdates = new JSONArray(); stateUpdates.put(mainState); rdata.put("__stateUpdates", stateUpdates); send(resp); } private void send(JSONObject rdata) throws IOException { // TODO Auto-generated method stub if (out==null) out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); out.write(rdata.toString()); out.write("\n"); out.flush(); logger.info("Sent to "+socket+": "+rdata); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new Thread(new Main(DEFAULT_PORT)).start(); } }
true
true
private void handleRegister(JSONObject json) throws JSONException, IOException { // TODO Auto-generated method stub JSONObject data = json.getJSONObject("__data"); deviceType = data.getString("deviceType"); if (data.has("deviceId")) deviceId = data.getString("deviceId"); else { logger.log(Level.WARNING, "Client "+socket+" did not provide deviceId on registration; assuming default"); deviceId = "000000000000000"; } registered = true; logger.info("Registered "+deviceType+":"+deviceId+" as "+socket); // return success JSONObject resp = new JSONObject(); resp.put("__type", "HPUpdate"); resp.put("__timestamp", System.currentTimeMillis()); JSONObject rdata = new JSONObject(); resp.put("__data", rdata); JSONObject response = new JSONObject(); response.put("action", "REGISTER"); response.put("success", true); response.put("text", "Registered with hyperplace proxy"); rdata.put("__responseUpdate", response); JSONObject mainState = new JSONObject(); mainState.put("__name", "ProxyState"); mainState.put("__type", "HPMainState"); mainState.put("__completed", true); mainState.put("__errorMessage", (Object)null); mainState.put("assets", new JSONArray()); mainState.put("tabs", new JSONArray()); JSONArray stateUpdates = new JSONArray(); stateUpdates.put(mainState); rdata.put("__stateUpdates", stateUpdates); send(resp); }
private void handleRegister(JSONObject json) throws JSONException, IOException { // TODO Auto-generated method stub JSONObject data = json.getJSONObject("__data"); deviceType = data.getString("deviceType"); if (data.has("deviceId")) deviceId = data.getString("deviceId"); else { logger.log(Level.WARNING, "Client "+socket+" did not provide deviceId on registration; assuming default"); deviceId = "000000000000000"; } registered = true; logger.info("Registered "+deviceType+":"+deviceId+" as "+socket); // return success JSONObject resp = new JSONObject(); resp.put("__type", "HPUpdate"); resp.put("__timestamp", System.currentTimeMillis()); JSONObject rdata = new JSONObject(); resp.put("__data", rdata); JSONObject response = new JSONObject(); response.put("action", "REGISTER"); response.put("success", true); response.put("text", "Registered with hyperplace proxy"); rdata.put("__responseUpdate", response); JSONObject mainState = new JSONObject(); mainState.put("__name", "PyramidMainState"); mainState.put("__type", "HPMainState"); mainState.put("__completed", true); mainState.put("__errorMessage", (Object)null); mainState.put("assets", new JSONArray()); mainState.put("tabs", new JSONArray()); JSONArray stateUpdates = new JSONArray(); stateUpdates.put(mainState); rdata.put("__stateUpdates", stateUpdates); send(resp); }
diff --git a/htroot/ConfigNetwork_p.java b/htroot/ConfigNetwork_p.java index bd3fddd3d..9a9c921f5 100644 --- a/htroot/ConfigNetwork_p.java +++ b/htroot/ConfigNetwork_p.java @@ -1,247 +1,247 @@ // ConfigNetwork_p.java // -------------------- // (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published 20.04.2007 on http://yacy.net // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $ // $LastChangedRevision: 1986 $ // $LastChangedBy: orbiter $ // // LICENSE // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import java.io.File; import java.util.HashSet; import de.anomic.http.httpHeader; import de.anomic.http.httpd; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverBusyThread; import de.anomic.server.serverCodings; import de.anomic.server.serverFileUtils; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; public class ConfigNetwork_p { public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { plasmaSwitchboard sb = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); int commit = 0; // load all options for network definitions File networkBootstrapLocationsFile = new File(new File(sb.getRootPath(), "defaults"), "yacy.networks"); HashSet<String> networkBootstrapLocations = serverFileUtils.loadList(networkBootstrapLocationsFile); if (post != null) { if (post.containsKey("changeNetwork")) { String networkDefinition = post.get("networkDefinition", "defaults/yacy.network.freeworld.unit"); if (networkDefinition.equals(sb.getConfig("network.unit.definition", ""))) { // no change commit = 3; } else { // shut down old network and index, start up new network and index commit = 1; sb.switchNetwork(networkDefinition); // check if the password is given if (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) { prop.put("commitPasswordWarning", "1"); } } } if (post.containsKey("save")) { boolean crawlResponse = post.get("crawlResponse", "off").equals("on"); // DHT control boolean indexDistribute = post.get("indexDistribute", "").equals("on"); boolean indexReceive = post.get("indexReceive", "").equals("on"); boolean robinsonmode = post.get("network", "").equals("robinson"); String clustermode = post.get("cluster.mode", "publicpeer"); if (robinsonmode) { indexDistribute = false; indexReceive = false; if ((clustermode.equals("privatepeer")) || (clustermode.equals("publicpeer"))) { prop.put("commitRobinsonWithoutRemoteIndexing", "1"); crawlResponse = false; } if ((clustermode.equals("privatecluster")) || (clustermode.equals("publiccluster"))) { prop.put("commitRobinsonWithRemoteIndexing", "1"); crawlResponse = true; } commit = 1; } else { if (!indexDistribute && !indexReceive) { prop.put("commitDHTIsRobinson", "1"); commit = 2; } else if (indexDistribute && indexReceive) { commit = 1; } else { if (!indexReceive) prop.put("commitDHTNoGlobalSearch", "1"); commit = 1; } if (!crawlResponse) { prop.put("commitCrawlPlea", "1"); } } if (indexDistribute) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, false); } if (post.get("indexDistributeWhileCrawling","").equals("on")) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, false); } if (post.get("indexDistributeWhileIndexing","").equals("on")) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, false); } if (indexReceive) { sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(true); } else { sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(false); } if (post.get("indexReceiveBlockBlacklist", "").equals("on")) { sb.setConfig("indexReceiveBlockBlacklist", true); } else { sb.setConfig("indexReceiveBlockBlacklist", false); } if (post.containsKey("peertags")) { sb.webIndex.seedDB.mySeed().setPeerTags(serverCodings.string2set(normalizedList(post.get("peertags")), ",")); } sb.setConfig("cluster.mode", post.get("cluster.mode", "publicpeer")); // read remote crawl request settings sb.setConfig("crawlResponse", (crawlResponse) ? "true" : "false"); int newppm = 1; try { newppm = Math.max(1, Integer.parseInt(post.get("acceptCrawlLimit", "1"))); } catch (NumberFormatException e) {} long newBusySleep = Math.max(100, 60000 / newppm); serverBusyThread rct = sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); rct.setBusySleep(newBusySleep); sb.setConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, Long.toString(newBusySleep)); sb.setConfig("cluster.peers.ipport", checkIPPortList(post.get("cluster.peers.ipport", ""))); sb.setConfig("cluster.peers.yacydomain", checkYaCyDomainList(post.get("cluster.peers.yacydomain", ""))); // update the cluster hash set sb.clusterhashes = sb.webIndex.seedDB.clusterHashes(sb.getConfig("cluster.peers.yacydomain", "")); } } // write answer code prop.put("commit", commit); // write remote crawl request settings prop.put("crawlResponse", sb.getConfigBool("crawlResponse", false) ? "1" : "0"); long RTCbusySleep = 100; try { - RTCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, "100")); + RTCbusySleep = Math.max(1, Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, "100"))); } catch (NumberFormatException e) {} - int RTCppm = (int) (60000L / (RTCbusySleep + 1)); + int RTCppm = (int) (60000L / RTCbusySleep); prop.put("acceptCrawlLimit", RTCppm); boolean indexDistribute = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true"); boolean indexReceive = sb.getConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, "true").equals("true"); prop.put("indexDistributeChecked", (indexDistribute) ? "1" : "0"); prop.put("indexDistributeWhileCrawling.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "1" : "0"); prop.put("indexDistributeWhileCrawling.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "0" : "1"); prop.put("indexDistributeWhileIndexing.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, "true").equals("true")) ? "1" : "0"); prop.put("indexDistributeWhileIndexing.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, "true").equals("true")) ? "0" : "1"); prop.put("indexReceiveChecked", (indexReceive) ? "1" : "0"); prop.put("indexReceiveBlockBlacklistChecked.on", (sb.getConfig("indexReceiveBlockBlacklist", "true").equals("true")) ? "1" : "0"); prop.put("indexReceiveBlockBlacklistChecked.off", (sb.getConfig("indexReceiveBlockBlacklist", "true").equals("true")) ? "0" : "1"); prop.putHTML("peertags", serverCodings.set2string(sb.webIndex.seedDB.mySeed().getPeerTags(), ",", false)); // set seed information directly sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteCrawl(sb.getConfigBool("crawlResponse", false)); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(indexReceive); // set p2p/robinson mode flags and values prop.put("p2p.checked", (indexDistribute || indexReceive) ? "1" : "0"); prop.put("robinson.checked", (indexDistribute || indexReceive) ? "0" : "1"); prop.put("cluster.peers.ipport", sb.getConfig("cluster.peers.ipport", "")); prop.put("cluster.peers.yacydomain", sb.getConfig("cluster.peers.yacydomain", "")); prop.put("cluster.peers.yacydomain.hashes", (sb.clusterhashes.size() == 0) ? "" : sb.clusterhashes.toString()); // set p2p mode flags prop.put("privatepeerChecked", (sb.getConfig("cluster.mode", "").equals("privatepeer")) ? "1" : "0"); prop.put("privateclusterChecked", (sb.getConfig("cluster.mode", "").equals("privatecluster")) ? "1" : "0"); prop.put("publicclusterChecked", (sb.getConfig("cluster.mode", "").equals("publiccluster")) ? "1" : "0"); prop.put("publicpeerChecked", (sb.getConfig("cluster.mode", "").equals("publicpeer")) ? "1" : "0"); // set network configuration prop.put("network.unit.definition", sb.getConfig("network.unit.definition", "")); prop.put("network.unit.name", sb.getConfig("network.unit.name", "")); prop.put("network.unit.description", sb.getConfig("network.unit.description", "")); prop.put("network.unit.domain", sb.getConfig("network.unit.domain", "")); prop.put("network.unit.dht", sb.getConfig("network.unit.dht", "")); networkBootstrapLocations.remove(sb.getConfig("network.unit.definition", "")); int c = 0; for (String s: networkBootstrapLocations) prop.put("networks_" + c++ + "_network", s); prop.put("networks", c); return prop; } public static String normalizedList(String input) { input = input.replace(' ', ','); input = input.replace(' ', ';'); input = input.replaceAll(",,", ","); if (input.startsWith(",")) input = input.substring(1); if (input.endsWith(",")) input = input.substring(0, input.length() - 1); return input; } public static String checkYaCyDomainList(String input) { input = normalizedList(input); String[] s = input.split(","); input = ""; for (int i = 0; i < s.length; i++) { if ((s[i].endsWith(".yacyh")) || (s[i].endsWith(".yacy")) || (s[i].indexOf(".yacyh=") > 0) || (s[i].indexOf(".yacy=") > 0)) input += "," + s[i]; } if (input.length() == 0) return input; else return input.substring(1); } public static String checkIPPortList(String input) { input = normalizedList(input); String[] s = input.split(","); input = ""; for (int i = 0; i < s.length; i++) { if (s[i].indexOf(':') >= 9) input += "," + s[i]; } if (input.length() == 0) return input; else return input.substring(1); } }
false
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { plasmaSwitchboard sb = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); int commit = 0; // load all options for network definitions File networkBootstrapLocationsFile = new File(new File(sb.getRootPath(), "defaults"), "yacy.networks"); HashSet<String> networkBootstrapLocations = serverFileUtils.loadList(networkBootstrapLocationsFile); if (post != null) { if (post.containsKey("changeNetwork")) { String networkDefinition = post.get("networkDefinition", "defaults/yacy.network.freeworld.unit"); if (networkDefinition.equals(sb.getConfig("network.unit.definition", ""))) { // no change commit = 3; } else { // shut down old network and index, start up new network and index commit = 1; sb.switchNetwork(networkDefinition); // check if the password is given if (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) { prop.put("commitPasswordWarning", "1"); } } } if (post.containsKey("save")) { boolean crawlResponse = post.get("crawlResponse", "off").equals("on"); // DHT control boolean indexDistribute = post.get("indexDistribute", "").equals("on"); boolean indexReceive = post.get("indexReceive", "").equals("on"); boolean robinsonmode = post.get("network", "").equals("robinson"); String clustermode = post.get("cluster.mode", "publicpeer"); if (robinsonmode) { indexDistribute = false; indexReceive = false; if ((clustermode.equals("privatepeer")) || (clustermode.equals("publicpeer"))) { prop.put("commitRobinsonWithoutRemoteIndexing", "1"); crawlResponse = false; } if ((clustermode.equals("privatecluster")) || (clustermode.equals("publiccluster"))) { prop.put("commitRobinsonWithRemoteIndexing", "1"); crawlResponse = true; } commit = 1; } else { if (!indexDistribute && !indexReceive) { prop.put("commitDHTIsRobinson", "1"); commit = 2; } else if (indexDistribute && indexReceive) { commit = 1; } else { if (!indexReceive) prop.put("commitDHTNoGlobalSearch", "1"); commit = 1; } if (!crawlResponse) { prop.put("commitCrawlPlea", "1"); } } if (indexDistribute) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, false); } if (post.get("indexDistributeWhileCrawling","").equals("on")) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, false); } if (post.get("indexDistributeWhileIndexing","").equals("on")) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, false); } if (indexReceive) { sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(true); } else { sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(false); } if (post.get("indexReceiveBlockBlacklist", "").equals("on")) { sb.setConfig("indexReceiveBlockBlacklist", true); } else { sb.setConfig("indexReceiveBlockBlacklist", false); } if (post.containsKey("peertags")) { sb.webIndex.seedDB.mySeed().setPeerTags(serverCodings.string2set(normalizedList(post.get("peertags")), ",")); } sb.setConfig("cluster.mode", post.get("cluster.mode", "publicpeer")); // read remote crawl request settings sb.setConfig("crawlResponse", (crawlResponse) ? "true" : "false"); int newppm = 1; try { newppm = Math.max(1, Integer.parseInt(post.get("acceptCrawlLimit", "1"))); } catch (NumberFormatException e) {} long newBusySleep = Math.max(100, 60000 / newppm); serverBusyThread rct = sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); rct.setBusySleep(newBusySleep); sb.setConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, Long.toString(newBusySleep)); sb.setConfig("cluster.peers.ipport", checkIPPortList(post.get("cluster.peers.ipport", ""))); sb.setConfig("cluster.peers.yacydomain", checkYaCyDomainList(post.get("cluster.peers.yacydomain", ""))); // update the cluster hash set sb.clusterhashes = sb.webIndex.seedDB.clusterHashes(sb.getConfig("cluster.peers.yacydomain", "")); } } // write answer code prop.put("commit", commit); // write remote crawl request settings prop.put("crawlResponse", sb.getConfigBool("crawlResponse", false) ? "1" : "0"); long RTCbusySleep = 100; try { RTCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, "100")); } catch (NumberFormatException e) {} int RTCppm = (int) (60000L / (RTCbusySleep + 1)); prop.put("acceptCrawlLimit", RTCppm); boolean indexDistribute = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true"); boolean indexReceive = sb.getConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, "true").equals("true"); prop.put("indexDistributeChecked", (indexDistribute) ? "1" : "0"); prop.put("indexDistributeWhileCrawling.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "1" : "0"); prop.put("indexDistributeWhileCrawling.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "0" : "1"); prop.put("indexDistributeWhileIndexing.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, "true").equals("true")) ? "1" : "0"); prop.put("indexDistributeWhileIndexing.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, "true").equals("true")) ? "0" : "1"); prop.put("indexReceiveChecked", (indexReceive) ? "1" : "0"); prop.put("indexReceiveBlockBlacklistChecked.on", (sb.getConfig("indexReceiveBlockBlacklist", "true").equals("true")) ? "1" : "0"); prop.put("indexReceiveBlockBlacklistChecked.off", (sb.getConfig("indexReceiveBlockBlacklist", "true").equals("true")) ? "0" : "1"); prop.putHTML("peertags", serverCodings.set2string(sb.webIndex.seedDB.mySeed().getPeerTags(), ",", false)); // set seed information directly sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteCrawl(sb.getConfigBool("crawlResponse", false)); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(indexReceive); // set p2p/robinson mode flags and values prop.put("p2p.checked", (indexDistribute || indexReceive) ? "1" : "0"); prop.put("robinson.checked", (indexDistribute || indexReceive) ? "0" : "1"); prop.put("cluster.peers.ipport", sb.getConfig("cluster.peers.ipport", "")); prop.put("cluster.peers.yacydomain", sb.getConfig("cluster.peers.yacydomain", "")); prop.put("cluster.peers.yacydomain.hashes", (sb.clusterhashes.size() == 0) ? "" : sb.clusterhashes.toString()); // set p2p mode flags prop.put("privatepeerChecked", (sb.getConfig("cluster.mode", "").equals("privatepeer")) ? "1" : "0"); prop.put("privateclusterChecked", (sb.getConfig("cluster.mode", "").equals("privatecluster")) ? "1" : "0"); prop.put("publicclusterChecked", (sb.getConfig("cluster.mode", "").equals("publiccluster")) ? "1" : "0"); prop.put("publicpeerChecked", (sb.getConfig("cluster.mode", "").equals("publicpeer")) ? "1" : "0"); // set network configuration prop.put("network.unit.definition", sb.getConfig("network.unit.definition", "")); prop.put("network.unit.name", sb.getConfig("network.unit.name", "")); prop.put("network.unit.description", sb.getConfig("network.unit.description", "")); prop.put("network.unit.domain", sb.getConfig("network.unit.domain", "")); prop.put("network.unit.dht", sb.getConfig("network.unit.dht", "")); networkBootstrapLocations.remove(sb.getConfig("network.unit.definition", "")); int c = 0; for (String s: networkBootstrapLocations) prop.put("networks_" + c++ + "_network", s); prop.put("networks", c); return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) { plasmaSwitchboard sb = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); int commit = 0; // load all options for network definitions File networkBootstrapLocationsFile = new File(new File(sb.getRootPath(), "defaults"), "yacy.networks"); HashSet<String> networkBootstrapLocations = serverFileUtils.loadList(networkBootstrapLocationsFile); if (post != null) { if (post.containsKey("changeNetwork")) { String networkDefinition = post.get("networkDefinition", "defaults/yacy.network.freeworld.unit"); if (networkDefinition.equals(sb.getConfig("network.unit.definition", ""))) { // no change commit = 3; } else { // shut down old network and index, start up new network and index commit = 1; sb.switchNetwork(networkDefinition); // check if the password is given if (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) { prop.put("commitPasswordWarning", "1"); } } } if (post.containsKey("save")) { boolean crawlResponse = post.get("crawlResponse", "off").equals("on"); // DHT control boolean indexDistribute = post.get("indexDistribute", "").equals("on"); boolean indexReceive = post.get("indexReceive", "").equals("on"); boolean robinsonmode = post.get("network", "").equals("robinson"); String clustermode = post.get("cluster.mode", "publicpeer"); if (robinsonmode) { indexDistribute = false; indexReceive = false; if ((clustermode.equals("privatepeer")) || (clustermode.equals("publicpeer"))) { prop.put("commitRobinsonWithoutRemoteIndexing", "1"); crawlResponse = false; } if ((clustermode.equals("privatecluster")) || (clustermode.equals("publiccluster"))) { prop.put("commitRobinsonWithRemoteIndexing", "1"); crawlResponse = true; } commit = 1; } else { if (!indexDistribute && !indexReceive) { prop.put("commitDHTIsRobinson", "1"); commit = 2; } else if (indexDistribute && indexReceive) { commit = 1; } else { if (!indexReceive) prop.put("commitDHTNoGlobalSearch", "1"); commit = 1; } if (!crawlResponse) { prop.put("commitCrawlPlea", "1"); } } if (indexDistribute) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, false); } if (post.get("indexDistributeWhileCrawling","").equals("on")) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, false); } if (post.get("indexDistributeWhileIndexing","").equals("on")) { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, true); } else { sb.setConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, false); } if (indexReceive) { sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, true); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(true); } else { sb.setConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, false); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(false); } if (post.get("indexReceiveBlockBlacklist", "").equals("on")) { sb.setConfig("indexReceiveBlockBlacklist", true); } else { sb.setConfig("indexReceiveBlockBlacklist", false); } if (post.containsKey("peertags")) { sb.webIndex.seedDB.mySeed().setPeerTags(serverCodings.string2set(normalizedList(post.get("peertags")), ",")); } sb.setConfig("cluster.mode", post.get("cluster.mode", "publicpeer")); // read remote crawl request settings sb.setConfig("crawlResponse", (crawlResponse) ? "true" : "false"); int newppm = 1; try { newppm = Math.max(1, Integer.parseInt(post.get("acceptCrawlLimit", "1"))); } catch (NumberFormatException e) {} long newBusySleep = Math.max(100, 60000 / newppm); serverBusyThread rct = sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); rct.setBusySleep(newBusySleep); sb.setConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, Long.toString(newBusySleep)); sb.setConfig("cluster.peers.ipport", checkIPPortList(post.get("cluster.peers.ipport", ""))); sb.setConfig("cluster.peers.yacydomain", checkYaCyDomainList(post.get("cluster.peers.yacydomain", ""))); // update the cluster hash set sb.clusterhashes = sb.webIndex.seedDB.clusterHashes(sb.getConfig("cluster.peers.yacydomain", "")); } } // write answer code prop.put("commit", commit); // write remote crawl request settings prop.put("crawlResponse", sb.getConfigBool("crawlResponse", false) ? "1" : "0"); long RTCbusySleep = 100; try { RTCbusySleep = Math.max(1, Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL_BUSYSLEEP, "100"))); } catch (NumberFormatException e) {} int RTCppm = (int) (60000L / RTCbusySleep); prop.put("acceptCrawlLimit", RTCppm); boolean indexDistribute = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true"); boolean indexReceive = sb.getConfig(plasmaSwitchboard.INDEX_RECEIVE_ALLOW, "true").equals("true"); prop.put("indexDistributeChecked", (indexDistribute) ? "1" : "0"); prop.put("indexDistributeWhileCrawling.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "1" : "0"); prop.put("indexDistributeWhileCrawling.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_CRAWLING, "true").equals("true")) ? "0" : "1"); prop.put("indexDistributeWhileIndexing.on", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, "true").equals("true")) ? "1" : "0"); prop.put("indexDistributeWhileIndexing.off", (sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW_WHILE_INDEXING, "true").equals("true")) ? "0" : "1"); prop.put("indexReceiveChecked", (indexReceive) ? "1" : "0"); prop.put("indexReceiveBlockBlacklistChecked.on", (sb.getConfig("indexReceiveBlockBlacklist", "true").equals("true")) ? "1" : "0"); prop.put("indexReceiveBlockBlacklistChecked.off", (sb.getConfig("indexReceiveBlockBlacklist", "true").equals("true")) ? "0" : "1"); prop.putHTML("peertags", serverCodings.set2string(sb.webIndex.seedDB.mySeed().getPeerTags(), ",", false)); // set seed information directly sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteCrawl(sb.getConfigBool("crawlResponse", false)); sb.webIndex.seedDB.mySeed().setFlagAcceptRemoteIndex(indexReceive); // set p2p/robinson mode flags and values prop.put("p2p.checked", (indexDistribute || indexReceive) ? "1" : "0"); prop.put("robinson.checked", (indexDistribute || indexReceive) ? "0" : "1"); prop.put("cluster.peers.ipport", sb.getConfig("cluster.peers.ipport", "")); prop.put("cluster.peers.yacydomain", sb.getConfig("cluster.peers.yacydomain", "")); prop.put("cluster.peers.yacydomain.hashes", (sb.clusterhashes.size() == 0) ? "" : sb.clusterhashes.toString()); // set p2p mode flags prop.put("privatepeerChecked", (sb.getConfig("cluster.mode", "").equals("privatepeer")) ? "1" : "0"); prop.put("privateclusterChecked", (sb.getConfig("cluster.mode", "").equals("privatecluster")) ? "1" : "0"); prop.put("publicclusterChecked", (sb.getConfig("cluster.mode", "").equals("publiccluster")) ? "1" : "0"); prop.put("publicpeerChecked", (sb.getConfig("cluster.mode", "").equals("publicpeer")) ? "1" : "0"); // set network configuration prop.put("network.unit.definition", sb.getConfig("network.unit.definition", "")); prop.put("network.unit.name", sb.getConfig("network.unit.name", "")); prop.put("network.unit.description", sb.getConfig("network.unit.description", "")); prop.put("network.unit.domain", sb.getConfig("network.unit.domain", "")); prop.put("network.unit.dht", sb.getConfig("network.unit.dht", "")); networkBootstrapLocations.remove(sb.getConfig("network.unit.definition", "")); int c = 0; for (String s: networkBootstrapLocations) prop.put("networks_" + c++ + "_network", s); prop.put("networks", c); return prop; }
diff --git a/src/me/smickles/DynamicMarket/DynamicMarket.java b/src/me/smickles/DynamicMarket/DynamicMarket.java index 4371c22..11b50ee 100644 --- a/src/me/smickles/DynamicMarket/DynamicMarket.java +++ b/src/me/smickles/DynamicMarket/DynamicMarket.java @@ -1,426 +1,427 @@ package me.smickles.DynamicMarket; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.config.Configuration; import com.nijikokun.register.payment.Methods; import com.nijikokun.register.payment.Method.MethodAccount; import me.smickles.DynamicMarket.Invoice; public class DynamicMarket extends JavaPlugin { public static DynamicMarket plugin; public final Logger logger = Logger.getLogger("Minecraft"); public Configuration items; public static BigDecimal MINVALUE = BigDecimal.valueOf(.01).setScale(2); public static BigDecimal MAXVALUE = BigDecimal.valueOf(10000).setScale(2); @Override public void onDisable(){ PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info(pdfFile.getName() + " disabled"); } @Override public void onEnable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " enabled"); //item 'config' items = getConfiguration(); items.load(); String[] itemNames = new String[]{"stone","01","dirt","03","cobblestone","04","sapling","06","sand","12","gravel","13","wood","17","lapis","22","sandstone","24","grass","31","wool","35","dandelion","37","rose","38","brownmushroom","39","redmushroom","40","mossstone","48","obsidian","49","cactus","81","netherrack","87","soulsand","88","vine","106","apple","260","coal","263","diamond","264","iron","265","gold","266","string","287","feather","288","gunpowder","289","seeds","295","flint","318","pork","319","redstone","331","snow","332","leather","334","clay","337","sugarcane","338","slime","341","egg","344","glowstone","348","fish","349","bone","352","pumpkinseeds","361","melonseeds","362","beef","363","chicken","365","rottenflesh","367","enderpearl","368"}; for(int x = 0; x < itemNames.length; x = x + 2) { items.getString(itemNames[x], " "); } for (int x = 1; x < itemNames.length; x = x + 2) { items.getInt(itemNames[x-1] + ".number", Integer.parseInt(itemNames[x])); } for (int x = 0; x < itemNames.length; x = x + 2) { items.getDouble(itemNames[x] + ".value", 10); } for (int x =0; x < itemNames.length; x = x + 2) { items.getDouble(itemNames[x] + ".minValue", MINVALUE.doubleValue()); } for (int x =0; x < itemNames.length; x = x + 2) { items.getDouble(itemNames[x] + ".maxValue", MAXVALUE.doubleValue()); } items.save(); } /** * Determine the cost of a given number of an item and calculate a new value for the item accordingly. * @param oper 1 for buying, 0 for selling. * @param item the item in question * @param amount the desired amount of the item in question * @return the total cost and the calculated new value as an Invoice */ public Invoice generateInvoice(int oper, String item, int amount) { items.load(); // get the initial value of the item, 0 for not found Invoice inv = new Invoice(BigDecimal.valueOf(0),BigDecimal.valueOf(0)); inv.value = BigDecimal.valueOf(items.getDouble(item + ".value", 0)); // determine the total cost inv.total = BigDecimal.valueOf(0); for(int x = 1; x <= amount; x++) { BigDecimal minValue = BigDecimal.valueOf(items.getDouble(item + ".minValue", .01)); if(inv.getValue().compareTo(minValue) == 1 | inv.getValue().compareTo(minValue) == 0) { inv.total = inv.getTotal().add(inv.getValue()); } else { inv.total = inv.getTotal().add(minValue); } if (oper == 1) { inv.value = inv.getValue().add(minValue); } else if (oper == 0) { inv.value = inv.getValue().subtract(minValue); } else { return null; } } return inv; } /** * Buy a specified amount of an item for the player. * * @param player The player on behalf of which these actions will be carried out. * @param item The desired item in the form of the item name. * @param amount The desired amount of the item to purchase. * @return true on success, false on failure. */ public boolean buy (Player player, String item, int amount) { // Be sure we have a positive amount if (amount < 0) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("No negative numbers, please."); return false; } items.load(); int id = items.getInt(item + ".number", 0); // a value of 0 would indicate that we did not find an item with that name if(id != 0) { // determine what it will cost Invoice invoice = generateInvoice(1, item, amount); MethodAccount cash = Methods.getMethod().getAccount(player.getName()); if(cash.hasEnough(invoice.getTotal().doubleValue())) { ItemStack its = new ItemStack(id,amount); player.getInventory().addItem(its); items.setProperty(item + ".value", invoice.getValue()); items.save(); // Give some nice output. player.sendMessage(ChatColor.GREEN + "Old Balance: " + ChatColor.WHITE + BigDecimal.valueOf(cash.balance()).setScale(2, RoundingMode.HALF_UP)); // Subtract the invoice (this is an efficient place to do this) cash.subtract(invoice.getTotal().doubleValue()); player.sendMessage(ChatColor.GREEN + "Cost: " + ChatColor.WHITE + invoice.getTotal()); player.sendMessage(ChatColor.GREEN + "New Balance: " + ChatColor.WHITE + BigDecimal.valueOf(cash.balance()).setScale(2, RoundingMode.HALF_UP)); return true; }else{ // Otherwise, give nice output anyway ;) // The idea here is to show how much more money is needed. BigDecimal difference = BigDecimal.valueOf(cash.balance() - invoice.getTotal().doubleValue()).setScale(2, RoundingMode.HALF_UP); player.sendMessage(ChatColor.RED + "You don't have enough money"); player.sendMessage(ChatColor.GREEN + "Balance: " + ChatColor.WHITE + BigDecimal.valueOf(cash.balance()).setScale(2, RoundingMode.HALF_UP)); player.sendMessage(ChatColor.GREEN + "Cost: " + ChatColor.WHITE + invoice.getTotal()); player.sendMessage(ChatColor.GREEN + "Difference: " + ChatColor.RED + difference); return false; } }else{ player.sendMessage(ChatColor.RED + "Not allowed to buy that item."); player.sendMessage("Be sure you typed the correct name"); return false; } } /** * Figure out how much of a given item is in the player's inventory * @param player The player entity in question. * @param id The Data Value of the item in question. * @return The amount of the item in the player's inventory as an integer. */ public int getAmountInInventory(Player player, int id) { int inInventory = 0; for (ItemStack slot : player.getInventory().all(id).values()) { inInventory += slot.getAmount(); } return inInventory; } /** * Sell a specified amount of an item for the player. * * @param player The player on behalf of which these actions will be carried out. * @param item The desired item in the form of the item name. * @param amount The desired amount of the item to sell. * @return true on success, false on failure. */ public boolean sell (Player player, String item, int amount) { // Be sure we have a positive amount if (amount < 0) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("No negative numbers, please."); return false; } items.load(); int id = items.getInt(item + ".number", 0); // a value of 0 would indicate that we did not find an item with that name if(id != 0) { // determine what it will pay Invoice invoice = generateInvoice(0, item, amount); MethodAccount cash = Methods.getMethod().getAccount(player.getName()); // If the player has enough of the item, perform the transaction. if (player.getInventory().contains(id, amount)) { // Figure out how much is left over. int left = getAmountInInventory(player,id) - amount; // Take out all of the item player.getInventory().remove(id); // put back what was left over if(left > 0) { ItemStack its = new ItemStack(id,left); player.getInventory().addItem(its); } items.setProperty(item + ".value", invoice.getValue()); // record the change in value items.save(); // give some nice output player.sendMessage(ChatColor.GREEN + "Old Balance: " + ChatColor.WHITE + BigDecimal.valueOf(cash.balance()).setScale(2, RoundingMode.HALF_UP)); cash.add(invoice.getTotal().doubleValue()); player.sendMessage(ChatColor.GREEN + "Sale: " + ChatColor.WHITE + invoice.total); player.sendMessage(ChatColor.GREEN + "New Balance: " + ChatColor.WHITE + BigDecimal.valueOf(cash.balance()).setScale(2, RoundingMode.HALF_UP)); return true; }else{ // give nice output even if they gave a bad number. player.sendMessage(ChatColor.RED + "You don't have enough " + item); player.sendMessage(ChatColor.GREEN + "In Inventory: " + ChatColor.WHITE + getAmountInInventory(player, id)); player.sendMessage(ChatColor.GREEN + "Attempted Amount: " + ChatColor.WHITE + amount); return false; } }else{ player.sendMessage(ChatColor.RED + "Not allowed to buy that item."); player.sendMessage("Be sure you typed the correct name"); return false; } } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { return readCommand((Player) sender, commandLabel, args); } public boolean readCommand(Player player, String command, String[] args) { if(command.equalsIgnoreCase("buy")) { if(args.length == 2) { String item = args[0]; int amount = 0; try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("Be sure you typed a whole number."); return false; } return buy(player, item, amount); } else { player.sendMessage("Invalid number of arguments"); return false; } } else if (command.equalsIgnoreCase("sell")) { if (args.length == 1) { if (args[0].equalsIgnoreCase("all")) { return sellAll(player); } } else if (args.length == 2) { String item = args[0]; int amount = 0; try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("Be sure you typed a whole number."); return false; } return sell(player, item, amount); } else { player.sendMessage("Invalid number of arguments"); return false; } // Command Example: /price cobblestone // should return: cobblestone: .01 }else if(command.equalsIgnoreCase("price")){ // We expect one argument if(args.length == 1){ // Load the item list items.load(); // get the price of the given item, if it's an invalid item set our variable to -2000000000 (an unlikely number to receive 'naturally') - double price = items.getDouble(args[0] + ".value", -2000000000); - if(price != -2000000000) { + BigDecimal price = BigDecimal.valueOf(items.getDouble(args[0] + ".value", -2000000000)); + BigDecimal minValue = BigDecimal.valueOf(items.getDouble(args[0] + ".minValue", MINVALUE.doubleValue())); + if(price.intValue() != -2000000000) { // We received an argument which resolved to an item on our list. // The price could register as a negative or below .01 // in this case we should return .01 as the price. - if(price < .01) { - price = .01; + if(price.compareTo(minValue) == -1) { + price = minValue; } player.sendMessage(ChatColor.GREEN + args[0] + ": " + ChatColor.WHITE + price); return true; }else{ // We received an argument which did not resolve to a known item. player.sendMessage(ChatColor.RED + "Be sure you typed the correct name"); player.sendMessage(args[0] + ChatColor.RED + " is invalid"); return false; } }else{ // We received too many or too few arguments. player.sendMessage("Invalid Arguments"); return false; } // Example: '/market top' should return the top 5 most expensive items on the market // '/market bottom' should do the dame for the least expensive items. }else if(command.equalsIgnoreCase("market")) { // we expect one argument if(args.length == 1) { // We received '/market top' if(args[0].equalsIgnoreCase("top")) { // load the item list items.load(); // make 'arrays', a name, a price List<String> names = items.getKeys(); String board[][] = new String[names.size()][2]; for(int x = 0; x < names.size(); x++) { // names board[x][1] = names.get(x); // prices board[x][0] = String.valueOf(items.getDouble(names.get(x) + ".value", -200000000)); } //sort 'em Arrays.sort(board, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { final BigDecimal value1 = BigDecimal.valueOf(Double.valueOf(entry1[0])); final BigDecimal value2 = BigDecimal.valueOf(Double.valueOf(entry2[0])); return value2.compareTo(value1); } }); // Send them to the player for(int x = 0; x < 10; x++) { player.sendMessage(board[x][0] + " " + board[x][1]); } return true; }else if(args[0].equalsIgnoreCase("bottom")) { // load the item list items.load(); // make 'arrays', a name, a price List<String> names = items.getKeys(); String board[][] = new String[names.size()][2]; for(int x = 0; x < names.size(); x++) { // names board[x][1] = names.get(x); // prices board[x][0] = String.valueOf(items.getDouble(names.get(x) + ".value", -200000000)); } //sort 'em Arrays.sort(board, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { final BigDecimal value1 = BigDecimal.valueOf(Double.valueOf(entry1[0])); final BigDecimal value2 = BigDecimal.valueOf(Double.valueOf(entry2[0])); return value1.compareTo(value2); } }); // Send them to the player for(int x = 0; x < 10; x++) { player.sendMessage(board[x][0] + " " + board[x][1]); } return true; } } player.sendMessage("Invalid number of arguments"); } return false; } private boolean sellAll(Player player) { items.load(); List<String> names = items.getKeys(); int[] id = new int[names.size()]; BigDecimal[] value = new BigDecimal[names.size()]; BigDecimal sale = BigDecimal.ZERO.setScale(2); // make a 'list' of all sellable items with their id's and values for (int x = 0; x < names.size(); x++) { id[x] = items.getInt(names.get(x) + ".number", 0); value[x] = BigDecimal.valueOf(items.getDouble(names.get(x) + ".value", 0)).setScale(2, RoundingMode.HALF_UP); } // run thru each slot and sell any sellable items for (int index = 0; index < 35; index++) { ItemStack slot = player.getInventory().getItem(index); int slotId = slot.getTypeId(); BigDecimal slotAmount = new BigDecimal(slot.getAmount()).setScale(0, RoundingMode.HALF_UP); for (int x = 0; x < names.size(); x++) { if (id[x] == slotId) { // perform sale of this slot Invoice thisSale = generateInvoice(0, names.get(x), slotAmount.intValue()); // rack up our total sale = sale.add(thisSale.getTotal()); // save the new value items.setProperty(names.get(x) + ".value", thisSale.getValue()); items.save(); // remove the item(s) player.getInventory().removeItem(slot); // "pay the man" MethodAccount cash = Methods.getMethod().getAccount(player.getName()); cash.add(thisSale.getTotal().doubleValue()); // give nice output player.sendMessage(ChatColor.GREEN + "Sold " + ChatColor.WHITE + slotAmount + " " + ChatColor.GRAY + names.get(x) + ChatColor.GREEN + " for " + ChatColor.WHITE + thisSale.getTotal()); } } } // give a nice total collumn if (sale == BigDecimal.ZERO.setScale(2)) player.sendMessage("Nothing to Sell"); player.sendMessage(ChatColor.GREEN + "--------------------------------"); player.sendMessage(ChatColor.GREEN + "Total Sale: " + ChatColor.WHITE + sale); return true; } public static double round2(double num) { double result = num * 100; result = Math.round(result); result = result / 100; return result; } }
false
true
public boolean readCommand(Player player, String command, String[] args) { if(command.equalsIgnoreCase("buy")) { if(args.length == 2) { String item = args[0]; int amount = 0; try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("Be sure you typed a whole number."); return false; } return buy(player, item, amount); } else { player.sendMessage("Invalid number of arguments"); return false; } } else if (command.equalsIgnoreCase("sell")) { if (args.length == 1) { if (args[0].equalsIgnoreCase("all")) { return sellAll(player); } } else if (args.length == 2) { String item = args[0]; int amount = 0; try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("Be sure you typed a whole number."); return false; } return sell(player, item, amount); } else { player.sendMessage("Invalid number of arguments"); return false; } // Command Example: /price cobblestone // should return: cobblestone: .01 }else if(command.equalsIgnoreCase("price")){ // We expect one argument if(args.length == 1){ // Load the item list items.load(); // get the price of the given item, if it's an invalid item set our variable to -2000000000 (an unlikely number to receive 'naturally') double price = items.getDouble(args[0] + ".value", -2000000000); if(price != -2000000000) { // We received an argument which resolved to an item on our list. // The price could register as a negative or below .01 // in this case we should return .01 as the price. if(price < .01) { price = .01; } player.sendMessage(ChatColor.GREEN + args[0] + ": " + ChatColor.WHITE + price); return true; }else{ // We received an argument which did not resolve to a known item. player.sendMessage(ChatColor.RED + "Be sure you typed the correct name"); player.sendMessage(args[0] + ChatColor.RED + " is invalid"); return false; } }else{ // We received too many or too few arguments. player.sendMessage("Invalid Arguments"); return false; } // Example: '/market top' should return the top 5 most expensive items on the market // '/market bottom' should do the dame for the least expensive items. }else if(command.equalsIgnoreCase("market")) { // we expect one argument if(args.length == 1) { // We received '/market top' if(args[0].equalsIgnoreCase("top")) { // load the item list items.load(); // make 'arrays', a name, a price List<String> names = items.getKeys(); String board[][] = new String[names.size()][2]; for(int x = 0; x < names.size(); x++) { // names board[x][1] = names.get(x); // prices board[x][0] = String.valueOf(items.getDouble(names.get(x) + ".value", -200000000)); } //sort 'em Arrays.sort(board, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { final BigDecimal value1 = BigDecimal.valueOf(Double.valueOf(entry1[0])); final BigDecimal value2 = BigDecimal.valueOf(Double.valueOf(entry2[0])); return value2.compareTo(value1); } }); // Send them to the player for(int x = 0; x < 10; x++) { player.sendMessage(board[x][0] + " " + board[x][1]); } return true; }else if(args[0].equalsIgnoreCase("bottom")) { // load the item list items.load(); // make 'arrays', a name, a price List<String> names = items.getKeys(); String board[][] = new String[names.size()][2]; for(int x = 0; x < names.size(); x++) { // names board[x][1] = names.get(x); // prices board[x][0] = String.valueOf(items.getDouble(names.get(x) + ".value", -200000000)); } //sort 'em Arrays.sort(board, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { final BigDecimal value1 = BigDecimal.valueOf(Double.valueOf(entry1[0])); final BigDecimal value2 = BigDecimal.valueOf(Double.valueOf(entry2[0])); return value1.compareTo(value2); } }); // Send them to the player for(int x = 0; x < 10; x++) { player.sendMessage(board[x][0] + " " + board[x][1]); } return true; } } player.sendMessage("Invalid number of arguments"); } return false; }
public boolean readCommand(Player player, String command, String[] args) { if(command.equalsIgnoreCase("buy")) { if(args.length == 2) { String item = args[0]; int amount = 0; try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("Be sure you typed a whole number."); return false; } return buy(player, item, amount); } else { player.sendMessage("Invalid number of arguments"); return false; } } else if (command.equalsIgnoreCase("sell")) { if (args.length == 1) { if (args[0].equalsIgnoreCase("all")) { return sellAll(player); } } else if (args.length == 2) { String item = args[0]; int amount = 0; try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "Invalid amount."); player.sendMessage("Be sure you typed a whole number."); return false; } return sell(player, item, amount); } else { player.sendMessage("Invalid number of arguments"); return false; } // Command Example: /price cobblestone // should return: cobblestone: .01 }else if(command.equalsIgnoreCase("price")){ // We expect one argument if(args.length == 1){ // Load the item list items.load(); // get the price of the given item, if it's an invalid item set our variable to -2000000000 (an unlikely number to receive 'naturally') BigDecimal price = BigDecimal.valueOf(items.getDouble(args[0] + ".value", -2000000000)); BigDecimal minValue = BigDecimal.valueOf(items.getDouble(args[0] + ".minValue", MINVALUE.doubleValue())); if(price.intValue() != -2000000000) { // We received an argument which resolved to an item on our list. // The price could register as a negative or below .01 // in this case we should return .01 as the price. if(price.compareTo(minValue) == -1) { price = minValue; } player.sendMessage(ChatColor.GREEN + args[0] + ": " + ChatColor.WHITE + price); return true; }else{ // We received an argument which did not resolve to a known item. player.sendMessage(ChatColor.RED + "Be sure you typed the correct name"); player.sendMessage(args[0] + ChatColor.RED + " is invalid"); return false; } }else{ // We received too many or too few arguments. player.sendMessage("Invalid Arguments"); return false; } // Example: '/market top' should return the top 5 most expensive items on the market // '/market bottom' should do the dame for the least expensive items. }else if(command.equalsIgnoreCase("market")) { // we expect one argument if(args.length == 1) { // We received '/market top' if(args[0].equalsIgnoreCase("top")) { // load the item list items.load(); // make 'arrays', a name, a price List<String> names = items.getKeys(); String board[][] = new String[names.size()][2]; for(int x = 0; x < names.size(); x++) { // names board[x][1] = names.get(x); // prices board[x][0] = String.valueOf(items.getDouble(names.get(x) + ".value", -200000000)); } //sort 'em Arrays.sort(board, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { final BigDecimal value1 = BigDecimal.valueOf(Double.valueOf(entry1[0])); final BigDecimal value2 = BigDecimal.valueOf(Double.valueOf(entry2[0])); return value2.compareTo(value1); } }); // Send them to the player for(int x = 0; x < 10; x++) { player.sendMessage(board[x][0] + " " + board[x][1]); } return true; }else if(args[0].equalsIgnoreCase("bottom")) { // load the item list items.load(); // make 'arrays', a name, a price List<String> names = items.getKeys(); String board[][] = new String[names.size()][2]; for(int x = 0; x < names.size(); x++) { // names board[x][1] = names.get(x); // prices board[x][0] = String.valueOf(items.getDouble(names.get(x) + ".value", -200000000)); } //sort 'em Arrays.sort(board, new Comparator<String[]>() { @Override public int compare(String[] entry1, String[] entry2) { final BigDecimal value1 = BigDecimal.valueOf(Double.valueOf(entry1[0])); final BigDecimal value2 = BigDecimal.valueOf(Double.valueOf(entry2[0])); return value1.compareTo(value2); } }); // Send them to the player for(int x = 0; x < 10; x++) { player.sendMessage(board[x][0] + " " + board[x][1]); } return true; } } player.sendMessage("Invalid number of arguments"); } return false; }
diff --git a/FullBlockTestGenerator.java b/FullBlockTestGenerator.java index 43bc5d4..fb539bc 100644 --- a/FullBlockTestGenerator.java +++ b/FullBlockTestGenerator.java @@ -1,1709 +1,1712 @@ package com.google.bitcoin.core; import com.google.bitcoin.core.Transaction.SigHash; import com.google.bitcoin.script.Script; import com.google.bitcoin.script.ScriptBuilder; import com.google.common.base.Preconditions; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.*; import static com.google.bitcoin.script.ScriptOpCodes.*; /** * Represents a block which is sent to the tested application and which the application must either reject or accept, * depending on the flags in the rule */ class BlockAndValidity extends Rule { Block block; Sha256Hash blockHash; boolean connects; boolean throwsException; Sha256Hash hashChainTipAfterBlock; int heightAfterBlock; public BlockAndValidity(Map<Sha256Hash, Integer> blockToHeightMap, Map<Sha256Hash, Block> hashHeaderMap, Block block, boolean connects, boolean throwsException, Sha256Hash hashChainTipAfterBlock, int heightAfterBlock, String blockName) { super(blockName); if (connects && throwsException) throw new RuntimeException("A block cannot connect if an exception was thrown while adding it."); this.block = block; this.blockHash = block.getHash(); this.connects = connects; this.throwsException = throwsException; this.hashChainTipAfterBlock = hashChainTipAfterBlock; this.heightAfterBlock = heightAfterBlock; // Keep track of the set of blocks indexed by hash hashHeaderMap.put(block.getHash(), block.cloneAsHeader()); // Double-check that we are always marking any given block at the same height Integer height = blockToHeightMap.get(hashChainTipAfterBlock); if (height != null) Preconditions.checkState(height == heightAfterBlock); else blockToHeightMap.put(hashChainTipAfterBlock, heightAfterBlock); } } /** * A test which checks the mempool state (ie defined which transactions should be in memory pool */ class MemoryPoolState extends Rule { Set<InventoryItem> mempool; public MemoryPoolState(Set<InventoryItem> mempool, String ruleName) { super(ruleName); this.mempool = mempool; } } /** An arbitrary rule which the testing client must match */ class Rule { String ruleName; Rule(String ruleName) { this.ruleName = ruleName; } } class TransactionOutPointWithValue { public TransactionOutPoint outpoint; public BigInteger value; Script scriptPubKey; public TransactionOutPointWithValue(TransactionOutPoint outpoint, BigInteger value, Script scriptPubKey) { this.outpoint = outpoint; this.value = value; this.scriptPubKey = scriptPubKey; } } class RuleList { public List<Rule> list; public int maximumReorgBlockCount; Map<Sha256Hash, Block> hashHeaderMap; public RuleList(List<Rule> list, Map<Sha256Hash, Block> hashHeaderMap, int maximumReorgBlockCount) { this.list = list; this.hashHeaderMap = hashHeaderMap; this.maximumReorgBlockCount = maximumReorgBlockCount; } } public class FullBlockTestGenerator { // Used by BitcoindComparisonTool and FullPrunedBlockChainTest to create test cases private NetworkParameters params; private ECKey coinbaseOutKey; private byte[] coinbaseOutKeyPubKey; // Used to double-check that we are always using the right next-height private Map<Sha256Hash, Integer> blockToHeightMap = new HashMap<Sha256Hash, Integer>(); private Map<Sha256Hash, Block> hashHeaderMap = new HashMap<Sha256Hash, Block>(); public FullBlockTestGenerator(NetworkParameters params) { this.params = params; coinbaseOutKey = new ECKey(); coinbaseOutKeyPubKey = coinbaseOutKey.getPubKey(); Utils.rollMockClock(0); // Set a mock clock for timestamp tests } public RuleList getBlocksToTest(boolean addSigExpensiveBlocks, boolean runLargeReorgs, File blockStorageFile) throws ScriptException, ProtocolException, IOException { final FileOutputStream outStream = blockStorageFile != null ? new FileOutputStream(blockStorageFile) : null; List<Rule> blocks = new LinkedList<Rule>() { @Override public boolean add(Rule element) { if (outStream != null && element instanceof BlockAndValidity) { try { outStream.write((int) (params.getPacketMagic() >>> 24)); outStream.write((int) (params.getPacketMagic() >>> 16)); outStream.write((int) (params.getPacketMagic() >>> 8)); outStream.write((int) (params.getPacketMagic() >>> 0)); byte[] block = ((BlockAndValidity)element).block.bitcoinSerialize(); byte[] length = new byte[4]; Utils.uint32ToByteArrayBE(block.length, length, 0); outStream.write(Utils.reverseBytes(length)); outStream.write(block); ((BlockAndValidity)element).block = null; } catch (IOException e) { throw new RuntimeException(e); } } return super.add(element); } }; RuleList ret = new RuleList(blocks, hashHeaderMap, 10); Queue<TransactionOutPointWithValue> spendableOutputs = new LinkedList<TransactionOutPointWithValue>(); int chainHeadHeight = 1; Block chainHead = params.getGenesisBlock().createNextBlockWithCoinbase(coinbaseOutKeyPubKey); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, chainHead, true, false, chainHead.getHash(), 1, "Initial Block")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, chainHead.getTransactions().get(0).getHash()), Utils.toNanoCoins(50, 0), chainHead.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) { chainHead = chainHead.createNextBlockWithCoinbase(coinbaseOutKeyPubKey); chainHeadHeight++; blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, chainHead, true, false, chainHead.getHash(), i+1, "Initial Block chain output generation")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, chainHead.getTransactions().get(0).getHash()), Utils.toNanoCoins(50, 0), chainHead.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); } // Start by building a couple of blocks on top of the genesis block. Block b1 = createNextBlock(chainHead, chainHeadHeight + 1, spendableOutputs.poll(), null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1, true, false, b1.getHash(), chainHeadHeight + 1, "b1")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b1.getTransactions().get(0).getHash()), b1.getTransactions().get(0).getOutputs().get(0).getValue(), b1.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out1 = spendableOutputs.poll(); Preconditions.checkState(out1 != null); Block b2 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); // Make sure nothing funky happens if we try to re-add b2 blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b2.getTransactions().get(0).getHash()), b2.getTransactions().get(0).getOutputs().get(0).getValue(), b2.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // We now have the following chain (which output is spent is in parentheses): // genesis -> b1 (0) -> b2 (1) // // so fork like this: // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) // // Nothing should happen at this point. We saw b2 first so it takes priority. Block b3 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Make sure nothing breaks if we add b3 twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Now we add another block to make the alternative chain longer. TransactionOutPointWithValue out2 = spendableOutputs.poll(); Preconditions.checkState(out2 != null); Block b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b4, true, false, b4.getHash(), chainHeadHeight + 3, "b4")); // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) -> b4 (2) // // ... and back to the first chain. Block b5 = createNextBlock(b2, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b5, true, false, b4.getHash(), chainHeadHeight + 3, "b5")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b5.getTransactions().get(0).getHash()), b5.getTransactions().get(0).getOutputs().get(0).getValue(), b5.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out3 = spendableOutputs.poll(); Block b6 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b6, true, false, b6.getHash(), chainHeadHeight + 4, "b6")); // // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b3 (1) -> b4 (2) // // Try to create a fork that double-spends // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b7 (2) -> b8 (4) // \-> b3 (1) -> b4 (2) // Block b7 = createNextBlock(b5, chainHeadHeight + 5, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b7, true, false, b6.getHash(), chainHeadHeight + 4, "b7")); TransactionOutPointWithValue out4 = spendableOutputs.poll(); Block b8 = createNextBlock(b7, chainHeadHeight + 6, out4, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b8, false, true, b6.getHash(), chainHeadHeight + 4, "b8")); // Try to create a block that has too much fee // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b9 (4) // \-> b3 (1) -> b4 (2) // Block b9 = createNextBlock(b6, chainHeadHeight + 5, out4, BigInteger.valueOf(1)); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b9, false, true, b6.getHash(), chainHeadHeight + 4, "b9")); // Create a fork that ends in a block with too much fee (the one that causes the reorg) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b10 (3) -> b11 (4) // \-> b3 (1) -> b4 (2) // Block b10 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b10, true, false, b6.getHash(), chainHeadHeight + 4, "b10")); Block b11 = createNextBlock(b10, chainHeadHeight + 5, out4, BigInteger.valueOf(1)); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b11, false, true, b6.getHash(), chainHeadHeight + 4, "b11")); // Try again, but with a valid fork first // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b14 (5) // (b12 added last) // \-> b3 (1) -> b4 (2) // Block b12 = createNextBlock(b5, chainHeadHeight + 4, out3, null); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b12.getTransactions().get(0).getHash()), b12.getTransactions().get(0).getOutputs().get(0).getValue(), b12.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b13 = createNextBlock(b12, chainHeadHeight + 5, out4, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); // Make sure we dont die if an orphan gets added twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b13.getTransactions().get(0).getHash()), b13.getTransactions().get(0).getOutputs().get(0).getValue(), b13.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out5 = spendableOutputs.poll(); Block b14 = createNextBlock(b13, chainHeadHeight + 6, out5, BigInteger.valueOf(1)); // This will be "validly" added, though its actually invalid, it will just be marked orphan // and will be discarded when an attempt is made to reorg to it. // TODO: Use a WeakReference to check that it is freed properly after the reorg blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); // Make sure we dont die if an orphan gets added twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b12, false, true, b13.getHash(), chainHeadHeight + 5, "b12")); // Add a block with MAX_BLOCK_SIGOPS and one with one more sigop // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6) // \-> b3 (1) -> b4 (2) // Block b15 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { int sigOps = 0; for (Transaction tx : b15.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b15.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b15.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b15.addTransaction(tx); } b15.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b15, true, false, b15.getHash(), chainHeadHeight + 6, "b15")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b15.getTransactions().get(0).getHash()), b15.getTransactions().get(0).getOutputs().get(0).getValue(), b15.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out6 = spendableOutputs.poll(); Block b16 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { int sigOps = 0; for (Transaction tx : b16.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b16.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b16.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b16.addTransaction(tx); } b16.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b16, false, true, b15.getHash(), chainHeadHeight + 6, "b16")); // Attempt to spend a transaction created on a different fork // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (6) // \-> b3 (1) -> b4 (2) // Block b17 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b3.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b3.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b17.addTransaction(tx); } b17.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b17, false, true, b15.getHash(), chainHeadHeight + 6, "b17")); // Attempt to spend a transaction created on a different fork (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b18 (5) -> b19 (6) // \-> b3 (1) -> b4 (2) // Block b18 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b3.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b3.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b18.addTransaction(tx); } b18.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b18, true, false, b15.getHash(), chainHeadHeight + 6, "b17")); Block b19 = createNextBlock(b18, chainHeadHeight + 7, out6, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b19, false, true, b15.getHash(), chainHeadHeight + 6, "b19")); // Attempt to spend a coinbase at depth too low // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7) // \-> b3 (1) -> b4 (2) // TransactionOutPointWithValue out7 = spendableOutputs.poll(); Block b20 = createNextBlock(b15, chainHeadHeight + 7, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b20, false, true, b15.getHash(), chainHeadHeight + 6, "b20")); // Attempt to spend a coinbase at depth too low (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b21 (6) -> b22 (5) // \-> b3 (1) -> b4 (2) // Block b21 = createNextBlock(b13, chainHeadHeight + 6, out6, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b21, true, false, b15.getHash(), chainHeadHeight + 6, "b21")); Block b22 = createNextBlock(b21, chainHeadHeight + 7, out5, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b22, false, true, b15.getHash(), chainHeadHeight + 6, "b22")); // Create a block on either side of MAX_BLOCK_SIZE and make sure its accepted/rejected // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) // \-> b24 (6) -> b25 (7) // \-> b3 (1) -> b4 (2) // Block b23 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b23.getMessageSize() - 138]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b23.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b23.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b23.addTransaction(tx); } b23.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b23, true, false, b23.getHash(), chainHeadHeight + 7, "b23")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b23.getTransactions().get(0).getHash()), b23.getTransactions().get(0).getOutputs().get(0).getValue(), b23.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b24 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b24.getMessageSize() - 135]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b24.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b24.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b24.addTransaction(tx); } b24.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b24, false, true, b23.getHash(), chainHeadHeight + 7, "b24")); // Extend the b24 chain to make sure bitcoind isn't accepting b24 Block b25 = createNextBlock(b24, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b25, false, false, b23.getHash(), chainHeadHeight + 7, "b25")); // Create blocks with a coinbase input script size out of range // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) // \-> ... (6) -> ... (7) // \-> b3 (1) -> b4 (2) // Block b26 = createNextBlock(b15, chainHeadHeight + 7, out6, null); // 1 is too small, but we already generate every other block with 2, so that is tested b26.getTransactions().get(0).getInputs().get(0).setScriptBytes(new byte[] {0}); b26.setMerkleRoot(null); b26.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b26, false, true, b23.getHash(), chainHeadHeight + 7, "b26")); // Extend the b26 chain to make sure bitcoind isn't accepting b26 Block b27 = createNextBlock(b26, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b27, false, false, b23.getHash(), chainHeadHeight + 7, "b27")); Block b28 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { byte[] coinbase = new byte[101]; Arrays.fill(coinbase, (byte)0); b28.getTransactions().get(0).getInputs().get(0).setScriptBytes(coinbase); } b28.setMerkleRoot(null); b28.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b28, false, true, b23.getHash(), chainHeadHeight + 7, "b28")); // Extend the b28 chain to make sure bitcoind isn't accepting b28 Block b29 = createNextBlock(b28, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b29, false, false, b23.getHash(), chainHeadHeight + 7, "b29")); Block b30 = createNextBlock(b23, chainHeadHeight + 8, out7, null); { byte[] coinbase = new byte[100]; Arrays.fill(coinbase, (byte)0); b30.getTransactions().get(0).getInputs().get(0).setScriptBytes(coinbase); } b30.setMerkleRoot(null); b30.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b30, true, false, b30.getHash(), chainHeadHeight + 8, "b30")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b30.getTransactions().get(0).getHash()), b30.getTransactions().get(0).getOutputs().get(0).getValue(), b30.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Check sigops of OP_CHECKMULTISIG/OP_CHECKMULTISIGVERIFY/OP_CHECKSIGVERIFY // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b36 (11) // \-> b34 (10) // \-> b32 (9) // TransactionOutPointWithValue out8 = spendableOutputs.poll(); Block b31 = createNextBlock(b30, chainHeadHeight + 9, out8, null); { int sigOps = 0; for (Transaction tx : b31.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b31.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b31.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b31.addTransaction(tx); } b31.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b31, true, false, b31.getHash(), chainHeadHeight + 9, "b31")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b31.getTransactions().get(0).getHash()), b31.getTransactions().get(0).getOutputs().get(0).getValue(), b31.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out9 = spendableOutputs.poll(); Block b32 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b32.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b32.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b32.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b32.addTransaction(tx); } b32.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b32, false, true, b31.getHash(), chainHeadHeight + 9, "b32")); Block b33 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b33.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b33.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b33.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b33.addTransaction(tx); } b33.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b33, true, false, b33.getHash(), chainHeadHeight + 10, "b33")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b33.getTransactions().get(0).getHash()), b33.getTransactions().get(0).getOutputs().get(0).getValue(), b33.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out10 = spendableOutputs.poll(); Block b34 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b34.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b34.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b34.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b34.addTransaction(tx); } b34.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b34, false, true, b33.getHash(), chainHeadHeight + 10, "b34")); Block b35 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b35.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b35.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b35.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b35.addTransaction(tx); } b35.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b35, true, false, b35.getHash(), chainHeadHeight + 11, "b35")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b35.getTransactions().get(0).getHash()), b35.getTransactions().get(0).getOutputs().get(0).getValue(), b35.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out11 = spendableOutputs.poll(); Block b36 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { int sigOps = 0; for (Transaction tx : b36.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b36.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b36.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b36.addTransaction(tx); } b36.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b36, false, true, b35.getHash(), chainHeadHeight + 11, "b36")); // Check spending of a transaction in a block which failed to connect // (test block store transaction abort handling, not that it should get this far if that's broken...) // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b37 (11) // \-> b38 (11) // Block b37 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, out11); // double spend out11 b37.addTransaction(tx); } b37.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b37, false, true, b35.getHash(), chainHeadHeight + 11, "b37")); Block b38 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); // Attempt to spend b37's first non-coinbase tx, at which point b37 was still considered valid addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b37.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b37.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b38.addTransaction(tx); } b38.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b38, false, true, b35.getHash(), chainHeadHeight + 11, "b38")); // Check P2SH SigOp counting // 13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b41 (12) // \-> b40 (12) // // Create some P2SH outputs that will require 6 sigops to spend byte[] b39p2shScriptPubKey; int b39numP2SHOutputs = 0, b39sigOpsPerOutput = 6; Block b39 = createNextBlock(b35, chainHeadHeight + 12, null, null); { ByteArrayOutputStream p2shScriptPubKey = new UnsafeByteArrayOutputStream(); try { Script.writeBytes(p2shScriptPubKey, coinbaseOutKeyPubKey); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_CHECKSIG); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } b39p2shScriptPubKey = p2shScriptPubKey.toByteArray(); byte[] scriptHash = Utils.sha256hash160(b39p2shScriptPubKey); UnsafeByteArrayOutputStream scriptPubKey = new UnsafeByteArrayOutputStream(scriptHash.length + 3); scriptPubKey.write(OP_HASH160); try { Script.writeBytes(scriptPubKey, scriptHash); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } scriptPubKey.write(OP_EQUAL); BigInteger lastOutputValue = out11.value.subtract(BigInteger.valueOf(1)); TransactionOutPoint lastOutPoint; { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(params, tx, lastOutputValue, new byte[]{OP_1})); addOnlyInputToTransaction(tx, out11); lastOutPoint = new TransactionOutPoint(params, 1, tx.getHash()); b39.addTransaction(tx); } b39numP2SHOutputs++; while (b39.getMessageSize() < Block.MAX_BLOCK_SIZE) { Transaction tx = new Transaction(params); lastOutputValue = lastOutputValue.subtract(BigInteger.valueOf(1)); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(params, tx, lastOutputValue, new byte[]{OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); lastOutPoint = new TransactionOutPoint(params, 1, tx.getHash()); if (b39.getMessageSize() + tx.getMessageSize() < Block.MAX_BLOCK_SIZE) { b39.addTransaction(tx); b39numP2SHOutputs++; } else break; } } b39.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b39, true, false, b39.getHash(), chainHeadHeight + 12, "b39")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b39.getTransactions().get(0).getHash()), b39.getTransactions().get(0).getOutputs().get(0).getValue(), b39.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out12 = spendableOutputs.poll(); Block b40 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b40.transactions) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; Preconditions.checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint(params, 2, b40.getTransactions().get(1).getHash()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(params, tx, new byte[]{}, new TransactionOutPoint(params, 0, b39.getTransactions().get(i).getHash())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.ordinal() + 1); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new UnsafeByteArrayOutputStream(signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] {(byte) OP_CHECKSIG}); scriptSigBos.write(Script.createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(params, 0, tx.getHash()); b40.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, scriptPubKey)); b40.addTransaction(tx); } b40.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b40, false, true, b39.getHash(), chainHeadHeight + 12, "b40")); Block b41 = null; if (addSigExpensiveBlocks) { b41 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b41.transactions) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; Preconditions.checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint( params, 2, b41.getTransactions().get(1).getHash()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger .valueOf(1), new byte[] {OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(params, tx, new byte[] {}, new TransactionOutPoint(params, 0, b39.getTransactions().get(i).getHash())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream( 73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.ordinal() + 1); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new UnsafeByteArrayOutputStream( signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] { (byte) OP_CHECKSIG}); scriptSigBos.write(Script .createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(params, 0, tx.getHash()); b41.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, scriptPubKey)); b41.addTransaction(tx); } b41.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b41, true, false, b41.getHash(), chainHeadHeight + 13, "b41")); } // Fork off of b39 to create a constant base again // b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) // \-> b41 (12) // Block b42 = createNextBlock(b39, chainHeadHeight + 13, out12, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b42, true, false, b41 == null ? b42.getHash() : b41.getHash(), chainHeadHeight + 13, "b42")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b42.getTransactions().get(0).getHash()), b42.getTransactions().get(0).getOutputs().get(0).getValue(), b42.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out13 = spendableOutputs.poll(); Block b43 = createNextBlock(b42, chainHeadHeight + 14, out13, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b43, true, false, b43.getHash(), chainHeadHeight + 14, "b43")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b43.getTransactions().get(0).getHash()), b43.getTransactions().get(0).getOutputs().get(0).getValue(), b43.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test a number of really invalid scenarios // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b44 (14) // \-> ??? (15) // TransactionOutPointWithValue out14 = spendableOutputs.poll(); // A valid block created exactly like b44 to make sure the creation itself works Block b44 = new Block(params); byte[] outScriptBytes = ScriptBuilder.createOutputScript(new ECKey(null, coinbaseOutKeyPubKey)).getProgram(); { b44.setDifficultyTarget(b43.getDifficultyTarget()); b44.addCoinbaseTransaction(coinbaseOutKeyPubKey, BigInteger.ZERO); Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out14); b44.addTransaction(t); b44.setPrevBlockHash(b43.getHash()); b44.setTime(b43.getTimeSeconds() + 1); } b44.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b44, true, false, b44.getHash(), chainHeadHeight + 15, "b44")); TransactionOutPointWithValue out15 = spendableOutputs.poll(); // A block with a non-coinbase as the first tx Block b45 = new Block(params); { b45.setDifficultyTarget(b44.getDifficultyTarget()); //b45.addCoinbaseTransaction(pubKey, coinbaseValue); Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out15); try { b45.addTransaction(t); } catch (RuntimeException e) { } // Should happen if (b45.getTransactions().size() > 0) throw new RuntimeException("addTransaction doesn't properly check for adding a non-coinbase as first tx"); b45.addTransaction(t, false); b45.setPrevBlockHash(b44.getHash()); b45.setTime(b44.getTimeSeconds() + 1); } b45.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b45, false, true, b44.getHash(), chainHeadHeight + 15, "b45")); // A block with no txn Block b46 = new Block(params); { b46.transactions = new ArrayList<Transaction>(); b46.setDifficultyTarget(b44.getDifficultyTarget()); b46.setMerkleRoot(Sha256Hash.ZERO_HASH); b46.setPrevBlockHash(b44.getHash()); b46.setTime(b44.getTimeSeconds() + 1); } b46.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b46, false, true, b44.getHash(), chainHeadHeight + 15, "b46")); // A block with invalid work Block b47 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { try { // Inverse solve BigInteger target = b47.getDifficultyTargetAsInteger(); while (true) { BigInteger h = b47.getHash().toBigInteger(); if (h.compareTo(target) > 0) // if invalid break; // increment the nonce and try again. b47.setNonce(b47.getNonce() + 1); } } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b47, false, true, b44.getHash(), chainHeadHeight + 15, "b47")); // Block with timestamp > 2h in the future Block b48 = createNextBlock(b44, chainHeadHeight + 16, out15, null); b48.setTime(Utils.now().getTime() / 1000 + 60*60*3); b48.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b48, false, true, b44.getHash(), chainHeadHeight + 15, "b48")); // Block with invalid merkle hash Block b49 = createNextBlock(b44, chainHeadHeight + 16, out15, null); - b49.setMerkleRoot(Sha256Hash.ZERO_HASH); + byte[] b49MerkleHash = Sha256Hash.ZERO_HASH.getBytes().clone(); + b49MerkleHash[1] = (byte) 0xDE; + b49.setMerkleRoot(Sha256Hash.create(b49MerkleHash)); b49.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b49, false, true, b44.getHash(), chainHeadHeight + 15, "b49")); // Block with incorrect POW limit Block b50 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { long diffTarget = b44.getDifficultyTarget(); diffTarget &= 0xFFBFFFFF; // Make difficulty one bit harder b50.setDifficultyTarget(diffTarget); } b50.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b50, false, true, b44.getHash(), chainHeadHeight + 15, "b50")); // A block with two coinbase txn Block b51 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction coinbase = new Transaction(params); coinbase.addInput(new TransactionInput(params, coinbase, new byte[]{(byte) 0xff, 110, 1})); coinbase.addOutput(new TransactionOutput(params, coinbase, BigInteger.ONE, outScriptBytes)); b51.addTransaction(coinbase, false); } b51.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b51, false, true, b44.getHash(), chainHeadHeight + 15, "b51")); // A block with duplicate txn Block b52 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b52.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b52.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b52.addTransaction(tx); b52.addTransaction(tx); } b52.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b52, false, true, b44.getHash(), chainHeadHeight + 15, "b52")); // Test block timestamp // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) // \-> b54 (15) // \-> b44 (14) // Block b53 = createNextBlock(b43, chainHeadHeight + 15, out14, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b53, true, false, b44.getHash(), chainHeadHeight + 15, "b53")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b53.getTransactions().get(0).getHash()), b53.getTransactions().get(0).getOutputs().get(0).getValue(), b53.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Block with invalid timestamp Block b54 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b54.setTime(b35.getTimeSeconds() - 1); b54.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b54, false, true, b44.getHash(), chainHeadHeight + 15, "b54")); // Block with valid timestamp Block b55 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b55.setTime(b35.getTimeSeconds()); b55.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b55, true, false, b55.getHash(), chainHeadHeight + 16, "b55")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b55.getTransactions().get(0).getHash()), b55.getTransactions().get(0).getOutputs().get(0).getValue(), b55.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test CVE-2012-2459 // -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) // \-> b56 (16) // TransactionOutPointWithValue out16 = spendableOutputs.poll(); Block b57 = createNextBlock(b55, chainHeadHeight + 17, out16, null); Transaction b56txToDuplicate; { b56txToDuplicate = new Transaction(params); b56txToDuplicate.addOutput(new TransactionOutput(params, b56txToDuplicate, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(b56txToDuplicate, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b57.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b57.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b57.addTransaction(b56txToDuplicate); } b57.solve(); Block b56; try { b56 = new Block(params, b57.bitcoinSerialize()); } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } b56.addTransaction(b56txToDuplicate); Preconditions.checkState(b56.getHash().equals(b57.getHash())); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b56, false, true, b55.getHash(), chainHeadHeight + 16, "b56")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b57, true, false, b57.getHash(), chainHeadHeight + 17, "b57")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b57.getTransactions().get(0).getHash()), b57.getTransactions().get(0).getOutputs().get(0).getValue(), b57.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test a few invalid tx types // -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> ??? (17) // TransactionOutPointWithValue out17 = spendableOutputs.poll(); // tx with prevout.n out of range Block b58 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] {})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, new TransactionOutPoint(params, 3, b58.getTransactions().get(1).getHash()))); b58.addTransaction(tx); } b58.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b58, false, true, b57.getHash(), chainHeadHeight + 17, "b58")); // tx with output value > input value out of range Block b59 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, b59.getTransactions().get(1).getOutputs().get(2).getValue().add(BigInteger.ONE), new byte[] {})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, new TransactionOutPoint(params, 2, b59.getTransactions().get(1).getHash()))); b59.addTransaction(tx); } b59.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b59, false, true, b57.getHash(), chainHeadHeight + 17, "b59")); Block b60 = createNextBlock(b57, chainHeadHeight + 18, out17, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b60, true, false, b60.getHash(), chainHeadHeight + 18, "b60")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b60.getTransactions().get(0).getHash()), b60.getTransactions().get(0).getOutputs().get(0).getValue(), b60.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test BIP30 // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b61 (18) // TransactionOutPointWithValue out18 = spendableOutputs.poll(); Block b61 = createNextBlock(b60, chainHeadHeight + 19, out18, null); { byte[] scriptBytes = b61.getTransactions().get(0).getInputs().get(0).getScriptBytes(); scriptBytes[0]--; // createNextBlock will increment the first script byte on each new block b61.getTransactions().get(0).getInputs().get(0).setScriptBytes(scriptBytes); b61.unCache(); Preconditions.checkState(b61.getTransactions().get(0).equals(b60.getTransactions().get(0))); } b61.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b61, false, true, b60.getHash(), chainHeadHeight + 18, "b61")); // Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b62 (18) // Block b62 = createNextBlock(b60, chainHeadHeight + 19, null, null); { Transaction tx = new Transaction(params); tx.setLockTime(0xffffffffL); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] {OP_TRUE})); addOnlyInputToTransaction(tx, out18, 0); b62.addTransaction(tx); Preconditions.checkState(!tx.isFinal(chainHeadHeight + 17, b62.getTimeSeconds())); } b62.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b62, false, true, b60.getHash(), chainHeadHeight + 18, "b62")); // Test a non-final coinbase is also rejected // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b63 (-) // Block b63 = createNextBlock(b60, chainHeadHeight + 19, null, null); { b63.getTransactions().get(0).setLockTime(0xffffffffL); b63.getTransactions().get(0).getInputs().get(0).setSequenceNumber(0xDEADBEEF); Preconditions.checkState(!b63.getTransactions().get(0).isFinal(chainHeadHeight + 17, b63.getTimeSeconds())); } b63.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b63, false, true, b60.getHash(), chainHeadHeight + 18, "b63")); // Check that a block which is (when properly encoded) <= MAX_BLOCK_SIZE is accepted // Even when it is encoded with varints that make its encoded size actually > MAX_BLOCK_SIZE // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) // Block b64; { Block b64Created = createNextBlock(b60, chainHeadHeight + 19, out18, null); Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b64Created.getMessageSize() - 138]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b64Created.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b64Created.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b64Created.addTransaction(tx); b64Created.solve(); UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(b64Created.getMessageSize() + 8); b64Created.writeHeader(stream); byte[] varIntBytes = new byte[9]; varIntBytes[0] = (byte) 255; Utils.uint32ToByteArrayLE((long)b64Created.getTransactions().size(), varIntBytes, 1); Utils.uint32ToByteArrayLE(((long)b64Created.getTransactions().size()) >>> 32, varIntBytes, 5); stream.write(varIntBytes); Preconditions.checkState(new VarInt(varIntBytes, 0).value == b64Created.getTransactions().size()); for (Transaction transaction : b64Created.getTransactions()) transaction.bitcoinSerialize(stream); b64 = new Block(params, stream.toByteArray(), false, true, stream.size()); // The following checks are checking to ensure block serialization functions in the way needed for this test // If they fail, it is likely not an indication of error, but an indication that this test needs rewritten Preconditions.checkState(stream.size() == b64Created.getMessageSize() + 8); Preconditions.checkState(stream.size() == b64.getMessageSize()); Preconditions.checkState(Arrays.equals(stream.toByteArray(), b64.bitcoinSerialize())); Preconditions.checkState(b64.getOptimalEncodingMessageSize() == b64Created.getMessageSize()); } blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b64, true, false, b64.getHash(), chainHeadHeight + 19, "b64")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b64.getTransactions().get(0).getHash()), b64.getTransactions().get(0).getOutputs().get(0).getValue(), b64.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Spend an output created in the block itself // -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // TransactionOutPointWithValue out19 = spendableOutputs.poll(); Preconditions.checkState(out19 != null);//TODO preconditions all the way up Block b65 = createNextBlock(b64, chainHeadHeight + 20, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out19.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out19, 0); b65.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b65.addTransaction(tx2); } b65.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b65, true, false, b65.getHash(), chainHeadHeight + 20, "b65")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b65.getTransactions().get(0).getHash()), b65.getTransactions().get(0).getOutputs().get(0).getValue(), b65.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Attempt to spend an output created later in the same block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b66 (20) // TransactionOutPointWithValue out20 = spendableOutputs.poll(); Preconditions.checkState(out20 != null); Block b66 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out20.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out20, 0); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b66.addTransaction(tx2); b66.addTransaction(tx1); } b66.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b66, false, true, b65.getHash(), chainHeadHeight + 20, "b66")); // Attempt to double-spend a transaction created in a block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b67 (20) // Block b67 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out20.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out20, 0); b67.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b67.addTransaction(tx2); Transaction tx3 = new Transaction(params); tx3.addOutput(new TransactionOutput(params, tx3, out20.value, new byte[]{OP_TRUE})); tx3.addInput(new TransactionInput(params, tx3, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b67.addTransaction(tx3); } b67.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b67, false, true, b65.getHash(), chainHeadHeight + 20, "b67")); // A few more tests of block subsidy // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b68 (20) // Block b68 = createNextBlock(b65, chainHeadHeight + 21, null, BigInteger.TEN); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, out20.value.subtract(BigInteger.valueOf(9)), new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, out20, 0); b68.addTransaction(tx); } b68.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b68, false, true, b65.getHash(), chainHeadHeight + 20, "b68")); Block b69 = createNextBlock(b65, chainHeadHeight + 21, null, BigInteger.TEN); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, out20.value.subtract(BigInteger.TEN), new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, out20, 0); b69.addTransaction(tx); } b69.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b69, true, false, b69.getHash(), chainHeadHeight + 21, "b69")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b69.getTransactions().get(0).getHash()), b69.getTransactions().get(0).getOutputs().get(0).getValue(), b69.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test spending the outpoint of a non-existent transaction // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b70 (21) // TransactionOutPointWithValue out21 = spendableOutputs.poll(); Preconditions.checkState(out21 != null); Block b70 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[]{OP_TRUE})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, new Sha256Hash("23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c")))); b70.addTransaction(tx); } b70.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b70, false, true, b69.getHash(), chainHeadHeight + 21, "b70")); // Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks) // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b71 (21) // \-> b72 (21) // Block b72 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b72.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b72.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b72.addTransaction(tx); } b72.solve(); Block b71 = new Block(params, b72.bitcoinSerialize()); b71.addTransaction(b72.getTransactions().get(2)); Preconditions.checkState(b71.getHash().equals(b72.getHash())); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b71, false, true, b69.getHash(), chainHeadHeight + 21, "b71")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b72, true, false, b72.getHash(), chainHeadHeight + 22, "b72")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b72.getTransactions().get(0).getHash()), b72.getTransactions().get(0).getOutputs().get(0).getValue(), b72.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Have some fun with invalid scripts and MAX_BLOCK_SIGOPS // -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) // \-> b** (22) // TransactionOutPointWithValue out22 = spendableOutputs.poll(); Preconditions.checkState(out22 != null); Block b73 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b73.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is too large, the CHECKSIGs after that push are still counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; Utils.uint32ToByteArrayLE(Script.MAX_SCRIPT_ELEMENT_SIZE + 1, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b73.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b73.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b73.addTransaction(tx); } b73.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b73, false, true, b72.getHash(), chainHeadHeight + 22, "b73")); Block b74 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b74.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all previous CHECKSIGs are counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xfe; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 5] = (byte)0xff; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b74.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b74.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b74.addTransaction(tx); } b74.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b74, false, true, b72.getHash(), chainHeadHeight + 22, "b74")); Block b75 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b75.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all subsequent CHECKSIGs are not counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b75.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b75.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b75.addTransaction(tx); } b75.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b75, true, false, b75.getHash(), chainHeadHeight + 23, "b75")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b75.getTransactions().get(0).getHash()), b75.getTransactions().get(0).getOutputs().get(0).getValue(), b75.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out23 = spendableOutputs.poll(); Preconditions.checkState(out23 != null); Block b76 = createNextBlock(b75, chainHeadHeight + 24, out23, null); { int sigOps = 0; for (Transaction tx : b76.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is filled with CHECKSIGs, they (obviously) arent counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; Utils.uint32ToByteArrayLE(Block.MAX_BLOCK_SIGOPS, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b76.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b76.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b76.addTransaction(tx); } b76.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b76, true, false, b76.getHash(), chainHeadHeight + 24, "b76")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b76.getTransactions().get(0).getHash()), b76.getTransactions().get(0).getOutputs().get(0).getValue(), b76.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test transaction resurrection // -> b77 (24) -> b78 (25) -> b79 (26) // \-> b80 (25) -> b81 (26) -> b82 (27) // b78 creates a tx, which is spent in b79. after b82, both should be in mempool // TransactionOutPointWithValue out24 = spendableOutputs.poll(); Preconditions.checkState(out24 != null); TransactionOutPointWithValue out25 = spendableOutputs.poll(); Preconditions.checkState(out25 != null); TransactionOutPointWithValue out26 = spendableOutputs.poll(); Preconditions.checkState(out26 != null); TransactionOutPointWithValue out27 = spendableOutputs.poll(); Preconditions.checkState(out27 != null); Block b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77")); Block b78 = createNextBlock(b77, chainHeadHeight + 26, out25, null); Transaction b78tx = new Transaction(params); { b78tx.addOutput(new TransactionOutput(params, b78tx, BigInteger.ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(b78tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b77.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b77.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b78.addTransaction(b78tx); } b78.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b78, true, false, b78.getHash(), chainHeadHeight + 26, "b78")); Block b79 = createNextBlock(b78, chainHeadHeight + 27, out26, null); Transaction b79tx = new Transaction(params); { b79tx.addOutput(new TransactionOutput(params, b79tx, BigInteger.ZERO, new byte[]{OP_TRUE})); b79tx.addInput(new TransactionInput(params, b79tx, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, b78tx.getHash()))); b79.addTransaction(b79tx); } b79.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b79, true, false, b79.getHash(), chainHeadHeight + 27, "b79")); blocks.add(new MemoryPoolState(new HashSet<InventoryItem>(), "post-b79 empty mempool")); Block b80 = createNextBlock(b77, chainHeadHeight + 26, out25, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b80, true, false, b79.getHash(), chainHeadHeight + 27, "b80")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b80.getTransactions().get(0).getHash()), b80.getTransactions().get(0).getOutputs().get(0).getValue(), b80.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b81 = createNextBlock(b80, chainHeadHeight + 27, out26, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b81, true, false, b79.getHash(), chainHeadHeight + 27, "b81")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b81.getTransactions().get(0).getHash()), b81.getTransactions().get(0).getOutputs().get(0).getValue(), b81.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b82 = createNextBlock(b81, chainHeadHeight + 28, out27, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b82, true, false, b82.getHash(), chainHeadHeight + 28, "b82")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b82.getTransactions().get(0).getHash()), b82.getTransactions().get(0).getOutputs().get(0).getValue(), b82.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); HashSet<InventoryItem> post82Mempool = new HashSet<InventoryItem>(); post82Mempool.add(new InventoryItem(InventoryItem.Type.Transaction, b78tx.getHash())); post82Mempool.add(new InventoryItem(InventoryItem.Type.Transaction, b79tx.getHash())); blocks.add(new MemoryPoolState(post82Mempool, "post-b82 tx resurrection")); // Test invalid opcodes in dead execution paths. // -> b81 (26) -> b82 (27) -> b83 (28) // b83 creates a tx which contains a transaction script with an invalid opcode in a dead execution path: // OP_FALSE OP_IF OP_INVALIDOPCODE OP_ELSE OP_TRUE OP_ENDIF // TransactionOutPointWithValue out28 = spendableOutputs.poll(); Preconditions.checkState(out28 != null); Block b83 = createNextBlock(b82, chainHeadHeight + 29, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out28.value, new byte[]{OP_IF, (byte) OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF})); addOnlyInputToTransaction(tx1, out28, 0); b83.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_FALSE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b83.addTransaction(tx2); } b83.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b83, true, false, b83.getHash(), chainHeadHeight + 29, "b83")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b83.getTransactions().get(0).getHash()), b83.getTransactions().get(0).getOutputs().get(0).getValue(), b83.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // The remaining tests arent designed to fit in the standard flow, and thus must always come last // Add new tests here. //TODO: Explicitly address MoneyRange() checks // Test massive reorgs (in terms of tx count) // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> lots of outputs -> lots of spends // Reorg back to: // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> empty blocks // TransactionOutPointWithValue out29 = spendableOutputs.poll(); Preconditions.checkState(out29 != null); Block b1001 = createNextBlock(b83, chainHeadHeight + 30, out29, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1001, true, false, b1001.getHash(), chainHeadHeight + 30, "b1001")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b1001.getTransactions().get(0).getHash()), b1001.getTransactions().get(0).getOutputs().get(0).getValue(), b1001.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); - int nextHeight = chainHeadHeight + 31; + int heightAfter1001 = chainHeadHeight + 31; if (runLargeReorgs) { // No way you can fit this test in memory Preconditions.checkArgument(blockStorageFile != null); Block lastBlock = b1001; TransactionOutPoint lastOutput = new TransactionOutPoint(params, 2, b1001.getTransactions().get(1).getHash()); int blockCountAfter1001; + int nextHeight = heightAfter1001; List<Sha256Hash> hashesToSpend = new LinkedList<Sha256Hash>(); // all index 0 final int TRANSACTION_CREATION_BLOCKS = 100; for (blockCountAfter1001 = 0; blockCountAfter1001 < TRANSACTION_CREATION_BLOCKS; blockCountAfter1001++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.getMessageSize() < Block.MAX_BLOCK_SIZE - 500) { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] { OP_TRUE }, lastOutput)); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); lastOutput = new TransactionOutPoint(params, 1, tx.getHash()); hashesToSpend.add(tx.getHash()); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction generator " + blockCountAfter1001 + "/" + TRANSACTION_CREATION_BLOCKS)); lastBlock = block; } Iterator<Sha256Hash> hashes = hashesToSpend.iterator(); for (int i = 0; hashes.hasNext(); i++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.getMessageSize() < Block.MAX_BLOCK_SIZE - 500 && hashes.hasNext()) { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] { OP_TRUE }, new TransactionOutPoint(params, 0, hashes.next()))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction spender " + i)); lastBlock = block; blockCountAfter1001++; } // Reorg back to b1001 + empty blocks Sha256Hash firstHash = lastBlock.getHash(); int height = nextHeight-1; - nextHeight = chainHeadHeight + 26; + nextHeight = heightAfter1001; lastBlock = b1001; for (int i = 0; i < blockCountAfter1001; i++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, firstHash, height, "post-b1001 empty reorg block " + i + "/" + blockCountAfter1001)); lastBlock = block; } // Try to spend from the other chain Block b1002 = createNextBlock(lastBlock, nextHeight, null, null); { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_TRUE}, new TransactionOutPoint(params, 0, hashesToSpend.get(0)))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); b1002.addTransaction(tx); } b1002.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1002, false, true, firstHash, height, "b1002")); // Now actually reorg Block b1003 = createNextBlock(lastBlock, nextHeight, null, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1003, true, false, b1003.getHash(), nextHeight, "b1003")); // Now try to spend again Block b1004 = createNextBlock(b1003, nextHeight+1, null, null); { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_TRUE}, new TransactionOutPoint(params, 0, hashesToSpend.get(0)))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); b1004.addTransaction(tx); } b1004.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1004, false, true, b1003.getHash(), nextHeight, "b1004")); ret.maximumReorgBlockCount = Math.max(ret.maximumReorgBlockCount, blockCountAfter1001); } if (outStream != null) outStream.close(); // (finally) return the created chain return ret; } private Block createNextBlock(Block baseBlock, int nextBlockHeight, TransactionOutPointWithValue prevOut, BigInteger additionalCoinbaseValue) throws ScriptException { Integer height = blockToHeightMap.get(baseBlock.getHash()); if (height != null) Preconditions.checkState(height == nextBlockHeight - 1); BigInteger coinbaseValue = Utils.toNanoCoins(50, 0).shiftRight(nextBlockHeight / params.getSubsidyDecreaseBlockCount()) .add((prevOut != null ? prevOut.value.subtract(BigInteger.ONE) : BigInteger.ZERO)) .add(additionalCoinbaseValue == null ? BigInteger.ZERO : additionalCoinbaseValue); Block block = baseBlock.createNextBlockWithCoinbase(coinbaseOutKeyPubKey, coinbaseValue); if (prevOut != null) { Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), ScriptBuilder.createOutputScript(new ECKey(null, coinbaseOutKeyPubKey)).getProgram())); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, prevOut); block.addTransaction(t); block.solve(); } return block; } private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut) throws ScriptException { addOnlyInputToTransaction(t, prevOut, TransactionInput.NO_SEQUENCE); } private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut, long sequence) throws ScriptException { TransactionInput input = new TransactionInput(params, t, new byte[]{}, prevOut.outpoint); input.setSequenceNumber(sequence); t.addInput(input); byte[] connectedPubKeyScript = prevOut.scriptPubKey.getProgram(); Sha256Hash hash = t.hashForSignature(0, connectedPubKeyScript, SigHash.ALL, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.ALL.ordinal() + 1); byte[] signature = bos.toByteArray(); Preconditions.checkState(prevOut.scriptPubKey.isSentToRawPubKey()); input.setScriptBytes(Script.createInputScript(signature)); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } }
false
true
public RuleList getBlocksToTest(boolean addSigExpensiveBlocks, boolean runLargeReorgs, File blockStorageFile) throws ScriptException, ProtocolException, IOException { final FileOutputStream outStream = blockStorageFile != null ? new FileOutputStream(blockStorageFile) : null; List<Rule> blocks = new LinkedList<Rule>() { @Override public boolean add(Rule element) { if (outStream != null && element instanceof BlockAndValidity) { try { outStream.write((int) (params.getPacketMagic() >>> 24)); outStream.write((int) (params.getPacketMagic() >>> 16)); outStream.write((int) (params.getPacketMagic() >>> 8)); outStream.write((int) (params.getPacketMagic() >>> 0)); byte[] block = ((BlockAndValidity)element).block.bitcoinSerialize(); byte[] length = new byte[4]; Utils.uint32ToByteArrayBE(block.length, length, 0); outStream.write(Utils.reverseBytes(length)); outStream.write(block); ((BlockAndValidity)element).block = null; } catch (IOException e) { throw new RuntimeException(e); } } return super.add(element); } }; RuleList ret = new RuleList(blocks, hashHeaderMap, 10); Queue<TransactionOutPointWithValue> spendableOutputs = new LinkedList<TransactionOutPointWithValue>(); int chainHeadHeight = 1; Block chainHead = params.getGenesisBlock().createNextBlockWithCoinbase(coinbaseOutKeyPubKey); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, chainHead, true, false, chainHead.getHash(), 1, "Initial Block")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, chainHead.getTransactions().get(0).getHash()), Utils.toNanoCoins(50, 0), chainHead.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) { chainHead = chainHead.createNextBlockWithCoinbase(coinbaseOutKeyPubKey); chainHeadHeight++; blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, chainHead, true, false, chainHead.getHash(), i+1, "Initial Block chain output generation")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, chainHead.getTransactions().get(0).getHash()), Utils.toNanoCoins(50, 0), chainHead.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); } // Start by building a couple of blocks on top of the genesis block. Block b1 = createNextBlock(chainHead, chainHeadHeight + 1, spendableOutputs.poll(), null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1, true, false, b1.getHash(), chainHeadHeight + 1, "b1")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b1.getTransactions().get(0).getHash()), b1.getTransactions().get(0).getOutputs().get(0).getValue(), b1.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out1 = spendableOutputs.poll(); Preconditions.checkState(out1 != null); Block b2 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); // Make sure nothing funky happens if we try to re-add b2 blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b2.getTransactions().get(0).getHash()), b2.getTransactions().get(0).getOutputs().get(0).getValue(), b2.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // We now have the following chain (which output is spent is in parentheses): // genesis -> b1 (0) -> b2 (1) // // so fork like this: // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) // // Nothing should happen at this point. We saw b2 first so it takes priority. Block b3 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Make sure nothing breaks if we add b3 twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Now we add another block to make the alternative chain longer. TransactionOutPointWithValue out2 = spendableOutputs.poll(); Preconditions.checkState(out2 != null); Block b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b4, true, false, b4.getHash(), chainHeadHeight + 3, "b4")); // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) -> b4 (2) // // ... and back to the first chain. Block b5 = createNextBlock(b2, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b5, true, false, b4.getHash(), chainHeadHeight + 3, "b5")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b5.getTransactions().get(0).getHash()), b5.getTransactions().get(0).getOutputs().get(0).getValue(), b5.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out3 = spendableOutputs.poll(); Block b6 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b6, true, false, b6.getHash(), chainHeadHeight + 4, "b6")); // // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b3 (1) -> b4 (2) // // Try to create a fork that double-spends // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b7 (2) -> b8 (4) // \-> b3 (1) -> b4 (2) // Block b7 = createNextBlock(b5, chainHeadHeight + 5, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b7, true, false, b6.getHash(), chainHeadHeight + 4, "b7")); TransactionOutPointWithValue out4 = spendableOutputs.poll(); Block b8 = createNextBlock(b7, chainHeadHeight + 6, out4, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b8, false, true, b6.getHash(), chainHeadHeight + 4, "b8")); // Try to create a block that has too much fee // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b9 (4) // \-> b3 (1) -> b4 (2) // Block b9 = createNextBlock(b6, chainHeadHeight + 5, out4, BigInteger.valueOf(1)); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b9, false, true, b6.getHash(), chainHeadHeight + 4, "b9")); // Create a fork that ends in a block with too much fee (the one that causes the reorg) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b10 (3) -> b11 (4) // \-> b3 (1) -> b4 (2) // Block b10 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b10, true, false, b6.getHash(), chainHeadHeight + 4, "b10")); Block b11 = createNextBlock(b10, chainHeadHeight + 5, out4, BigInteger.valueOf(1)); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b11, false, true, b6.getHash(), chainHeadHeight + 4, "b11")); // Try again, but with a valid fork first // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b14 (5) // (b12 added last) // \-> b3 (1) -> b4 (2) // Block b12 = createNextBlock(b5, chainHeadHeight + 4, out3, null); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b12.getTransactions().get(0).getHash()), b12.getTransactions().get(0).getOutputs().get(0).getValue(), b12.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b13 = createNextBlock(b12, chainHeadHeight + 5, out4, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); // Make sure we dont die if an orphan gets added twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b13.getTransactions().get(0).getHash()), b13.getTransactions().get(0).getOutputs().get(0).getValue(), b13.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out5 = spendableOutputs.poll(); Block b14 = createNextBlock(b13, chainHeadHeight + 6, out5, BigInteger.valueOf(1)); // This will be "validly" added, though its actually invalid, it will just be marked orphan // and will be discarded when an attempt is made to reorg to it. // TODO: Use a WeakReference to check that it is freed properly after the reorg blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); // Make sure we dont die if an orphan gets added twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b12, false, true, b13.getHash(), chainHeadHeight + 5, "b12")); // Add a block with MAX_BLOCK_SIGOPS and one with one more sigop // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6) // \-> b3 (1) -> b4 (2) // Block b15 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { int sigOps = 0; for (Transaction tx : b15.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b15.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b15.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b15.addTransaction(tx); } b15.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b15, true, false, b15.getHash(), chainHeadHeight + 6, "b15")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b15.getTransactions().get(0).getHash()), b15.getTransactions().get(0).getOutputs().get(0).getValue(), b15.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out6 = spendableOutputs.poll(); Block b16 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { int sigOps = 0; for (Transaction tx : b16.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b16.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b16.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b16.addTransaction(tx); } b16.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b16, false, true, b15.getHash(), chainHeadHeight + 6, "b16")); // Attempt to spend a transaction created on a different fork // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (6) // \-> b3 (1) -> b4 (2) // Block b17 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b3.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b3.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b17.addTransaction(tx); } b17.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b17, false, true, b15.getHash(), chainHeadHeight + 6, "b17")); // Attempt to spend a transaction created on a different fork (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b18 (5) -> b19 (6) // \-> b3 (1) -> b4 (2) // Block b18 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b3.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b3.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b18.addTransaction(tx); } b18.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b18, true, false, b15.getHash(), chainHeadHeight + 6, "b17")); Block b19 = createNextBlock(b18, chainHeadHeight + 7, out6, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b19, false, true, b15.getHash(), chainHeadHeight + 6, "b19")); // Attempt to spend a coinbase at depth too low // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7) // \-> b3 (1) -> b4 (2) // TransactionOutPointWithValue out7 = spendableOutputs.poll(); Block b20 = createNextBlock(b15, chainHeadHeight + 7, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b20, false, true, b15.getHash(), chainHeadHeight + 6, "b20")); // Attempt to spend a coinbase at depth too low (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b21 (6) -> b22 (5) // \-> b3 (1) -> b4 (2) // Block b21 = createNextBlock(b13, chainHeadHeight + 6, out6, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b21, true, false, b15.getHash(), chainHeadHeight + 6, "b21")); Block b22 = createNextBlock(b21, chainHeadHeight + 7, out5, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b22, false, true, b15.getHash(), chainHeadHeight + 6, "b22")); // Create a block on either side of MAX_BLOCK_SIZE and make sure its accepted/rejected // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) // \-> b24 (6) -> b25 (7) // \-> b3 (1) -> b4 (2) // Block b23 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b23.getMessageSize() - 138]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b23.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b23.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b23.addTransaction(tx); } b23.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b23, true, false, b23.getHash(), chainHeadHeight + 7, "b23")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b23.getTransactions().get(0).getHash()), b23.getTransactions().get(0).getOutputs().get(0).getValue(), b23.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b24 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b24.getMessageSize() - 135]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b24.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b24.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b24.addTransaction(tx); } b24.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b24, false, true, b23.getHash(), chainHeadHeight + 7, "b24")); // Extend the b24 chain to make sure bitcoind isn't accepting b24 Block b25 = createNextBlock(b24, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b25, false, false, b23.getHash(), chainHeadHeight + 7, "b25")); // Create blocks with a coinbase input script size out of range // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) // \-> ... (6) -> ... (7) // \-> b3 (1) -> b4 (2) // Block b26 = createNextBlock(b15, chainHeadHeight + 7, out6, null); // 1 is too small, but we already generate every other block with 2, so that is tested b26.getTransactions().get(0).getInputs().get(0).setScriptBytes(new byte[] {0}); b26.setMerkleRoot(null); b26.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b26, false, true, b23.getHash(), chainHeadHeight + 7, "b26")); // Extend the b26 chain to make sure bitcoind isn't accepting b26 Block b27 = createNextBlock(b26, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b27, false, false, b23.getHash(), chainHeadHeight + 7, "b27")); Block b28 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { byte[] coinbase = new byte[101]; Arrays.fill(coinbase, (byte)0); b28.getTransactions().get(0).getInputs().get(0).setScriptBytes(coinbase); } b28.setMerkleRoot(null); b28.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b28, false, true, b23.getHash(), chainHeadHeight + 7, "b28")); // Extend the b28 chain to make sure bitcoind isn't accepting b28 Block b29 = createNextBlock(b28, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b29, false, false, b23.getHash(), chainHeadHeight + 7, "b29")); Block b30 = createNextBlock(b23, chainHeadHeight + 8, out7, null); { byte[] coinbase = new byte[100]; Arrays.fill(coinbase, (byte)0); b30.getTransactions().get(0).getInputs().get(0).setScriptBytes(coinbase); } b30.setMerkleRoot(null); b30.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b30, true, false, b30.getHash(), chainHeadHeight + 8, "b30")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b30.getTransactions().get(0).getHash()), b30.getTransactions().get(0).getOutputs().get(0).getValue(), b30.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Check sigops of OP_CHECKMULTISIG/OP_CHECKMULTISIGVERIFY/OP_CHECKSIGVERIFY // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b36 (11) // \-> b34 (10) // \-> b32 (9) // TransactionOutPointWithValue out8 = spendableOutputs.poll(); Block b31 = createNextBlock(b30, chainHeadHeight + 9, out8, null); { int sigOps = 0; for (Transaction tx : b31.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b31.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b31.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b31.addTransaction(tx); } b31.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b31, true, false, b31.getHash(), chainHeadHeight + 9, "b31")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b31.getTransactions().get(0).getHash()), b31.getTransactions().get(0).getOutputs().get(0).getValue(), b31.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out9 = spendableOutputs.poll(); Block b32 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b32.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b32.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b32.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b32.addTransaction(tx); } b32.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b32, false, true, b31.getHash(), chainHeadHeight + 9, "b32")); Block b33 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b33.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b33.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b33.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b33.addTransaction(tx); } b33.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b33, true, false, b33.getHash(), chainHeadHeight + 10, "b33")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b33.getTransactions().get(0).getHash()), b33.getTransactions().get(0).getOutputs().get(0).getValue(), b33.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out10 = spendableOutputs.poll(); Block b34 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b34.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b34.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b34.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b34.addTransaction(tx); } b34.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b34, false, true, b33.getHash(), chainHeadHeight + 10, "b34")); Block b35 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b35.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b35.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b35.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b35.addTransaction(tx); } b35.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b35, true, false, b35.getHash(), chainHeadHeight + 11, "b35")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b35.getTransactions().get(0).getHash()), b35.getTransactions().get(0).getOutputs().get(0).getValue(), b35.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out11 = spendableOutputs.poll(); Block b36 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { int sigOps = 0; for (Transaction tx : b36.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b36.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b36.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b36.addTransaction(tx); } b36.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b36, false, true, b35.getHash(), chainHeadHeight + 11, "b36")); // Check spending of a transaction in a block which failed to connect // (test block store transaction abort handling, not that it should get this far if that's broken...) // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b37 (11) // \-> b38 (11) // Block b37 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, out11); // double spend out11 b37.addTransaction(tx); } b37.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b37, false, true, b35.getHash(), chainHeadHeight + 11, "b37")); Block b38 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); // Attempt to spend b37's first non-coinbase tx, at which point b37 was still considered valid addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b37.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b37.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b38.addTransaction(tx); } b38.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b38, false, true, b35.getHash(), chainHeadHeight + 11, "b38")); // Check P2SH SigOp counting // 13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b41 (12) // \-> b40 (12) // // Create some P2SH outputs that will require 6 sigops to spend byte[] b39p2shScriptPubKey; int b39numP2SHOutputs = 0, b39sigOpsPerOutput = 6; Block b39 = createNextBlock(b35, chainHeadHeight + 12, null, null); { ByteArrayOutputStream p2shScriptPubKey = new UnsafeByteArrayOutputStream(); try { Script.writeBytes(p2shScriptPubKey, coinbaseOutKeyPubKey); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_CHECKSIG); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } b39p2shScriptPubKey = p2shScriptPubKey.toByteArray(); byte[] scriptHash = Utils.sha256hash160(b39p2shScriptPubKey); UnsafeByteArrayOutputStream scriptPubKey = new UnsafeByteArrayOutputStream(scriptHash.length + 3); scriptPubKey.write(OP_HASH160); try { Script.writeBytes(scriptPubKey, scriptHash); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } scriptPubKey.write(OP_EQUAL); BigInteger lastOutputValue = out11.value.subtract(BigInteger.valueOf(1)); TransactionOutPoint lastOutPoint; { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(params, tx, lastOutputValue, new byte[]{OP_1})); addOnlyInputToTransaction(tx, out11); lastOutPoint = new TransactionOutPoint(params, 1, tx.getHash()); b39.addTransaction(tx); } b39numP2SHOutputs++; while (b39.getMessageSize() < Block.MAX_BLOCK_SIZE) { Transaction tx = new Transaction(params); lastOutputValue = lastOutputValue.subtract(BigInteger.valueOf(1)); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(params, tx, lastOutputValue, new byte[]{OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); lastOutPoint = new TransactionOutPoint(params, 1, tx.getHash()); if (b39.getMessageSize() + tx.getMessageSize() < Block.MAX_BLOCK_SIZE) { b39.addTransaction(tx); b39numP2SHOutputs++; } else break; } } b39.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b39, true, false, b39.getHash(), chainHeadHeight + 12, "b39")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b39.getTransactions().get(0).getHash()), b39.getTransactions().get(0).getOutputs().get(0).getValue(), b39.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out12 = spendableOutputs.poll(); Block b40 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b40.transactions) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; Preconditions.checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint(params, 2, b40.getTransactions().get(1).getHash()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(params, tx, new byte[]{}, new TransactionOutPoint(params, 0, b39.getTransactions().get(i).getHash())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.ordinal() + 1); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new UnsafeByteArrayOutputStream(signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] {(byte) OP_CHECKSIG}); scriptSigBos.write(Script.createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(params, 0, tx.getHash()); b40.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, scriptPubKey)); b40.addTransaction(tx); } b40.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b40, false, true, b39.getHash(), chainHeadHeight + 12, "b40")); Block b41 = null; if (addSigExpensiveBlocks) { b41 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b41.transactions) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; Preconditions.checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint( params, 2, b41.getTransactions().get(1).getHash()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger .valueOf(1), new byte[] {OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(params, tx, new byte[] {}, new TransactionOutPoint(params, 0, b39.getTransactions().get(i).getHash())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream( 73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.ordinal() + 1); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new UnsafeByteArrayOutputStream( signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] { (byte) OP_CHECKSIG}); scriptSigBos.write(Script .createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(params, 0, tx.getHash()); b41.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, scriptPubKey)); b41.addTransaction(tx); } b41.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b41, true, false, b41.getHash(), chainHeadHeight + 13, "b41")); } // Fork off of b39 to create a constant base again // b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) // \-> b41 (12) // Block b42 = createNextBlock(b39, chainHeadHeight + 13, out12, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b42, true, false, b41 == null ? b42.getHash() : b41.getHash(), chainHeadHeight + 13, "b42")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b42.getTransactions().get(0).getHash()), b42.getTransactions().get(0).getOutputs().get(0).getValue(), b42.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out13 = spendableOutputs.poll(); Block b43 = createNextBlock(b42, chainHeadHeight + 14, out13, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b43, true, false, b43.getHash(), chainHeadHeight + 14, "b43")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b43.getTransactions().get(0).getHash()), b43.getTransactions().get(0).getOutputs().get(0).getValue(), b43.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test a number of really invalid scenarios // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b44 (14) // \-> ??? (15) // TransactionOutPointWithValue out14 = spendableOutputs.poll(); // A valid block created exactly like b44 to make sure the creation itself works Block b44 = new Block(params); byte[] outScriptBytes = ScriptBuilder.createOutputScript(new ECKey(null, coinbaseOutKeyPubKey)).getProgram(); { b44.setDifficultyTarget(b43.getDifficultyTarget()); b44.addCoinbaseTransaction(coinbaseOutKeyPubKey, BigInteger.ZERO); Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out14); b44.addTransaction(t); b44.setPrevBlockHash(b43.getHash()); b44.setTime(b43.getTimeSeconds() + 1); } b44.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b44, true, false, b44.getHash(), chainHeadHeight + 15, "b44")); TransactionOutPointWithValue out15 = spendableOutputs.poll(); // A block with a non-coinbase as the first tx Block b45 = new Block(params); { b45.setDifficultyTarget(b44.getDifficultyTarget()); //b45.addCoinbaseTransaction(pubKey, coinbaseValue); Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out15); try { b45.addTransaction(t); } catch (RuntimeException e) { } // Should happen if (b45.getTransactions().size() > 0) throw new RuntimeException("addTransaction doesn't properly check for adding a non-coinbase as first tx"); b45.addTransaction(t, false); b45.setPrevBlockHash(b44.getHash()); b45.setTime(b44.getTimeSeconds() + 1); } b45.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b45, false, true, b44.getHash(), chainHeadHeight + 15, "b45")); // A block with no txn Block b46 = new Block(params); { b46.transactions = new ArrayList<Transaction>(); b46.setDifficultyTarget(b44.getDifficultyTarget()); b46.setMerkleRoot(Sha256Hash.ZERO_HASH); b46.setPrevBlockHash(b44.getHash()); b46.setTime(b44.getTimeSeconds() + 1); } b46.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b46, false, true, b44.getHash(), chainHeadHeight + 15, "b46")); // A block with invalid work Block b47 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { try { // Inverse solve BigInteger target = b47.getDifficultyTargetAsInteger(); while (true) { BigInteger h = b47.getHash().toBigInteger(); if (h.compareTo(target) > 0) // if invalid break; // increment the nonce and try again. b47.setNonce(b47.getNonce() + 1); } } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b47, false, true, b44.getHash(), chainHeadHeight + 15, "b47")); // Block with timestamp > 2h in the future Block b48 = createNextBlock(b44, chainHeadHeight + 16, out15, null); b48.setTime(Utils.now().getTime() / 1000 + 60*60*3); b48.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b48, false, true, b44.getHash(), chainHeadHeight + 15, "b48")); // Block with invalid merkle hash Block b49 = createNextBlock(b44, chainHeadHeight + 16, out15, null); b49.setMerkleRoot(Sha256Hash.ZERO_HASH); b49.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b49, false, true, b44.getHash(), chainHeadHeight + 15, "b49")); // Block with incorrect POW limit Block b50 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { long diffTarget = b44.getDifficultyTarget(); diffTarget &= 0xFFBFFFFF; // Make difficulty one bit harder b50.setDifficultyTarget(diffTarget); } b50.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b50, false, true, b44.getHash(), chainHeadHeight + 15, "b50")); // A block with two coinbase txn Block b51 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction coinbase = new Transaction(params); coinbase.addInput(new TransactionInput(params, coinbase, new byte[]{(byte) 0xff, 110, 1})); coinbase.addOutput(new TransactionOutput(params, coinbase, BigInteger.ONE, outScriptBytes)); b51.addTransaction(coinbase, false); } b51.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b51, false, true, b44.getHash(), chainHeadHeight + 15, "b51")); // A block with duplicate txn Block b52 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b52.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b52.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b52.addTransaction(tx); b52.addTransaction(tx); } b52.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b52, false, true, b44.getHash(), chainHeadHeight + 15, "b52")); // Test block timestamp // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) // \-> b54 (15) // \-> b44 (14) // Block b53 = createNextBlock(b43, chainHeadHeight + 15, out14, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b53, true, false, b44.getHash(), chainHeadHeight + 15, "b53")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b53.getTransactions().get(0).getHash()), b53.getTransactions().get(0).getOutputs().get(0).getValue(), b53.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Block with invalid timestamp Block b54 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b54.setTime(b35.getTimeSeconds() - 1); b54.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b54, false, true, b44.getHash(), chainHeadHeight + 15, "b54")); // Block with valid timestamp Block b55 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b55.setTime(b35.getTimeSeconds()); b55.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b55, true, false, b55.getHash(), chainHeadHeight + 16, "b55")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b55.getTransactions().get(0).getHash()), b55.getTransactions().get(0).getOutputs().get(0).getValue(), b55.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test CVE-2012-2459 // -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) // \-> b56 (16) // TransactionOutPointWithValue out16 = spendableOutputs.poll(); Block b57 = createNextBlock(b55, chainHeadHeight + 17, out16, null); Transaction b56txToDuplicate; { b56txToDuplicate = new Transaction(params); b56txToDuplicate.addOutput(new TransactionOutput(params, b56txToDuplicate, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(b56txToDuplicate, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b57.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b57.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b57.addTransaction(b56txToDuplicate); } b57.solve(); Block b56; try { b56 = new Block(params, b57.bitcoinSerialize()); } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } b56.addTransaction(b56txToDuplicate); Preconditions.checkState(b56.getHash().equals(b57.getHash())); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b56, false, true, b55.getHash(), chainHeadHeight + 16, "b56")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b57, true, false, b57.getHash(), chainHeadHeight + 17, "b57")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b57.getTransactions().get(0).getHash()), b57.getTransactions().get(0).getOutputs().get(0).getValue(), b57.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test a few invalid tx types // -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> ??? (17) // TransactionOutPointWithValue out17 = spendableOutputs.poll(); // tx with prevout.n out of range Block b58 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] {})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, new TransactionOutPoint(params, 3, b58.getTransactions().get(1).getHash()))); b58.addTransaction(tx); } b58.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b58, false, true, b57.getHash(), chainHeadHeight + 17, "b58")); // tx with output value > input value out of range Block b59 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, b59.getTransactions().get(1).getOutputs().get(2).getValue().add(BigInteger.ONE), new byte[] {})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, new TransactionOutPoint(params, 2, b59.getTransactions().get(1).getHash()))); b59.addTransaction(tx); } b59.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b59, false, true, b57.getHash(), chainHeadHeight + 17, "b59")); Block b60 = createNextBlock(b57, chainHeadHeight + 18, out17, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b60, true, false, b60.getHash(), chainHeadHeight + 18, "b60")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b60.getTransactions().get(0).getHash()), b60.getTransactions().get(0).getOutputs().get(0).getValue(), b60.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test BIP30 // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b61 (18) // TransactionOutPointWithValue out18 = spendableOutputs.poll(); Block b61 = createNextBlock(b60, chainHeadHeight + 19, out18, null); { byte[] scriptBytes = b61.getTransactions().get(0).getInputs().get(0).getScriptBytes(); scriptBytes[0]--; // createNextBlock will increment the first script byte on each new block b61.getTransactions().get(0).getInputs().get(0).setScriptBytes(scriptBytes); b61.unCache(); Preconditions.checkState(b61.getTransactions().get(0).equals(b60.getTransactions().get(0))); } b61.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b61, false, true, b60.getHash(), chainHeadHeight + 18, "b61")); // Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b62 (18) // Block b62 = createNextBlock(b60, chainHeadHeight + 19, null, null); { Transaction tx = new Transaction(params); tx.setLockTime(0xffffffffL); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] {OP_TRUE})); addOnlyInputToTransaction(tx, out18, 0); b62.addTransaction(tx); Preconditions.checkState(!tx.isFinal(chainHeadHeight + 17, b62.getTimeSeconds())); } b62.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b62, false, true, b60.getHash(), chainHeadHeight + 18, "b62")); // Test a non-final coinbase is also rejected // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b63 (-) // Block b63 = createNextBlock(b60, chainHeadHeight + 19, null, null); { b63.getTransactions().get(0).setLockTime(0xffffffffL); b63.getTransactions().get(0).getInputs().get(0).setSequenceNumber(0xDEADBEEF); Preconditions.checkState(!b63.getTransactions().get(0).isFinal(chainHeadHeight + 17, b63.getTimeSeconds())); } b63.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b63, false, true, b60.getHash(), chainHeadHeight + 18, "b63")); // Check that a block which is (when properly encoded) <= MAX_BLOCK_SIZE is accepted // Even when it is encoded with varints that make its encoded size actually > MAX_BLOCK_SIZE // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) // Block b64; { Block b64Created = createNextBlock(b60, chainHeadHeight + 19, out18, null); Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b64Created.getMessageSize() - 138]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b64Created.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b64Created.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b64Created.addTransaction(tx); b64Created.solve(); UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(b64Created.getMessageSize() + 8); b64Created.writeHeader(stream); byte[] varIntBytes = new byte[9]; varIntBytes[0] = (byte) 255; Utils.uint32ToByteArrayLE((long)b64Created.getTransactions().size(), varIntBytes, 1); Utils.uint32ToByteArrayLE(((long)b64Created.getTransactions().size()) >>> 32, varIntBytes, 5); stream.write(varIntBytes); Preconditions.checkState(new VarInt(varIntBytes, 0).value == b64Created.getTransactions().size()); for (Transaction transaction : b64Created.getTransactions()) transaction.bitcoinSerialize(stream); b64 = new Block(params, stream.toByteArray(), false, true, stream.size()); // The following checks are checking to ensure block serialization functions in the way needed for this test // If they fail, it is likely not an indication of error, but an indication that this test needs rewritten Preconditions.checkState(stream.size() == b64Created.getMessageSize() + 8); Preconditions.checkState(stream.size() == b64.getMessageSize()); Preconditions.checkState(Arrays.equals(stream.toByteArray(), b64.bitcoinSerialize())); Preconditions.checkState(b64.getOptimalEncodingMessageSize() == b64Created.getMessageSize()); } blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b64, true, false, b64.getHash(), chainHeadHeight + 19, "b64")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b64.getTransactions().get(0).getHash()), b64.getTransactions().get(0).getOutputs().get(0).getValue(), b64.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Spend an output created in the block itself // -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // TransactionOutPointWithValue out19 = spendableOutputs.poll(); Preconditions.checkState(out19 != null);//TODO preconditions all the way up Block b65 = createNextBlock(b64, chainHeadHeight + 20, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out19.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out19, 0); b65.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b65.addTransaction(tx2); } b65.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b65, true, false, b65.getHash(), chainHeadHeight + 20, "b65")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b65.getTransactions().get(0).getHash()), b65.getTransactions().get(0).getOutputs().get(0).getValue(), b65.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Attempt to spend an output created later in the same block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b66 (20) // TransactionOutPointWithValue out20 = spendableOutputs.poll(); Preconditions.checkState(out20 != null); Block b66 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out20.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out20, 0); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b66.addTransaction(tx2); b66.addTransaction(tx1); } b66.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b66, false, true, b65.getHash(), chainHeadHeight + 20, "b66")); // Attempt to double-spend a transaction created in a block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b67 (20) // Block b67 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out20.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out20, 0); b67.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b67.addTransaction(tx2); Transaction tx3 = new Transaction(params); tx3.addOutput(new TransactionOutput(params, tx3, out20.value, new byte[]{OP_TRUE})); tx3.addInput(new TransactionInput(params, tx3, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b67.addTransaction(tx3); } b67.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b67, false, true, b65.getHash(), chainHeadHeight + 20, "b67")); // A few more tests of block subsidy // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b68 (20) // Block b68 = createNextBlock(b65, chainHeadHeight + 21, null, BigInteger.TEN); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, out20.value.subtract(BigInteger.valueOf(9)), new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, out20, 0); b68.addTransaction(tx); } b68.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b68, false, true, b65.getHash(), chainHeadHeight + 20, "b68")); Block b69 = createNextBlock(b65, chainHeadHeight + 21, null, BigInteger.TEN); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, out20.value.subtract(BigInteger.TEN), new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, out20, 0); b69.addTransaction(tx); } b69.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b69, true, false, b69.getHash(), chainHeadHeight + 21, "b69")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b69.getTransactions().get(0).getHash()), b69.getTransactions().get(0).getOutputs().get(0).getValue(), b69.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test spending the outpoint of a non-existent transaction // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b70 (21) // TransactionOutPointWithValue out21 = spendableOutputs.poll(); Preconditions.checkState(out21 != null); Block b70 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[]{OP_TRUE})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, new Sha256Hash("23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c")))); b70.addTransaction(tx); } b70.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b70, false, true, b69.getHash(), chainHeadHeight + 21, "b70")); // Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks) // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b71 (21) // \-> b72 (21) // Block b72 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b72.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b72.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b72.addTransaction(tx); } b72.solve(); Block b71 = new Block(params, b72.bitcoinSerialize()); b71.addTransaction(b72.getTransactions().get(2)); Preconditions.checkState(b71.getHash().equals(b72.getHash())); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b71, false, true, b69.getHash(), chainHeadHeight + 21, "b71")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b72, true, false, b72.getHash(), chainHeadHeight + 22, "b72")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b72.getTransactions().get(0).getHash()), b72.getTransactions().get(0).getOutputs().get(0).getValue(), b72.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Have some fun with invalid scripts and MAX_BLOCK_SIGOPS // -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) // \-> b** (22) // TransactionOutPointWithValue out22 = spendableOutputs.poll(); Preconditions.checkState(out22 != null); Block b73 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b73.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is too large, the CHECKSIGs after that push are still counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; Utils.uint32ToByteArrayLE(Script.MAX_SCRIPT_ELEMENT_SIZE + 1, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b73.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b73.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b73.addTransaction(tx); } b73.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b73, false, true, b72.getHash(), chainHeadHeight + 22, "b73")); Block b74 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b74.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all previous CHECKSIGs are counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xfe; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 5] = (byte)0xff; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b74.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b74.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b74.addTransaction(tx); } b74.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b74, false, true, b72.getHash(), chainHeadHeight + 22, "b74")); Block b75 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b75.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all subsequent CHECKSIGs are not counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b75.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b75.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b75.addTransaction(tx); } b75.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b75, true, false, b75.getHash(), chainHeadHeight + 23, "b75")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b75.getTransactions().get(0).getHash()), b75.getTransactions().get(0).getOutputs().get(0).getValue(), b75.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out23 = spendableOutputs.poll(); Preconditions.checkState(out23 != null); Block b76 = createNextBlock(b75, chainHeadHeight + 24, out23, null); { int sigOps = 0; for (Transaction tx : b76.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is filled with CHECKSIGs, they (obviously) arent counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; Utils.uint32ToByteArrayLE(Block.MAX_BLOCK_SIGOPS, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b76.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b76.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b76.addTransaction(tx); } b76.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b76, true, false, b76.getHash(), chainHeadHeight + 24, "b76")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b76.getTransactions().get(0).getHash()), b76.getTransactions().get(0).getOutputs().get(0).getValue(), b76.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test transaction resurrection // -> b77 (24) -> b78 (25) -> b79 (26) // \-> b80 (25) -> b81 (26) -> b82 (27) // b78 creates a tx, which is spent in b79. after b82, both should be in mempool // TransactionOutPointWithValue out24 = spendableOutputs.poll(); Preconditions.checkState(out24 != null); TransactionOutPointWithValue out25 = spendableOutputs.poll(); Preconditions.checkState(out25 != null); TransactionOutPointWithValue out26 = spendableOutputs.poll(); Preconditions.checkState(out26 != null); TransactionOutPointWithValue out27 = spendableOutputs.poll(); Preconditions.checkState(out27 != null); Block b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77")); Block b78 = createNextBlock(b77, chainHeadHeight + 26, out25, null); Transaction b78tx = new Transaction(params); { b78tx.addOutput(new TransactionOutput(params, b78tx, BigInteger.ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(b78tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b77.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b77.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b78.addTransaction(b78tx); } b78.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b78, true, false, b78.getHash(), chainHeadHeight + 26, "b78")); Block b79 = createNextBlock(b78, chainHeadHeight + 27, out26, null); Transaction b79tx = new Transaction(params); { b79tx.addOutput(new TransactionOutput(params, b79tx, BigInteger.ZERO, new byte[]{OP_TRUE})); b79tx.addInput(new TransactionInput(params, b79tx, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, b78tx.getHash()))); b79.addTransaction(b79tx); } b79.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b79, true, false, b79.getHash(), chainHeadHeight + 27, "b79")); blocks.add(new MemoryPoolState(new HashSet<InventoryItem>(), "post-b79 empty mempool")); Block b80 = createNextBlock(b77, chainHeadHeight + 26, out25, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b80, true, false, b79.getHash(), chainHeadHeight + 27, "b80")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b80.getTransactions().get(0).getHash()), b80.getTransactions().get(0).getOutputs().get(0).getValue(), b80.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b81 = createNextBlock(b80, chainHeadHeight + 27, out26, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b81, true, false, b79.getHash(), chainHeadHeight + 27, "b81")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b81.getTransactions().get(0).getHash()), b81.getTransactions().get(0).getOutputs().get(0).getValue(), b81.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b82 = createNextBlock(b81, chainHeadHeight + 28, out27, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b82, true, false, b82.getHash(), chainHeadHeight + 28, "b82")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b82.getTransactions().get(0).getHash()), b82.getTransactions().get(0).getOutputs().get(0).getValue(), b82.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); HashSet<InventoryItem> post82Mempool = new HashSet<InventoryItem>(); post82Mempool.add(new InventoryItem(InventoryItem.Type.Transaction, b78tx.getHash())); post82Mempool.add(new InventoryItem(InventoryItem.Type.Transaction, b79tx.getHash())); blocks.add(new MemoryPoolState(post82Mempool, "post-b82 tx resurrection")); // Test invalid opcodes in dead execution paths. // -> b81 (26) -> b82 (27) -> b83 (28) // b83 creates a tx which contains a transaction script with an invalid opcode in a dead execution path: // OP_FALSE OP_IF OP_INVALIDOPCODE OP_ELSE OP_TRUE OP_ENDIF // TransactionOutPointWithValue out28 = spendableOutputs.poll(); Preconditions.checkState(out28 != null); Block b83 = createNextBlock(b82, chainHeadHeight + 29, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out28.value, new byte[]{OP_IF, (byte) OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF})); addOnlyInputToTransaction(tx1, out28, 0); b83.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_FALSE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b83.addTransaction(tx2); } b83.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b83, true, false, b83.getHash(), chainHeadHeight + 29, "b83")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b83.getTransactions().get(0).getHash()), b83.getTransactions().get(0).getOutputs().get(0).getValue(), b83.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // The remaining tests arent designed to fit in the standard flow, and thus must always come last // Add new tests here. //TODO: Explicitly address MoneyRange() checks // Test massive reorgs (in terms of tx count) // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> lots of outputs -> lots of spends // Reorg back to: // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> empty blocks // TransactionOutPointWithValue out29 = spendableOutputs.poll(); Preconditions.checkState(out29 != null); Block b1001 = createNextBlock(b83, chainHeadHeight + 30, out29, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1001, true, false, b1001.getHash(), chainHeadHeight + 30, "b1001")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b1001.getTransactions().get(0).getHash()), b1001.getTransactions().get(0).getOutputs().get(0).getValue(), b1001.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); int nextHeight = chainHeadHeight + 31; if (runLargeReorgs) { // No way you can fit this test in memory Preconditions.checkArgument(blockStorageFile != null); Block lastBlock = b1001; TransactionOutPoint lastOutput = new TransactionOutPoint(params, 2, b1001.getTransactions().get(1).getHash()); int blockCountAfter1001; List<Sha256Hash> hashesToSpend = new LinkedList<Sha256Hash>(); // all index 0 final int TRANSACTION_CREATION_BLOCKS = 100; for (blockCountAfter1001 = 0; blockCountAfter1001 < TRANSACTION_CREATION_BLOCKS; blockCountAfter1001++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.getMessageSize() < Block.MAX_BLOCK_SIZE - 500) { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] { OP_TRUE }, lastOutput)); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); lastOutput = new TransactionOutPoint(params, 1, tx.getHash()); hashesToSpend.add(tx.getHash()); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction generator " + blockCountAfter1001 + "/" + TRANSACTION_CREATION_BLOCKS)); lastBlock = block; } Iterator<Sha256Hash> hashes = hashesToSpend.iterator(); for (int i = 0; hashes.hasNext(); i++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.getMessageSize() < Block.MAX_BLOCK_SIZE - 500 && hashes.hasNext()) { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] { OP_TRUE }, new TransactionOutPoint(params, 0, hashes.next()))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction spender " + i)); lastBlock = block; blockCountAfter1001++; } // Reorg back to b1001 + empty blocks Sha256Hash firstHash = lastBlock.getHash(); int height = nextHeight-1; nextHeight = chainHeadHeight + 26; lastBlock = b1001; for (int i = 0; i < blockCountAfter1001; i++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, firstHash, height, "post-b1001 empty reorg block " + i + "/" + blockCountAfter1001)); lastBlock = block; } // Try to spend from the other chain Block b1002 = createNextBlock(lastBlock, nextHeight, null, null); { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_TRUE}, new TransactionOutPoint(params, 0, hashesToSpend.get(0)))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); b1002.addTransaction(tx); } b1002.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1002, false, true, firstHash, height, "b1002")); // Now actually reorg Block b1003 = createNextBlock(lastBlock, nextHeight, null, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1003, true, false, b1003.getHash(), nextHeight, "b1003")); // Now try to spend again Block b1004 = createNextBlock(b1003, nextHeight+1, null, null); { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_TRUE}, new TransactionOutPoint(params, 0, hashesToSpend.get(0)))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); b1004.addTransaction(tx); } b1004.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1004, false, true, b1003.getHash(), nextHeight, "b1004")); ret.maximumReorgBlockCount = Math.max(ret.maximumReorgBlockCount, blockCountAfter1001); } if (outStream != null) outStream.close(); // (finally) return the created chain return ret; }
public RuleList getBlocksToTest(boolean addSigExpensiveBlocks, boolean runLargeReorgs, File blockStorageFile) throws ScriptException, ProtocolException, IOException { final FileOutputStream outStream = blockStorageFile != null ? new FileOutputStream(blockStorageFile) : null; List<Rule> blocks = new LinkedList<Rule>() { @Override public boolean add(Rule element) { if (outStream != null && element instanceof BlockAndValidity) { try { outStream.write((int) (params.getPacketMagic() >>> 24)); outStream.write((int) (params.getPacketMagic() >>> 16)); outStream.write((int) (params.getPacketMagic() >>> 8)); outStream.write((int) (params.getPacketMagic() >>> 0)); byte[] block = ((BlockAndValidity)element).block.bitcoinSerialize(); byte[] length = new byte[4]; Utils.uint32ToByteArrayBE(block.length, length, 0); outStream.write(Utils.reverseBytes(length)); outStream.write(block); ((BlockAndValidity)element).block = null; } catch (IOException e) { throw new RuntimeException(e); } } return super.add(element); } }; RuleList ret = new RuleList(blocks, hashHeaderMap, 10); Queue<TransactionOutPointWithValue> spendableOutputs = new LinkedList<TransactionOutPointWithValue>(); int chainHeadHeight = 1; Block chainHead = params.getGenesisBlock().createNextBlockWithCoinbase(coinbaseOutKeyPubKey); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, chainHead, true, false, chainHead.getHash(), 1, "Initial Block")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, chainHead.getTransactions().get(0).getHash()), Utils.toNanoCoins(50, 0), chainHead.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); for (int i = 1; i < params.getSpendableCoinbaseDepth(); i++) { chainHead = chainHead.createNextBlockWithCoinbase(coinbaseOutKeyPubKey); chainHeadHeight++; blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, chainHead, true, false, chainHead.getHash(), i+1, "Initial Block chain output generation")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, chainHead.getTransactions().get(0).getHash()), Utils.toNanoCoins(50, 0), chainHead.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); } // Start by building a couple of blocks on top of the genesis block. Block b1 = createNextBlock(chainHead, chainHeadHeight + 1, spendableOutputs.poll(), null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1, true, false, b1.getHash(), chainHeadHeight + 1, "b1")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b1.getTransactions().get(0).getHash()), b1.getTransactions().get(0).getOutputs().get(0).getValue(), b1.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out1 = spendableOutputs.poll(); Preconditions.checkState(out1 != null); Block b2 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); // Make sure nothing funky happens if we try to re-add b2 blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b2, true, false, b2.getHash(), chainHeadHeight + 2, "b2")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b2.getTransactions().get(0).getHash()), b2.getTransactions().get(0).getOutputs().get(0).getValue(), b2.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // We now have the following chain (which output is spent is in parentheses): // genesis -> b1 (0) -> b2 (1) // // so fork like this: // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) // // Nothing should happen at this point. We saw b2 first so it takes priority. Block b3 = createNextBlock(b1, chainHeadHeight + 2, out1, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Make sure nothing breaks if we add b3 twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b3, true, false, b2.getHash(), chainHeadHeight + 2, "b3")); // Now we add another block to make the alternative chain longer. TransactionOutPointWithValue out2 = spendableOutputs.poll(); Preconditions.checkState(out2 != null); Block b4 = createNextBlock(b3, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b4, true, false, b4.getHash(), chainHeadHeight + 3, "b4")); // // genesis -> b1 (0) -> b2 (1) // \-> b3 (1) -> b4 (2) // // ... and back to the first chain. Block b5 = createNextBlock(b2, chainHeadHeight + 3, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b5, true, false, b4.getHash(), chainHeadHeight + 3, "b5")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b5.getTransactions().get(0).getHash()), b5.getTransactions().get(0).getOutputs().get(0).getValue(), b5.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out3 = spendableOutputs.poll(); Block b6 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b6, true, false, b6.getHash(), chainHeadHeight + 4, "b6")); // // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b3 (1) -> b4 (2) // // Try to create a fork that double-spends // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b7 (2) -> b8 (4) // \-> b3 (1) -> b4 (2) // Block b7 = createNextBlock(b5, chainHeadHeight + 5, out2, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b7, true, false, b6.getHash(), chainHeadHeight + 4, "b7")); TransactionOutPointWithValue out4 = spendableOutputs.poll(); Block b8 = createNextBlock(b7, chainHeadHeight + 6, out4, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b8, false, true, b6.getHash(), chainHeadHeight + 4, "b8")); // Try to create a block that has too much fee // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b9 (4) // \-> b3 (1) -> b4 (2) // Block b9 = createNextBlock(b6, chainHeadHeight + 5, out4, BigInteger.valueOf(1)); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b9, false, true, b6.getHash(), chainHeadHeight + 4, "b9")); // Create a fork that ends in a block with too much fee (the one that causes the reorg) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b10 (3) -> b11 (4) // \-> b3 (1) -> b4 (2) // Block b10 = createNextBlock(b5, chainHeadHeight + 4, out3, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b10, true, false, b6.getHash(), chainHeadHeight + 4, "b10")); Block b11 = createNextBlock(b10, chainHeadHeight + 5, out4, BigInteger.valueOf(1)); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b11, false, true, b6.getHash(), chainHeadHeight + 4, "b11")); // Try again, but with a valid fork first // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b14 (5) // (b12 added last) // \-> b3 (1) -> b4 (2) // Block b12 = createNextBlock(b5, chainHeadHeight + 4, out3, null); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b12.getTransactions().get(0).getHash()), b12.getTransactions().get(0).getOutputs().get(0).getValue(), b12.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b13 = createNextBlock(b12, chainHeadHeight + 5, out4, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); // Make sure we dont die if an orphan gets added twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b13, false, false, b6.getHash(), chainHeadHeight + 4, "b13")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b13.getTransactions().get(0).getHash()), b13.getTransactions().get(0).getOutputs().get(0).getValue(), b13.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out5 = spendableOutputs.poll(); Block b14 = createNextBlock(b13, chainHeadHeight + 6, out5, BigInteger.valueOf(1)); // This will be "validly" added, though its actually invalid, it will just be marked orphan // and will be discarded when an attempt is made to reorg to it. // TODO: Use a WeakReference to check that it is freed properly after the reorg blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); // Make sure we dont die if an orphan gets added twice blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b14, false, false, b6.getHash(), chainHeadHeight + 4, "b14")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b12, false, true, b13.getHash(), chainHeadHeight + 5, "b12")); // Add a block with MAX_BLOCK_SIGOPS and one with one more sigop // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6) // \-> b3 (1) -> b4 (2) // Block b15 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { int sigOps = 0; for (Transaction tx : b15.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b15.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b15.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b15.addTransaction(tx); } b15.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b15, true, false, b15.getHash(), chainHeadHeight + 6, "b15")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b15.getTransactions().get(0).getHash()), b15.getTransactions().get(0).getOutputs().get(0).getValue(), b15.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out6 = spendableOutputs.poll(); Block b16 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { int sigOps = 0; for (Transaction tx : b16.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b16.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b16.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b16.addTransaction(tx); } b16.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b16, false, true, b15.getHash(), chainHeadHeight + 6, "b16")); // Attempt to spend a transaction created on a different fork // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (6) // \-> b3 (1) -> b4 (2) // Block b17 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b3.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b3.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b17.addTransaction(tx); } b17.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b17, false, true, b15.getHash(), chainHeadHeight + 6, "b17")); // Attempt to spend a transaction created on a different fork (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b18 (5) -> b19 (6) // \-> b3 (1) -> b4 (2) // Block b18 = createNextBlock(b13, chainHeadHeight + 6, out5, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b3.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b3.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b18.addTransaction(tx); } b18.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b18, true, false, b15.getHash(), chainHeadHeight + 6, "b17")); Block b19 = createNextBlock(b18, chainHeadHeight + 7, out6, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b19, false, true, b15.getHash(), chainHeadHeight + 6, "b19")); // Attempt to spend a coinbase at depth too low // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7) // \-> b3 (1) -> b4 (2) // TransactionOutPointWithValue out7 = spendableOutputs.poll(); Block b20 = createNextBlock(b15, chainHeadHeight + 7, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b20, false, true, b15.getHash(), chainHeadHeight + 6, "b20")); // Attempt to spend a coinbase at depth too low (on a fork this time) // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) // \-> b21 (6) -> b22 (5) // \-> b3 (1) -> b4 (2) // Block b21 = createNextBlock(b13, chainHeadHeight + 6, out6, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b21, true, false, b15.getHash(), chainHeadHeight + 6, "b21")); Block b22 = createNextBlock(b21, chainHeadHeight + 7, out5, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b22, false, true, b15.getHash(), chainHeadHeight + 6, "b22")); // Create a block on either side of MAX_BLOCK_SIZE and make sure its accepted/rejected // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) // \-> b24 (6) -> b25 (7) // \-> b3 (1) -> b4 (2) // Block b23 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b23.getMessageSize() - 138]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b23.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b23.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b23.addTransaction(tx); } b23.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b23, true, false, b23.getHash(), chainHeadHeight + 7, "b23")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b23.getTransactions().get(0).getHash()), b23.getTransactions().get(0).getOutputs().get(0).getValue(), b23.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b24 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b24.getMessageSize() - 135]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b24.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b24.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b24.addTransaction(tx); } b24.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b24, false, true, b23.getHash(), chainHeadHeight + 7, "b24")); // Extend the b24 chain to make sure bitcoind isn't accepting b24 Block b25 = createNextBlock(b24, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b25, false, false, b23.getHash(), chainHeadHeight + 7, "b25")); // Create blocks with a coinbase input script size out of range // genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3) // \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) // \-> ... (6) -> ... (7) // \-> b3 (1) -> b4 (2) // Block b26 = createNextBlock(b15, chainHeadHeight + 7, out6, null); // 1 is too small, but we already generate every other block with 2, so that is tested b26.getTransactions().get(0).getInputs().get(0).setScriptBytes(new byte[] {0}); b26.setMerkleRoot(null); b26.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b26, false, true, b23.getHash(), chainHeadHeight + 7, "b26")); // Extend the b26 chain to make sure bitcoind isn't accepting b26 Block b27 = createNextBlock(b26, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b27, false, false, b23.getHash(), chainHeadHeight + 7, "b27")); Block b28 = createNextBlock(b15, chainHeadHeight + 7, out6, null); { byte[] coinbase = new byte[101]; Arrays.fill(coinbase, (byte)0); b28.getTransactions().get(0).getInputs().get(0).setScriptBytes(coinbase); } b28.setMerkleRoot(null); b28.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b28, false, true, b23.getHash(), chainHeadHeight + 7, "b28")); // Extend the b28 chain to make sure bitcoind isn't accepting b28 Block b29 = createNextBlock(b28, chainHeadHeight + 8, out7, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b29, false, false, b23.getHash(), chainHeadHeight + 7, "b29")); Block b30 = createNextBlock(b23, chainHeadHeight + 8, out7, null); { byte[] coinbase = new byte[100]; Arrays.fill(coinbase, (byte)0); b30.getTransactions().get(0).getInputs().get(0).setScriptBytes(coinbase); } b30.setMerkleRoot(null); b30.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b30, true, false, b30.getHash(), chainHeadHeight + 8, "b30")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b30.getTransactions().get(0).getHash()), b30.getTransactions().get(0).getOutputs().get(0).getValue(), b30.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Check sigops of OP_CHECKMULTISIG/OP_CHECKMULTISIGVERIFY/OP_CHECKSIGVERIFY // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b36 (11) // \-> b34 (10) // \-> b32 (9) // TransactionOutPointWithValue out8 = spendableOutputs.poll(); Block b31 = createNextBlock(b30, chainHeadHeight + 9, out8, null); { int sigOps = 0; for (Transaction tx : b31.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b31.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b31.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b31.addTransaction(tx); } b31.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b31, true, false, b31.getHash(), chainHeadHeight + 9, "b31")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b31.getTransactions().get(0).getHash()), b31.getTransactions().get(0).getOutputs().get(0).getValue(), b31.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out9 = spendableOutputs.poll(); Block b32 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b32.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIG); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b32.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b32.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b32.addTransaction(tx); } b32.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b32, false, true, b31.getHash(), chainHeadHeight + 9, "b32")); Block b33 = createNextBlock(b31, chainHeadHeight + 10, out9, null); { int sigOps = 0; for (Transaction tx : b33.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b33.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b33.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b33.addTransaction(tx); } b33.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b33, true, false, b33.getHash(), chainHeadHeight + 10, "b33")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b33.getTransactions().get(0).getHash()), b33.getTransactions().get(0).getOutputs().get(0).getValue(), b33.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out10 = spendableOutputs.poll(); Block b34 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b34.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[(Block.MAX_BLOCK_SIGOPS - sigOps)/20 + (Block.MAX_BLOCK_SIGOPS - sigOps)%20 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKMULTISIGVERIFY); for (int i = 0; i < (Block.MAX_BLOCK_SIGOPS - sigOps)%20; i++) outputScript[i] = (byte) OP_CHECKSIG; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b34.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b34.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b34.addTransaction(tx); } b34.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b34, false, true, b33.getHash(), chainHeadHeight + 10, "b34")); Block b35 = createNextBlock(b33, chainHeadHeight + 11, out10, null); { int sigOps = 0; for (Transaction tx : b35.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b35.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b35.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b35.addTransaction(tx); } b35.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b35, true, false, b35.getHash(), chainHeadHeight + 11, "b35")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b35.getTransactions().get(0).getHash()), b35.getTransactions().get(0).getOutputs().get(0).getValue(), b35.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out11 = spendableOutputs.poll(); Block b36 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { int sigOps = 0; for (Transaction tx : b36.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIGVERIFY); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b36.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b36.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b36.addTransaction(tx); } b36.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b36, false, true, b35.getHash(), chainHeadHeight + 11, "b36")); // Check spending of a transaction in a block which failed to connect // (test block store transaction abort handling, not that it should get this far if that's broken...) // 6 (3) // 12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) // \-> b37 (11) // \-> b38 (11) // Block b37 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, out11); // double spend out11 b37.addTransaction(tx); } b37.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b37, false, true, b35.getHash(), chainHeadHeight + 11, "b37")); Block b38 = createNextBlock(b35, chainHeadHeight + 12, out11, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); // Attempt to spend b37's first non-coinbase tx, at which point b37 was still considered valid addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b37.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b37.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b38.addTransaction(tx); } b38.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b38, false, true, b35.getHash(), chainHeadHeight + 11, "b38")); // Check P2SH SigOp counting // 13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b41 (12) // \-> b40 (12) // // Create some P2SH outputs that will require 6 sigops to spend byte[] b39p2shScriptPubKey; int b39numP2SHOutputs = 0, b39sigOpsPerOutput = 6; Block b39 = createNextBlock(b35, chainHeadHeight + 12, null, null); { ByteArrayOutputStream p2shScriptPubKey = new UnsafeByteArrayOutputStream(); try { Script.writeBytes(p2shScriptPubKey, coinbaseOutKeyPubKey); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_2DUP); p2shScriptPubKey.write(OP_CHECKSIGVERIFY); p2shScriptPubKey.write(OP_CHECKSIG); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } b39p2shScriptPubKey = p2shScriptPubKey.toByteArray(); byte[] scriptHash = Utils.sha256hash160(b39p2shScriptPubKey); UnsafeByteArrayOutputStream scriptPubKey = new UnsafeByteArrayOutputStream(scriptHash.length + 3); scriptPubKey.write(OP_HASH160); try { Script.writeBytes(scriptPubKey, scriptHash); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } scriptPubKey.write(OP_EQUAL); BigInteger lastOutputValue = out11.value.subtract(BigInteger.valueOf(1)); TransactionOutPoint lastOutPoint; { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(params, tx, lastOutputValue, new byte[]{OP_1})); addOnlyInputToTransaction(tx, out11); lastOutPoint = new TransactionOutPoint(params, 1, tx.getHash()); b39.addTransaction(tx); } b39numP2SHOutputs++; while (b39.getMessageSize() < Block.MAX_BLOCK_SIZE) { Transaction tx = new Transaction(params); lastOutputValue = lastOutputValue.subtract(BigInteger.valueOf(1)); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), scriptPubKey.toByteArray())); tx.addOutput(new TransactionOutput(params, tx, lastOutputValue, new byte[]{OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); lastOutPoint = new TransactionOutPoint(params, 1, tx.getHash()); if (b39.getMessageSize() + tx.getMessageSize() < Block.MAX_BLOCK_SIZE) { b39.addTransaction(tx); b39numP2SHOutputs++; } else break; } } b39.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b39, true, false, b39.getHash(), chainHeadHeight + 12, "b39")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b39.getTransactions().get(0).getHash()), b39.getTransactions().get(0).getOutputs().get(0).getValue(), b39.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out12 = spendableOutputs.poll(); Block b40 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b40.transactions) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; Preconditions.checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint(params, 2, b40.getTransactions().get(1).getHash()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(params, tx, new byte[]{}, new TransactionOutPoint(params, 0, b39.getTransactions().get(i).getHash())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.ordinal() + 1); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new UnsafeByteArrayOutputStream(signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] {(byte) OP_CHECKSIG}); scriptSigBos.write(Script.createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(params, 0, tx.getHash()); b40.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + 1]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, scriptPubKey)); b40.addTransaction(tx); } b40.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b40, false, true, b39.getHash(), chainHeadHeight + 12, "b40")); Block b41 = null; if (addSigExpensiveBlocks) { b41 = createNextBlock(b39, chainHeadHeight + 13, out12, null); { int sigOps = 0; for (Transaction tx : b41.transactions) { sigOps += tx.getSigOpCount(); } int numTxes = (Block.MAX_BLOCK_SIGOPS - sigOps) / b39sigOpsPerOutput; Preconditions.checkState(numTxes <= b39numP2SHOutputs); TransactionOutPoint lastOutPoint = new TransactionOutPoint( params, 2, b41.getTransactions().get(1).getHash()); byte[] scriptSig = null; for (int i = 1; i <= numTxes; i++) { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger .valueOf(1), new byte[] {OP_1})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, lastOutPoint)); TransactionInput input = new TransactionInput(params, tx, new byte[] {}, new TransactionOutPoint(params, 0, b39.getTransactions().get(i).getHash())); tx.addInput(input); if (scriptSig == null) { // Exploit the SigHash.SINGLE bug to avoid having to make more than one signature Sha256Hash hash = tx.hashForSignature(1, b39p2shScriptPubKey, SigHash.SINGLE, false); // Sign input try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream( 73); bos.write(coinbaseOutKey.sign(hash).encodeToDER()); bos.write(SigHash.SINGLE.ordinal() + 1); byte[] signature = bos.toByteArray(); ByteArrayOutputStream scriptSigBos = new UnsafeByteArrayOutputStream( signature.length + b39p2shScriptPubKey.length + 3); Script.writeBytes(scriptSigBos, new byte[] { (byte) OP_CHECKSIG}); scriptSigBos.write(Script .createInputScript(signature)); Script.writeBytes(scriptSigBos, b39p2shScriptPubKey); scriptSig = scriptSigBos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } input.setScriptBytes(scriptSig); lastOutPoint = new TransactionOutPoint(params, 0, tx.getHash()); b41.addTransaction(tx); } sigOps += numTxes * b39sigOpsPerOutput; Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, lastOutPoint)); byte[] scriptPubKey = new byte[Block.MAX_BLOCK_SIGOPS - sigOps]; Arrays.fill(scriptPubKey, (byte) OP_CHECKSIG); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, scriptPubKey)); b41.addTransaction(tx); } b41.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b41, true, false, b41.getHash(), chainHeadHeight + 13, "b41")); } // Fork off of b39 to create a constant base again // b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) // \-> b41 (12) // Block b42 = createNextBlock(b39, chainHeadHeight + 13, out12, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b42, true, false, b41 == null ? b42.getHash() : b41.getHash(), chainHeadHeight + 13, "b42")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b42.getTransactions().get(0).getHash()), b42.getTransactions().get(0).getOutputs().get(0).getValue(), b42.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out13 = spendableOutputs.poll(); Block b43 = createNextBlock(b42, chainHeadHeight + 14, out13, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b43, true, false, b43.getHash(), chainHeadHeight + 14, "b43")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b43.getTransactions().get(0).getHash()), b43.getTransactions().get(0).getOutputs().get(0).getValue(), b43.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test a number of really invalid scenarios // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b44 (14) // \-> ??? (15) // TransactionOutPointWithValue out14 = spendableOutputs.poll(); // A valid block created exactly like b44 to make sure the creation itself works Block b44 = new Block(params); byte[] outScriptBytes = ScriptBuilder.createOutputScript(new ECKey(null, coinbaseOutKeyPubKey)).getProgram(); { b44.setDifficultyTarget(b43.getDifficultyTarget()); b44.addCoinbaseTransaction(coinbaseOutKeyPubKey, BigInteger.ZERO); Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out14); b44.addTransaction(t); b44.setPrevBlockHash(b43.getHash()); b44.setTime(b43.getTimeSeconds() + 1); } b44.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b44, true, false, b44.getHash(), chainHeadHeight + 15, "b44")); TransactionOutPointWithValue out15 = spendableOutputs.poll(); // A block with a non-coinbase as the first tx Block b45 = new Block(params); { b45.setDifficultyTarget(b44.getDifficultyTarget()); //b45.addCoinbaseTransaction(pubKey, coinbaseValue); Transaction t = new Transaction(params); // Entirely invalid scriptPubKey to ensure we aren't pre-verifying too much t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(0), new byte[] {OP_PUSHDATA1 - 1 })); t.addOutput(new TransactionOutput(params, t, BigInteger.valueOf(1), outScriptBytes)); // Spendable output t.addOutput(new TransactionOutput(params, t, BigInteger.ZERO, new byte[] {OP_1})); addOnlyInputToTransaction(t, out15); try { b45.addTransaction(t); } catch (RuntimeException e) { } // Should happen if (b45.getTransactions().size() > 0) throw new RuntimeException("addTransaction doesn't properly check for adding a non-coinbase as first tx"); b45.addTransaction(t, false); b45.setPrevBlockHash(b44.getHash()); b45.setTime(b44.getTimeSeconds() + 1); } b45.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b45, false, true, b44.getHash(), chainHeadHeight + 15, "b45")); // A block with no txn Block b46 = new Block(params); { b46.transactions = new ArrayList<Transaction>(); b46.setDifficultyTarget(b44.getDifficultyTarget()); b46.setMerkleRoot(Sha256Hash.ZERO_HASH); b46.setPrevBlockHash(b44.getHash()); b46.setTime(b44.getTimeSeconds() + 1); } b46.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b46, false, true, b44.getHash(), chainHeadHeight + 15, "b46")); // A block with invalid work Block b47 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { try { // Inverse solve BigInteger target = b47.getDifficultyTargetAsInteger(); while (true) { BigInteger h = b47.getHash().toBigInteger(); if (h.compareTo(target) > 0) // if invalid break; // increment the nonce and try again. b47.setNonce(b47.getNonce() + 1); } } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b47, false, true, b44.getHash(), chainHeadHeight + 15, "b47")); // Block with timestamp > 2h in the future Block b48 = createNextBlock(b44, chainHeadHeight + 16, out15, null); b48.setTime(Utils.now().getTime() / 1000 + 60*60*3); b48.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b48, false, true, b44.getHash(), chainHeadHeight + 15, "b48")); // Block with invalid merkle hash Block b49 = createNextBlock(b44, chainHeadHeight + 16, out15, null); byte[] b49MerkleHash = Sha256Hash.ZERO_HASH.getBytes().clone(); b49MerkleHash[1] = (byte) 0xDE; b49.setMerkleRoot(Sha256Hash.create(b49MerkleHash)); b49.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b49, false, true, b44.getHash(), chainHeadHeight + 15, "b49")); // Block with incorrect POW limit Block b50 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { long diffTarget = b44.getDifficultyTarget(); diffTarget &= 0xFFBFFFFF; // Make difficulty one bit harder b50.setDifficultyTarget(diffTarget); } b50.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b50, false, true, b44.getHash(), chainHeadHeight + 15, "b50")); // A block with two coinbase txn Block b51 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction coinbase = new Transaction(params); coinbase.addInput(new TransactionInput(params, coinbase, new byte[]{(byte) 0xff, 110, 1})); coinbase.addOutput(new TransactionOutput(params, coinbase, BigInteger.ONE, outScriptBytes)); b51.addTransaction(coinbase, false); } b51.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b51, false, true, b44.getHash(), chainHeadHeight + 15, "b51")); // A block with duplicate txn Block b52 = createNextBlock(b44, chainHeadHeight + 16, out15, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b52.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b52.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b52.addTransaction(tx); b52.addTransaction(tx); } b52.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b52, false, true, b44.getHash(), chainHeadHeight + 15, "b52")); // Test block timestamp // -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) // \-> b54 (15) // \-> b44 (14) // Block b53 = createNextBlock(b43, chainHeadHeight + 15, out14, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b53, true, false, b44.getHash(), chainHeadHeight + 15, "b53")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b53.getTransactions().get(0).getHash()), b53.getTransactions().get(0).getOutputs().get(0).getValue(), b53.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Block with invalid timestamp Block b54 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b54.setTime(b35.getTimeSeconds() - 1); b54.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b54, false, true, b44.getHash(), chainHeadHeight + 15, "b54")); // Block with valid timestamp Block b55 = createNextBlock(b53, chainHeadHeight + 16, out15, null); b55.setTime(b35.getTimeSeconds()); b55.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b55, true, false, b55.getHash(), chainHeadHeight + 16, "b55")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b55.getTransactions().get(0).getHash()), b55.getTransactions().get(0).getOutputs().get(0).getValue(), b55.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test CVE-2012-2459 // -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) // \-> b56 (16) // TransactionOutPointWithValue out16 = spendableOutputs.poll(); Block b57 = createNextBlock(b55, chainHeadHeight + 17, out16, null); Transaction b56txToDuplicate; { b56txToDuplicate = new Transaction(params); b56txToDuplicate.addOutput(new TransactionOutput(params, b56txToDuplicate, BigInteger.valueOf(1), new byte[] {})); addOnlyInputToTransaction(b56txToDuplicate, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b57.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b57.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b57.addTransaction(b56txToDuplicate); } b57.solve(); Block b56; try { b56 = new Block(params, b57.bitcoinSerialize()); } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } b56.addTransaction(b56txToDuplicate); Preconditions.checkState(b56.getHash().equals(b57.getHash())); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b56, false, true, b55.getHash(), chainHeadHeight + 16, "b56")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b57, true, false, b57.getHash(), chainHeadHeight + 17, "b57")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b57.getTransactions().get(0).getHash()), b57.getTransactions().get(0).getOutputs().get(0).getValue(), b57.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test a few invalid tx types // -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> ??? (17) // TransactionOutPointWithValue out17 = spendableOutputs.poll(); // tx with prevout.n out of range Block b58 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] {})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, new TransactionOutPoint(params, 3, b58.getTransactions().get(1).getHash()))); b58.addTransaction(tx); } b58.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b58, false, true, b57.getHash(), chainHeadHeight + 17, "b58")); // tx with output value > input value out of range Block b59 = createNextBlock(b57, chainHeadHeight + 18, out17, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, b59.getTransactions().get(1).getOutputs().get(2).getValue().add(BigInteger.ONE), new byte[] {})); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_1}, new TransactionOutPoint(params, 2, b59.getTransactions().get(1).getHash()))); b59.addTransaction(tx); } b59.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b59, false, true, b57.getHash(), chainHeadHeight + 17, "b59")); Block b60 = createNextBlock(b57, chainHeadHeight + 18, out17, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b60, true, false, b60.getHash(), chainHeadHeight + 18, "b60")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b60.getTransactions().get(0).getHash()), b60.getTransactions().get(0).getOutputs().get(0).getValue(), b60.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test BIP30 // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b61 (18) // TransactionOutPointWithValue out18 = spendableOutputs.poll(); Block b61 = createNextBlock(b60, chainHeadHeight + 19, out18, null); { byte[] scriptBytes = b61.getTransactions().get(0).getInputs().get(0).getScriptBytes(); scriptBytes[0]--; // createNextBlock will increment the first script byte on each new block b61.getTransactions().get(0).getInputs().get(0).setScriptBytes(scriptBytes); b61.unCache(); Preconditions.checkState(b61.getTransactions().get(0).equals(b60.getTransactions().get(0))); } b61.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b61, false, true, b60.getHash(), chainHeadHeight + 18, "b61")); // Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests) // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b62 (18) // Block b62 = createNextBlock(b60, chainHeadHeight + 19, null, null); { Transaction tx = new Transaction(params); tx.setLockTime(0xffffffffL); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] {OP_TRUE})); addOnlyInputToTransaction(tx, out18, 0); b62.addTransaction(tx); Preconditions.checkState(!tx.isFinal(chainHeadHeight + 17, b62.getTimeSeconds())); } b62.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b62, false, true, b60.getHash(), chainHeadHeight + 18, "b62")); // Test a non-final coinbase is also rejected // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) // \-> b63 (-) // Block b63 = createNextBlock(b60, chainHeadHeight + 19, null, null); { b63.getTransactions().get(0).setLockTime(0xffffffffL); b63.getTransactions().get(0).getInputs().get(0).setSequenceNumber(0xDEADBEEF); Preconditions.checkState(!b63.getTransactions().get(0).isFinal(chainHeadHeight + 17, b63.getTimeSeconds())); } b63.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b63, false, true, b60.getHash(), chainHeadHeight + 18, "b63")); // Check that a block which is (when properly encoded) <= MAX_BLOCK_SIZE is accepted // Even when it is encoded with varints that make its encoded size actually > MAX_BLOCK_SIZE // -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) // Block b64; { Block b64Created = createNextBlock(b60, chainHeadHeight + 19, out18, null); Transaction tx = new Transaction(params); // Signature size is non-deterministic, so it may take several runs before finding any off-by-one errors byte[] outputScript = new byte[Block.MAX_BLOCK_SIZE - b64Created.getMessageSize() - 138]; Arrays.fill(outputScript, (byte) OP_FALSE); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b64Created.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b64Created.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b64Created.addTransaction(tx); b64Created.solve(); UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(b64Created.getMessageSize() + 8); b64Created.writeHeader(stream); byte[] varIntBytes = new byte[9]; varIntBytes[0] = (byte) 255; Utils.uint32ToByteArrayLE((long)b64Created.getTransactions().size(), varIntBytes, 1); Utils.uint32ToByteArrayLE(((long)b64Created.getTransactions().size()) >>> 32, varIntBytes, 5); stream.write(varIntBytes); Preconditions.checkState(new VarInt(varIntBytes, 0).value == b64Created.getTransactions().size()); for (Transaction transaction : b64Created.getTransactions()) transaction.bitcoinSerialize(stream); b64 = new Block(params, stream.toByteArray(), false, true, stream.size()); // The following checks are checking to ensure block serialization functions in the way needed for this test // If they fail, it is likely not an indication of error, but an indication that this test needs rewritten Preconditions.checkState(stream.size() == b64Created.getMessageSize() + 8); Preconditions.checkState(stream.size() == b64.getMessageSize()); Preconditions.checkState(Arrays.equals(stream.toByteArray(), b64.bitcoinSerialize())); Preconditions.checkState(b64.getOptimalEncodingMessageSize() == b64Created.getMessageSize()); } blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b64, true, false, b64.getHash(), chainHeadHeight + 19, "b64")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b64.getTransactions().get(0).getHash()), b64.getTransactions().get(0).getOutputs().get(0).getValue(), b64.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Spend an output created in the block itself // -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // TransactionOutPointWithValue out19 = spendableOutputs.poll(); Preconditions.checkState(out19 != null);//TODO preconditions all the way up Block b65 = createNextBlock(b64, chainHeadHeight + 20, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out19.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out19, 0); b65.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b65.addTransaction(tx2); } b65.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b65, true, false, b65.getHash(), chainHeadHeight + 20, "b65")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b65.getTransactions().get(0).getHash()), b65.getTransactions().get(0).getOutputs().get(0).getValue(), b65.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Attempt to spend an output created later in the same block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b66 (20) // TransactionOutPointWithValue out20 = spendableOutputs.poll(); Preconditions.checkState(out20 != null); Block b66 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out20.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out20, 0); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b66.addTransaction(tx2); b66.addTransaction(tx1); } b66.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b66, false, true, b65.getHash(), chainHeadHeight + 20, "b66")); // Attempt to double-spend a transaction created in a block // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) // \-> b67 (20) // Block b67 = createNextBlock(b65, chainHeadHeight + 21, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out20.value, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx1, out20, 0); b67.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b67.addTransaction(tx2); Transaction tx3 = new Transaction(params); tx3.addOutput(new TransactionOutput(params, tx3, out20.value, new byte[]{OP_TRUE})); tx3.addInput(new TransactionInput(params, tx3, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b67.addTransaction(tx3); } b67.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b67, false, true, b65.getHash(), chainHeadHeight + 20, "b67")); // A few more tests of block subsidy // -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b68 (20) // Block b68 = createNextBlock(b65, chainHeadHeight + 21, null, BigInteger.TEN); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, out20.value.subtract(BigInteger.valueOf(9)), new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, out20, 0); b68.addTransaction(tx); } b68.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b68, false, true, b65.getHash(), chainHeadHeight + 20, "b68")); Block b69 = createNextBlock(b65, chainHeadHeight + 21, null, BigInteger.TEN); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, out20.value.subtract(BigInteger.TEN), new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, out20, 0); b69.addTransaction(tx); } b69.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b69, true, false, b69.getHash(), chainHeadHeight + 21, "b69")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b69.getTransactions().get(0).getHash()), b69.getTransactions().get(0).getOutputs().get(0).getValue(), b69.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test spending the outpoint of a non-existent transaction // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) // \-> b70 (21) // TransactionOutPointWithValue out21 = spendableOutputs.poll(); Preconditions.checkState(out21 != null); Block b70 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[]{OP_TRUE})); tx.addInput(new TransactionInput(params, tx, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, new Sha256Hash("23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c")))); b70.addTransaction(tx); } b70.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b70, false, true, b69.getHash(), chainHeadHeight + 21, "b70")); // Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks) // -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b71 (21) // \-> b72 (21) // Block b72 = createNextBlock(b69, chainHeadHeight + 22, out21, null); { Transaction tx = new Transaction(params); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b72.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b72.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b72.addTransaction(tx); } b72.solve(); Block b71 = new Block(params, b72.bitcoinSerialize()); b71.addTransaction(b72.getTransactions().get(2)); Preconditions.checkState(b71.getHash().equals(b72.getHash())); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b71, false, true, b69.getHash(), chainHeadHeight + 21, "b71")); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b72, true, false, b72.getHash(), chainHeadHeight + 22, "b72")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b72.getTransactions().get(0).getHash()), b72.getTransactions().get(0).getOutputs().get(0).getValue(), b72.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Have some fun with invalid scripts and MAX_BLOCK_SIGOPS // -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) // \-> b** (22) // TransactionOutPointWithValue out22 = spendableOutputs.poll(); Preconditions.checkState(out22 != null); Block b73 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b73.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is too large, the CHECKSIGs after that push are still counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; Utils.uint32ToByteArrayLE(Script.MAX_SCRIPT_ELEMENT_SIZE + 1, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b73.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b73.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b73.addTransaction(tx); } b73.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b73, false, true, b72.getHash(), chainHeadHeight + 22, "b73")); Block b74 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b74.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all previous CHECKSIGs are counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xfe; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 5] = (byte)0xff; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b74.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b74.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b74.addTransaction(tx); } b74.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b74, false, true, b72.getHash(), chainHeadHeight + 22, "b74")); Block b75 = createNextBlock(b72, chainHeadHeight + 23, out22, null); { int sigOps = 0; for (Transaction tx : b75.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 42]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an invalid element, all subsequent CHECKSIGs are not counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 1] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 2] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 3] = (byte)0xff; outputScript[Block.MAX_BLOCK_SIGOPS - sigOps + 4] = (byte)0xff; tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b75.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b75.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b75.addTransaction(tx); } b75.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b75, true, false, b75.getHash(), chainHeadHeight + 23, "b75")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b75.getTransactions().get(0).getHash()), b75.getTransactions().get(0).getOutputs().get(0).getValue(), b75.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); TransactionOutPointWithValue out23 = spendableOutputs.poll(); Preconditions.checkState(out23 != null); Block b76 = createNextBlock(b75, chainHeadHeight + 24, out23, null); { int sigOps = 0; for (Transaction tx : b76.transactions) { sigOps += tx.getSigOpCount(); } Transaction tx = new Transaction(params); byte[] outputScript = new byte[Block.MAX_BLOCK_SIGOPS - sigOps + (int)Script.MAX_SCRIPT_ELEMENT_SIZE + 1 + 5]; Arrays.fill(outputScript, (byte) OP_CHECKSIG); // If we push an element that is filled with CHECKSIGs, they (obviously) arent counted outputScript[Block.MAX_BLOCK_SIGOPS - sigOps] = OP_PUSHDATA4; Utils.uint32ToByteArrayLE(Block.MAX_BLOCK_SIGOPS, outputScript, Block.MAX_BLOCK_SIGOPS - sigOps + 1); tx.addOutput(new TransactionOutput(params, tx, BigInteger.valueOf(1), outputScript)); addOnlyInputToTransaction(tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b76.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b76.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b76.addTransaction(tx); } b76.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b76, true, false, b76.getHash(), chainHeadHeight + 24, "b76")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b76.getTransactions().get(0).getHash()), b76.getTransactions().get(0).getOutputs().get(0).getValue(), b76.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // Test transaction resurrection // -> b77 (24) -> b78 (25) -> b79 (26) // \-> b80 (25) -> b81 (26) -> b82 (27) // b78 creates a tx, which is spent in b79. after b82, both should be in mempool // TransactionOutPointWithValue out24 = spendableOutputs.poll(); Preconditions.checkState(out24 != null); TransactionOutPointWithValue out25 = spendableOutputs.poll(); Preconditions.checkState(out25 != null); TransactionOutPointWithValue out26 = spendableOutputs.poll(); Preconditions.checkState(out26 != null); TransactionOutPointWithValue out27 = spendableOutputs.poll(); Preconditions.checkState(out27 != null); Block b77 = createNextBlock(b76, chainHeadHeight + 25, out24, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b77, true, false, b77.getHash(), chainHeadHeight + 25, "b77")); Block b78 = createNextBlock(b77, chainHeadHeight + 26, out25, null); Transaction b78tx = new Transaction(params); { b78tx.addOutput(new TransactionOutput(params, b78tx, BigInteger.ZERO, new byte[]{OP_TRUE})); addOnlyInputToTransaction(b78tx, new TransactionOutPointWithValue( new TransactionOutPoint(params, 1, b77.getTransactions().get(1).getHash()), BigInteger.valueOf(1), b77.getTransactions().get(1).getOutputs().get(1).getScriptPubKey())); b78.addTransaction(b78tx); } b78.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b78, true, false, b78.getHash(), chainHeadHeight + 26, "b78")); Block b79 = createNextBlock(b78, chainHeadHeight + 27, out26, null); Transaction b79tx = new Transaction(params); { b79tx.addOutput(new TransactionOutput(params, b79tx, BigInteger.ZERO, new byte[]{OP_TRUE})); b79tx.addInput(new TransactionInput(params, b79tx, new byte[]{OP_TRUE}, new TransactionOutPoint(params, 0, b78tx.getHash()))); b79.addTransaction(b79tx); } b79.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b79, true, false, b79.getHash(), chainHeadHeight + 27, "b79")); blocks.add(new MemoryPoolState(new HashSet<InventoryItem>(), "post-b79 empty mempool")); Block b80 = createNextBlock(b77, chainHeadHeight + 26, out25, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b80, true, false, b79.getHash(), chainHeadHeight + 27, "b80")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b80.getTransactions().get(0).getHash()), b80.getTransactions().get(0).getOutputs().get(0).getValue(), b80.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b81 = createNextBlock(b80, chainHeadHeight + 27, out26, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b81, true, false, b79.getHash(), chainHeadHeight + 27, "b81")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b81.getTransactions().get(0).getHash()), b81.getTransactions().get(0).getOutputs().get(0).getValue(), b81.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); Block b82 = createNextBlock(b81, chainHeadHeight + 28, out27, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b82, true, false, b82.getHash(), chainHeadHeight + 28, "b82")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b82.getTransactions().get(0).getHash()), b82.getTransactions().get(0).getOutputs().get(0).getValue(), b82.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); HashSet<InventoryItem> post82Mempool = new HashSet<InventoryItem>(); post82Mempool.add(new InventoryItem(InventoryItem.Type.Transaction, b78tx.getHash())); post82Mempool.add(new InventoryItem(InventoryItem.Type.Transaction, b79tx.getHash())); blocks.add(new MemoryPoolState(post82Mempool, "post-b82 tx resurrection")); // Test invalid opcodes in dead execution paths. // -> b81 (26) -> b82 (27) -> b83 (28) // b83 creates a tx which contains a transaction script with an invalid opcode in a dead execution path: // OP_FALSE OP_IF OP_INVALIDOPCODE OP_ELSE OP_TRUE OP_ENDIF // TransactionOutPointWithValue out28 = spendableOutputs.poll(); Preconditions.checkState(out28 != null); Block b83 = createNextBlock(b82, chainHeadHeight + 29, null, null); { Transaction tx1 = new Transaction(params); tx1.addOutput(new TransactionOutput(params, tx1, out28.value, new byte[]{OP_IF, (byte) OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF})); addOnlyInputToTransaction(tx1, out28, 0); b83.addTransaction(tx1); Transaction tx2 = new Transaction(params); tx2.addOutput(new TransactionOutput(params, tx2, BigInteger.ZERO, new byte[]{OP_TRUE})); tx2.addInput(new TransactionInput(params, tx2, new byte[]{OP_FALSE}, new TransactionOutPoint(params, 0, tx1.getHash()))); b83.addTransaction(tx2); } b83.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b83, true, false, b83.getHash(), chainHeadHeight + 29, "b83")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b83.getTransactions().get(0).getHash()), b83.getTransactions().get(0).getOutputs().get(0).getValue(), b83.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); // The remaining tests arent designed to fit in the standard flow, and thus must always come last // Add new tests here. //TODO: Explicitly address MoneyRange() checks // Test massive reorgs (in terms of tx count) // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> lots of outputs -> lots of spends // Reorg back to: // -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21) -> b1001 (22) -> empty blocks // TransactionOutPointWithValue out29 = spendableOutputs.poll(); Preconditions.checkState(out29 != null); Block b1001 = createNextBlock(b83, chainHeadHeight + 30, out29, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1001, true, false, b1001.getHash(), chainHeadHeight + 30, "b1001")); spendableOutputs.offer(new TransactionOutPointWithValue( new TransactionOutPoint(params, 0, b1001.getTransactions().get(0).getHash()), b1001.getTransactions().get(0).getOutputs().get(0).getValue(), b1001.getTransactions().get(0).getOutputs().get(0).getScriptPubKey())); int heightAfter1001 = chainHeadHeight + 31; if (runLargeReorgs) { // No way you can fit this test in memory Preconditions.checkArgument(blockStorageFile != null); Block lastBlock = b1001; TransactionOutPoint lastOutput = new TransactionOutPoint(params, 2, b1001.getTransactions().get(1).getHash()); int blockCountAfter1001; int nextHeight = heightAfter1001; List<Sha256Hash> hashesToSpend = new LinkedList<Sha256Hash>(); // all index 0 final int TRANSACTION_CREATION_BLOCKS = 100; for (blockCountAfter1001 = 0; blockCountAfter1001 < TRANSACTION_CREATION_BLOCKS; blockCountAfter1001++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.getMessageSize() < Block.MAX_BLOCK_SIZE - 500) { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] { OP_TRUE }, lastOutput)); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); lastOutput = new TransactionOutPoint(params, 1, tx.getHash()); hashesToSpend.add(tx.getHash()); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction generator " + blockCountAfter1001 + "/" + TRANSACTION_CREATION_BLOCKS)); lastBlock = block; } Iterator<Sha256Hash> hashes = hashesToSpend.iterator(); for (int i = 0; hashes.hasNext(); i++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); while (block.getMessageSize() < Block.MAX_BLOCK_SIZE - 500 && hashes.hasNext()) { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] { OP_TRUE }, new TransactionOutPoint(params, 0, hashes.next()))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); block.addTransaction(tx); } block.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, block.getHash(), nextHeight-1, "post-b1001 repeated transaction spender " + i)); lastBlock = block; blockCountAfter1001++; } // Reorg back to b1001 + empty blocks Sha256Hash firstHash = lastBlock.getHash(); int height = nextHeight-1; nextHeight = heightAfter1001; lastBlock = b1001; for (int i = 0; i < blockCountAfter1001; i++) { Block block = createNextBlock(lastBlock, nextHeight++, null, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, block, true, false, firstHash, height, "post-b1001 empty reorg block " + i + "/" + blockCountAfter1001)); lastBlock = block; } // Try to spend from the other chain Block b1002 = createNextBlock(lastBlock, nextHeight, null, null); { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_TRUE}, new TransactionOutPoint(params, 0, hashesToSpend.get(0)))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); b1002.addTransaction(tx); } b1002.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1002, false, true, firstHash, height, "b1002")); // Now actually reorg Block b1003 = createNextBlock(lastBlock, nextHeight, null, null); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1003, true, false, b1003.getHash(), nextHeight, "b1003")); // Now try to spend again Block b1004 = createNextBlock(b1003, nextHeight+1, null, null); { Transaction tx = new Transaction(params); tx.addInput(new TransactionInput(params, tx, new byte[] {OP_TRUE}, new TransactionOutPoint(params, 0, hashesToSpend.get(0)))); tx.addOutput(new TransactionOutput(params, tx, BigInteger.ZERO, new byte[] { OP_TRUE })); b1004.addTransaction(tx); } b1004.solve(); blocks.add(new BlockAndValidity(blockToHeightMap, hashHeaderMap, b1004, false, true, b1003.getHash(), nextHeight, "b1004")); ret.maximumReorgBlockCount = Math.max(ret.maximumReorgBlockCount, blockCountAfter1001); } if (outStream != null) outStream.close(); // (finally) return the created chain return ret; }
diff --git a/app/Global.java b/app/Global.java index 27f54b2..6260460 100644 --- a/app/Global.java +++ b/app/Global.java @@ -1,20 +1,32 @@ import play.*; import models.*; public class Global extends GlobalSettings { @Override public void onStart(Application app) { Logger.info("Application has started"); - Substance substance = new Substance(); - substance.name = "Новое вещество"; - substance.s_pdk = 1.35; - substance.k = 1.75; - substance.save(); + if(Substance.all().size()==0){ + Substance substance = new Substance(); + substance.name = "Первое вещество"; + substance.s_pdk = 1.35; + substance.k = 1.75; + substance.save(); + Substance substance2 = new Substance(); + substance2.name = "Второе вещество"; + substance2.s_pdk = 1.35; + substance2.k = 1.75; + substance2.save(); + Substance substance3 = new Substance(); + substance3.name = "Третье вещество"; + substance3.s_pdk = 1.35; + substance3.k = 1.75; + substance3.save(); + } } @Override public void onStop(Application app) { Logger.info("Application shutdown..."); } }
true
true
public void onStart(Application app) { Logger.info("Application has started"); Substance substance = new Substance(); substance.name = "Новое вещество"; substance.s_pdk = 1.35; substance.k = 1.75; substance.save(); }
public void onStart(Application app) { Logger.info("Application has started"); if(Substance.all().size()==0){ Substance substance = new Substance(); substance.name = "Первое вещество"; substance.s_pdk = 1.35; substance.k = 1.75; substance.save(); Substance substance2 = new Substance(); substance2.name = "Второе вещество"; substance2.s_pdk = 1.35; substance2.k = 1.75; substance2.save(); Substance substance3 = new Substance(); substance3.name = "Третье вещество"; substance3.s_pdk = 1.35; substance3.k = 1.75; substance3.save(); } }
diff --git a/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java b/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java index da48ee1e..32420e91 100644 --- a/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java +++ b/52n-sos-importer/52n-sos-importer-feeder/src/main/java/org/n52/sos/importer/feeder/model/Timestamp.java @@ -1,130 +1,130 @@ /** * Copyright (C) 2012 * by 52North Initiative for Geospatial Open Source Software GmbH * * Contact: Andreas Wytzisk * 52 North Initiative for Geospatial Open Source Software GmbH * Martin-Luther-King-Weg 24 * 48155 Muenster, Germany * [email protected] * * This program is free software; you can redistribute and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * * This program is distributed WITHOUT ANY WARRANTY; even without the implied * WARRANTY OF MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program (see gnu-gpl v2.txt). If not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or * visit the Free Software Foundation web page, http://www.fsf.org. */ package org.n52.sos.importer.feeder.model; /** * @author <a href="mailto:[email protected]">Eike Hinderk J&uuml;rrens</a> */ public class Timestamp { private short year = Short.MIN_VALUE; private byte month = Byte.MIN_VALUE; private byte day = Byte.MIN_VALUE; private byte hour = Byte.MIN_VALUE; private byte minute = Byte.MIN_VALUE; private byte seconds = Byte.MIN_VALUE; private byte timezone = Byte.MIN_VALUE; @Override public String toString() { StringBuffer ts = new StringBuffer(25); // <- yyyy-mm-ddThh:mm:ss+hh:mm if (year != Short.MIN_VALUE) { ts.append(year); if (month != Byte.MIN_VALUE) { ts.append("-"); } } if (month != Byte.MIN_VALUE) { ts.append(month<10?"0"+month:month); if (day != Byte.MIN_VALUE) { ts.append("-"); } } if (day != Byte.MIN_VALUE) { ts.append(day<10?"0"+day:day); } if ( (year != Short.MIN_VALUE || month != Byte.MIN_VALUE || day != Byte.MIN_VALUE ) && (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) { ts.append("T"); } if (hour != Byte.MIN_VALUE) { ts.append(hour<10?"0"+hour:hour); if (minute != Byte.MIN_VALUE) { ts.append(":"); } } if (minute != Byte.MIN_VALUE) { ts.append(minute<10?"0"+minute:minute); if (seconds != Byte.MIN_VALUE) { - ts.append(""); + ts.append(":"); } } if (seconds != Byte.MIN_VALUE) { ts.append(seconds<10?"0"+seconds:seconds); } if (timezone != Byte.MIN_VALUE && (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) { ts.append(convertTimeZone(timezone)); } return ts.toString(); } private String convertTimeZone(int timeZone) { if (timeZone >= 0) { if (timeZone >= 10) { return "+" + timeZone + ":00"; } else { return "+0" + timeZone + ":00"; } } else { if (timeZone <= -10) { return timeZone + ":00"; } else { return "-0" + Math.abs(timeZone) + ":00"; } } } public void setYear(short year) { this.year = year; } public void setMonth(byte month) { this.month = month; } public void setDay(byte day) { this.day = day; } public void setHour(byte hour) { this.hour = hour; } public void setMinute(byte minute) { this.minute = minute; } public void setSeconds(byte seconds) { this.seconds = seconds; } public void setTimezone(byte timezone) { this.timezone = timezone; } }
true
true
public String toString() { StringBuffer ts = new StringBuffer(25); // <- yyyy-mm-ddThh:mm:ss+hh:mm if (year != Short.MIN_VALUE) { ts.append(year); if (month != Byte.MIN_VALUE) { ts.append("-"); } } if (month != Byte.MIN_VALUE) { ts.append(month<10?"0"+month:month); if (day != Byte.MIN_VALUE) { ts.append("-"); } } if (day != Byte.MIN_VALUE) { ts.append(day<10?"0"+day:day); } if ( (year != Short.MIN_VALUE || month != Byte.MIN_VALUE || day != Byte.MIN_VALUE ) && (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) { ts.append("T"); } if (hour != Byte.MIN_VALUE) { ts.append(hour<10?"0"+hour:hour); if (minute != Byte.MIN_VALUE) { ts.append(":"); } } if (minute != Byte.MIN_VALUE) { ts.append(minute<10?"0"+minute:minute); if (seconds != Byte.MIN_VALUE) { ts.append(""); } } if (seconds != Byte.MIN_VALUE) { ts.append(seconds<10?"0"+seconds:seconds); } if (timezone != Byte.MIN_VALUE && (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) { ts.append(convertTimeZone(timezone)); } return ts.toString(); }
public String toString() { StringBuffer ts = new StringBuffer(25); // <- yyyy-mm-ddThh:mm:ss+hh:mm if (year != Short.MIN_VALUE) { ts.append(year); if (month != Byte.MIN_VALUE) { ts.append("-"); } } if (month != Byte.MIN_VALUE) { ts.append(month<10?"0"+month:month); if (day != Byte.MIN_VALUE) { ts.append("-"); } } if (day != Byte.MIN_VALUE) { ts.append(day<10?"0"+day:day); } if ( (year != Short.MIN_VALUE || month != Byte.MIN_VALUE || day != Byte.MIN_VALUE ) && (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) { ts.append("T"); } if (hour != Byte.MIN_VALUE) { ts.append(hour<10?"0"+hour:hour); if (minute != Byte.MIN_VALUE) { ts.append(":"); } } if (minute != Byte.MIN_VALUE) { ts.append(minute<10?"0"+minute:minute); if (seconds != Byte.MIN_VALUE) { ts.append(":"); } } if (seconds != Byte.MIN_VALUE) { ts.append(seconds<10?"0"+seconds:seconds); } if (timezone != Byte.MIN_VALUE && (hour != Byte.MIN_VALUE || minute != Byte.MIN_VALUE || seconds != Byte.MIN_VALUE)) { ts.append(convertTimeZone(timezone)); } return ts.toString(); }
diff --git a/src/core/java/org/wyona/yanel/core/source/SourceResolver.java b/src/core/java/org/wyona/yanel/core/source/SourceResolver.java index 1c5477146..070b1bc02 100644 --- a/src/core/java/org/wyona/yanel/core/source/SourceResolver.java +++ b/src/core/java/org/wyona/yanel/core/source/SourceResolver.java @@ -1,104 +1,104 @@ package org.wyona.yanel.core.source; import java.util.HashMap; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.apache.log4j.Logger; import org.wyona.yanel.core.Resource; import org.wyona.commons.io.PathUtil; /** * Resolves a URI to a Source. * This class just checks the scheme and delegates to the scheme-specific resolver. * * TODO: allow to configure schemes in a config file */ public class SourceResolver implements URIResolver { private static final Logger log = Logger.getLogger(SourceResolver.class); private HashMap<String, URIResolver> resolvers; private Resource resource; public SourceResolver(Resource resource) { this.resource = resource; this.resolvers = new HashMap<String, URIResolver>(); } public Source resolve(String uri, String base) throws SourceException { if (log.isDebugEnabled()) { log.debug("URI to be resolved: " + uri); log.debug("Base: "+ base); } // NOTE: One cannot use ":/" in order to find the protocol/scheme, because one can also specifiy the realm id and repository id, for example: yanelrepo:REALM_ID:REPO_ID:/foo/bar.gif int colonIndex = uri.indexOf(":"); //int colonIndex = uri.indexOf(":/"); String uriScheme = ""; if (colonIndex <= 0) {//Check for scheme in URI, if true, then URI has no scheme - //log.error("DEBUG: URI has no scheme: " + uri); + if (log.isDebugEnabled()) log.debug("URI <" + uri + "> has no scheme."); if (base != null) { int colBaseIndex = base.indexOf(":"); //int colBaseIndex = base.indexOf(":/"); if(colBaseIndex <=0 ){//Check for scheme in Base throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base } uriScheme = base.substring(0, colBaseIndex); uri = PathUtil.concat(base,uri); - //log.error("DEBUG: Use scheme of base: " + uriScheme + ", " + uri); + if (log.isDebugEnabled()) log.debug("Base URI <" + uri + "> has scheme \"" + uriScheme + "\"."); } else { log.error("Neither scheme for URI nor base specified for URI: " + uri); throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base } } else {//uri contains scheme uriScheme = uri.substring(0, colonIndex); - //log.error("DEBUG: URI has scheme: " + uriScheme + ", " + uri); + if (log.isDebugEnabled()) log.debug("URI <" + uri + "> has scheme \"" + uriScheme + "\"."); } URIResolver resolver = getResolver(uriScheme); if (resolver != null) { try { // TODO: What shall be used as base?! Source s = resolver.resolve(uri, base); s.setSystemId(uri); return s; } catch (TransformerException e) { throw new SourceException(e.getMessage(), e); } } throw new SourceException("No resolver could be loaded for scheme: " + uriScheme); } private URIResolver getResolver(String scheme) { URIResolver resolver = null; if (this.resolvers.containsKey(scheme)) { resolver = this.resolvers.get(scheme); } else { if (scheme.equals("yanelresource")) { resolver = new ResourceResolver(this.resource); this.resolvers.put(scheme, resolver); } else if (scheme.equals("yanelrepo")) { resolver = new YanelRepositoryResolver(this.resource); this.resolvers.put(scheme, resolver); //resolver = new RepositoryResolver(this.resource); } else if (scheme.equals("http")) { resolver = new HttpResolver(this.resource); this.resolvers.put(scheme, resolver); } else if (scheme.equals("rthtdocs")) { resolver = new RTHtdocsResolver(this.resource); this.resolvers.put(scheme, resolver); } else if (scheme.equals("rtyanelhtdocs")) { resolver = new RTYanelHtdocsResolver(this.resource); this.resolvers.put(scheme, resolver); } else if (scheme.equals("yanelhtdocs")) { resolver = new YanelHtdocsResolver(this.resource); this.resolvers.put(scheme, resolver); } } return resolver; } }
false
true
public Source resolve(String uri, String base) throws SourceException { if (log.isDebugEnabled()) { log.debug("URI to be resolved: " + uri); log.debug("Base: "+ base); } // NOTE: One cannot use ":/" in order to find the protocol/scheme, because one can also specifiy the realm id and repository id, for example: yanelrepo:REALM_ID:REPO_ID:/foo/bar.gif int colonIndex = uri.indexOf(":"); //int colonIndex = uri.indexOf(":/"); String uriScheme = ""; if (colonIndex <= 0) {//Check for scheme in URI, if true, then URI has no scheme //log.error("DEBUG: URI has no scheme: " + uri); if (base != null) { int colBaseIndex = base.indexOf(":"); //int colBaseIndex = base.indexOf(":/"); if(colBaseIndex <=0 ){//Check for scheme in Base throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base } uriScheme = base.substring(0, colBaseIndex); uri = PathUtil.concat(base,uri); //log.error("DEBUG: Use scheme of base: " + uriScheme + ", " + uri); } else { log.error("Neither scheme for URI nor base specified for URI: " + uri); throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base } } else {//uri contains scheme uriScheme = uri.substring(0, colonIndex); //log.error("DEBUG: URI has scheme: " + uriScheme + ", " + uri); } URIResolver resolver = getResolver(uriScheme); if (resolver != null) { try { // TODO: What shall be used as base?! Source s = resolver.resolve(uri, base); s.setSystemId(uri); return s; } catch (TransformerException e) { throw new SourceException(e.getMessage(), e); } } throw new SourceException("No resolver could be loaded for scheme: " + uriScheme); }
public Source resolve(String uri, String base) throws SourceException { if (log.isDebugEnabled()) { log.debug("URI to be resolved: " + uri); log.debug("Base: "+ base); } // NOTE: One cannot use ":/" in order to find the protocol/scheme, because one can also specifiy the realm id and repository id, for example: yanelrepo:REALM_ID:REPO_ID:/foo/bar.gif int colonIndex = uri.indexOf(":"); //int colonIndex = uri.indexOf(":/"); String uriScheme = ""; if (colonIndex <= 0) {//Check for scheme in URI, if true, then URI has no scheme if (log.isDebugEnabled()) log.debug("URI <" + uri + "> has no scheme."); if (base != null) { int colBaseIndex = base.indexOf(":"); //int colBaseIndex = base.indexOf(":/"); if(colBaseIndex <=0 ){//Check for scheme in Base throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base } uriScheme = base.substring(0, colBaseIndex); uri = PathUtil.concat(base,uri); if (log.isDebugEnabled()) log.debug("Base URI <" + uri + "> has scheme \"" + uriScheme + "\"."); } else { log.error("Neither scheme for URI nor base specified for URI: " + uri); throw new SourceException("invalid url syntax (missing scheme): " + uri);//no scheme found in uri and base } } else {//uri contains scheme uriScheme = uri.substring(0, colonIndex); if (log.isDebugEnabled()) log.debug("URI <" + uri + "> has scheme \"" + uriScheme + "\"."); } URIResolver resolver = getResolver(uriScheme); if (resolver != null) { try { // TODO: What shall be used as base?! Source s = resolver.resolve(uri, base); s.setSystemId(uri); return s; } catch (TransformerException e) { throw new SourceException(e.getMessage(), e); } } throw new SourceException("No resolver could be loaded for scheme: " + uriScheme); }
diff --git a/apps/animaldb/plugins/fillanimaldb/FillAnimalDB.java b/apps/animaldb/plugins/fillanimaldb/FillAnimalDB.java index 195676d78..5fd0efab6 100644 --- a/apps/animaldb/plugins/fillanimaldb/FillAnimalDB.java +++ b/apps/animaldb/plugins/fillanimaldb/FillAnimalDB.java @@ -1,668 +1,668 @@ package plugins.fillanimaldb; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.molgenis.auth.MolgenisGroup; import org.molgenis.core.MolgenisEntity; import org.molgenis.core.Ontology; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; import org.molgenis.framework.db.Query; import org.molgenis.framework.db.QueryRule; import org.molgenis.framework.db.QueryRule.Operator; import org.molgenis.framework.security.Login; import org.molgenis.organization.Investigation; import org.molgenis.pheno.ObservedValue; import org.molgenis.util.HandleRequestDelegationException; import app.DatabaseFactory; import commonservice.CommonService; public class FillAnimalDB { private Database db; private CommonService ct; public FillAnimalDB() throws Exception { db = DatabaseFactory.create("handwritten/apps/org/molgenis/animaldb/animaldb.properties"); ct = CommonService.getInstance(); ct.setDatabase(db); } public FillAnimalDB(Database db) throws Exception { this.db = db; ct = CommonService.getInstance(); ct.setDatabase(this.db); } public void populateDB(Login login) throws Exception, HandleRequestDelegationException,DatabaseException, ParseException, IOException { // Login as admin to have enough rights to do this login.login(db, "admin", "admin"); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); Logger logger = Logger.getLogger("FillAnimalDB"); logger.info("Start filling the database with factory defaults for AnimalDB."); // Make investigation logger.info("Create investigation"); Investigation inv = new Investigation(); inv.setName("System"); inv.setOwns_Id(login.getUserId()); int allUsersId = db.find(MolgenisGroup.class, new QueryRule(MolgenisGroup.NAME, Operator.EQUALS, "AllUsers")).get(0).getId(); inv.setCanRead_Id(allUsersId); db.add(inv); int invid = inv.getId(); // Make ontology 'Units' logger.info("Add ontology entries"); Ontology ont = new Ontology(); ont.setName("Units"); db.add(ont); Query<Ontology> q = db.query(Ontology.class); q.eq(Ontology.NAME, "Units"); List<Ontology> ontList = q.find(); int ontid = ontList.get(0).getId(); // Make ontology term entries int targetlinkUnitId = ct.makeOntologyTerm("TargetLink", ontid, "Link to an entry in one of the ObservationTarget tables."); int gramUnitId = ct.makeOntologyTerm("Gram", ontid, "SI unit for mass."); int booleanUnitId = ct.makeOntologyTerm("Boolean", ontid, "True (1) or false (0)."); int datetimeUnitId = ct.makeOntologyTerm("Datetime", ontid, "Timestamp."); int numberUnitId = ct.makeOntologyTerm("Number", ontid, "A discrete number greater than 0."); int stringUnitId = ct.makeOntologyTerm("String", ontid, "Short piece of text."); logger.info("Create measurements"); MolgenisEntity individual = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Individual").find().get(0); MolgenisEntity panel = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Panel").find().get(0); MolgenisEntity location = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Location").find().get(0); // Make features // Because of the MeasurementDecorator a basic protocol with the name Set<MeasurementName> will be auto-generated ct.makeMeasurement(invid, "TypeOfGroup", stringUnitId, null, null, false, "string", "To label a group of targets.", login.getUserId()); ct.makeMeasurement(invid, "Species", targetlinkUnitId, panel, "Species", false, "xref", "To set the species of an animal.", login.getUserId()); ct.makeMeasurement(invid, "Sex", targetlinkUnitId, panel, "Sex", false, "xref", "To set the sex of an animal.", login.getUserId()); ct.makeMeasurement(invid, "Location", targetlinkUnitId, location, null, false, "xref", "To set the location of a target.", login.getUserId()); ct.makeMeasurement(invid, "Weight", gramUnitId, null, null, true, "decimal", "To set the weight of a target.", login.getUserId()); ct.makeMeasurement(invid, "Father", targetlinkUnitId, individual, null, false, "xref", "To link a parent-group to an animal that may be a father.", login.getUserId()); ct.makeMeasurement(invid, "Mother", targetlinkUnitId, individual, null, false, "xref", "To link a parent-group to an animal that may be a mother.", login.getUserId()); ct.makeMeasurement(invid, "Certain", booleanUnitId, null, null, false, "bool", "To indicate whether the parenthood of an animal regarding a parent-group is certain.", login.getUserId()); ct.makeMeasurement(invid, "Group", targetlinkUnitId, panel, null, false, "xref", "To add a target to a panel.", login.getUserId()); ct.makeMeasurement(invid, "Parentgroup", targetlinkUnitId, panel, "Parentgroup", false, "xref", "To link a litter to a parent-group.", login.getUserId()); ct.makeMeasurement(invid, "DateOfBirth", datetimeUnitId, null, null, true, "datetime", "To set a target's or a litter's date of birth.", login.getUserId()); ct.makeMeasurement(invid, "Size", numberUnitId, null, null, true, "int", "To set the size of a target-group, for instance a litter.", login.getUserId()); ct.makeMeasurement(invid, "WeanSize", numberUnitId, null, null, true, "int", "To set the wean size of a litter.", login.getUserId()); ct.makeMeasurement(invid, "WeanSizeFemale", numberUnitId, null, null, true, "int", "To set the number of females in a litter when weaning.", login.getUserId()); ct.makeMeasurement(invid, "Street", stringUnitId, null, null, false, "string", "To set the street part of an address.", login.getUserId()); ct.makeMeasurement(invid, "Housenumber", numberUnitId, null, null, false, "int", "To set the house-number part of an address.", login.getUserId()); ct.makeMeasurement(invid, "City", stringUnitId, null, null, false, "string", "To set the city part of an address.", login.getUserId()); ct.makeMeasurement(invid, "CustomID", stringUnitId, null, null, false, "string", "To set a target's custom ID.", login.getUserId()); ct.makeMeasurement(invid, "WeanDate", datetimeUnitId, null, null, true, "datetime", "To set a litter's or target's date of weaning.", login.getUserId()); ct.makeMeasurement(invid, "GenotypeDate", datetimeUnitId, null, null, true, "datetime", "To set a litter's date of genotyping.", login.getUserId()); ct.makeMeasurement(invid, "CageCleanDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of cage cleaning.", login.getUserId()); ct.makeMeasurement(invid, "DeathDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of death.", login.getUserId()); ct.makeMeasurement(invid, "Active", stringUnitId, null, null, false, "string", "To register a target's activity span.", login.getUserId()); ct.makeMeasurement(invid, "Background", targetlinkUnitId, panel, "Background", false, "xref", "To set an animal's genotypic background.", login.getUserId()); ct.makeMeasurement(invid, "Source", targetlinkUnitId, panel, "Source", false, "xref", "To link an animal or a breeding line to a source.", login.getUserId()); ct.makeMeasurement(invid, "Line", targetlinkUnitId, panel, "Link", false, "xref", "To link a parentgroup to a breeding line.", login.getUserId()); ct.makeMeasurement(invid, "SourceType", stringUnitId, null, null, false, "string", "To set the type of an animal source (used in VWA Report 4).", login.getUserId()); ct.makeMeasurement(invid, "SourceTypeSubproject", stringUnitId, null, null, false, "string", "To set the animal's source type, when it enters a DEC subproject (used in VWA Report 5).", login.getUserId()); ct.makeMeasurement(invid, "ParticipantGroup", stringUnitId, null, null, false, "string", "To set the participant group an animal is considered part of.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBRemarks", stringUnitId, null, null, false, "string", "To store remarks about the animal in the animal table, from the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "Remark", stringUnitId, null, null, false, "string", "To store remarks about the animal.", login.getUserId()); ct.makeMeasurement(invid, "Litter", targetlinkUnitId, panel, "Litter", false, "xref", "To link an animal to a litter.", login.getUserId()); ct.makeMeasurement(invid, "ExperimentNr", stringUnitId, null, null, false, "string", "To set a (sub)experiment's number.", login.getUserId()); - ct.makeMeasurement(invid, "ExperimentTitle", stringUnitId, null, null, false, "string", "To set a (sub)experiment's number.", login.getUserId()); + ct.makeMeasurement(invid, "ExperimentTitle", stringUnitId, null, null, false, "string", "To set a (sub)experiment's title.", login.getUserId()); ct.makeMeasurement(invid, "DecSubprojectApplicationPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the (sub)experiment's DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecApplicationPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecApprovalPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the DEC approval.", login.getUserId()); ct.makeMeasurement(invid, "DecApplication", targetlinkUnitId, panel, "DecApplication", false, "xref", "To link a DEC subproject (experiment) to a DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecNr", stringUnitId, null, null, false, "string", "To set a DEC application's DEC number.", login.getUserId()); ct.makeMeasurement(invid, "DecTitle", stringUnitId, null, null, false, "string", "To set the title of a DEC project.", login.getUserId()); ct.makeMeasurement(invid, "DecApplicantId", stringUnitId, null, null, false, "string", "To link a DEC application to a user with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "Anaesthesia", stringUnitId, null, null, false, "string", "To set the Anaesthesia value of (an animal in) an experiment.", login.getUserId()); ct.makeMeasurement(invid, "PainManagement", stringUnitId, null, null, false, "string", "To set the PainManagement value of (an animal in) an experiment.", login.getUserId()); ct.makeMeasurement(invid, "AnimalEndStatus", stringUnitId, null, null, false, "string", "To set the AnimalEndStatus value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "LawDef", stringUnitId, null, null, false, "string", "To set the Lawdef value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ToxRes", stringUnitId, null, null, false, "string", "To set the ToxRes value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "SpecialTechn", stringUnitId, null, null, false, "string", "To set the SpecialTechn value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Goal", stringUnitId, null, null, false, "string", "To set the Goal of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Concern", stringUnitId, null, null, false, "string", "To set the Concern value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "FieldBiology", booleanUnitId, null, null, false, "bool", "To indicate whether a DEC application is related to field biology.", login.getUserId()); ct.makeMeasurement(invid, "ExpectedDiscomfort", stringUnitId, null, null, false, "string", "To set the expected discomfort of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ActualDiscomfort", stringUnitId, null, null, false, "string", "To set the actual discomfort of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "AnimalType", stringUnitId, null, null, false, "string", "To set the animal type.", login.getUserId()); ct.makeMeasurement(invid, "ExpectedAnimalEndStatus", stringUnitId, null, null, false, "string", "To set the expected end status of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ActualAnimalEndStatus", stringUnitId, null, null, false, "string", "To set the actual end status of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Experiment", targetlinkUnitId, panel, "Experiment", false, "xref", "To link an animal to a DEC subproject (experiment).", login.getUserId()); ct.makeMeasurement(invid, "FromExperiment", targetlinkUnitId, panel, "Experiment", false, "xref", "To remove an animal from a DEC subproject (experiment).", login.getUserId()); ct.makeMeasurement(invid, "GeneName", stringUnitId, null, null, false, "string", "The name of a gene that may or may not be present in an animal.", login.getUserId()); ct.makeMeasurement(invid, "GeneState", stringUnitId, null, null, false, "string", "To indicate whether an animal is homo- or heterozygous for a gene.", login.getUserId()); ct.makeMeasurement(invid, "VWASpecies", stringUnitId, null, null, false, "string", "To give a species the name the VWA uses for it.", login.getUserId()); ct.makeMeasurement(invid, "LatinSpecies", stringUnitId, null, null, false, "string", "To give a species its scientific (Latin) name.", login.getUserId()); ct.makeMeasurement(invid, "StartDate", datetimeUnitId, null, null, true, "datetime", "To set a (sub)project's start date.", login.getUserId()); ct.makeMeasurement(invid, "EndDate", datetimeUnitId, null, null, true, "datetime", "To set a (sub)project's end date.", login.getUserId()); ct.makeMeasurement(invid, "Removal", stringUnitId, null, null, false, "string", "To register an animal's removal.", login.getUserId()); ct.makeMeasurement(invid, "Article", numberUnitId, null, null, false, "int", "To set an actor's Article status according to the Law, e.g. Article 9.", login.getUserId()); ct.makeMeasurement(invid, "MolgenisUserId", numberUnitId, null, null, false, "int", "To set an actor's corresponding MolgenisUser ID.", login.getUserId()); // For importing old AnimalDB ct.makeMeasurement(invid, "OldAnimalDBAnimalID", stringUnitId, null, null, false, "string", "To set an animal's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBAnimalCustomID", stringUnitId, null, null, false, "string", "To set an animal's Custom ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBLocationID", stringUnitId, null, null, false, "string", "To set a location's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBLitterID", stringUnitId, null, null, false, "string", "To link an animal to a litter with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBExperimentID", stringUnitId, null, null, false, "string", "To set an experiment's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBDecApplicationID", stringUnitId, null, null, false, "string", "To link an experiment to a DEC application with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBBroughtinDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of arrival in the system/ on the location in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBExperimentalManipulationRemark", stringUnitId, null, null, false, "string", "To store Experiment remarks about the animal, from the Experimental manipulation event, from the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBPresetID", stringUnitId, null, null, false, "string", "To link a targetgroup to a preset this ID in the old version of AnimalDB.", login.getUserId()); // For importing old Uli Eisel DB ct.makeMeasurement(invid, "OldUliDbId", stringUnitId, null, null, false, "string", "To set an animal's ID in the old Uli Eisel DB.", login.getUserId()); - ct.makeMeasurement(invid, "OldUliDbKuerzel", stringUnitId, null, null, false, "string", "To set an animal's 'K�rzel' in the old Uli Eisel DB.", login.getUserId()); + ct.makeMeasurement(invid, "OldUliDbKuerzel", stringUnitId, null, null, false, "string", "To set an animal's 'Kürzel' in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbAktenzeichen", stringUnitId, null, null, false, "string", "To set an animal's 'Aktenzeichen' in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbExperimentator", stringUnitId, null, null, false, "string", "To set an animal's experimenter in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbTierschutzrecht", stringUnitId, null, null, false, "string", "To set an animal's 'Tierschutzrecht' (~ DEC subproject Goal) in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "Color", stringUnitId, null, null, false, "string", "To set an animal's color.", login.getUserId()); ct.makeMeasurement(invid, "Earmark", stringUnitId, null, null, false, "string", "To set an animal's earmark.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbMotherInfo", stringUnitId, null, null, false, "string", "To set an animal's mother info in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbFatherInfo", stringUnitId, null, null, false, "string", "To set an animal's father info in the old Uli Eisel DB.", login.getUserId()); logger.info("Add codes"); // Codes for Subprojects ct.makeCode("A", "A", "ExperimentNr"); ct.makeCode("B", "B", "ExperimentNr"); ct.makeCode("C", "C", "ExperimentNr"); ct.makeCode("D", "D", "ExperimentNr"); ct.makeCode("E", "E", "ExperimentNr"); ct.makeCode("F", "F", "ExperimentNr"); ct.makeCode("G", "G", "ExperimentNr"); ct.makeCode("H", "H", "ExperimentNr"); ct.makeCode("I", "I", "ExperimentNr"); ct.makeCode("J", "J", "ExperimentNr"); ct.makeCode("K", "K", "ExperimentNr"); ct.makeCode("L", "L", "ExperimentNr"); ct.makeCode("M", "M", "ExperimentNr"); ct.makeCode("N", "N", "ExperimentNr"); ct.makeCode("O", "O", "ExperimentNr"); ct.makeCode("P", "P", "ExperimentNr"); ct.makeCode("Q", "Q", "ExperimentNr"); ct.makeCode("R", "R", "ExperimentNr"); ct.makeCode("S", "S", "ExperimentNr"); ct.makeCode("T", "T", "ExperimentNr"); ct.makeCode("U", "U", "ExperimentNr"); ct.makeCode("V", "V", "ExperimentNr"); ct.makeCode("W", "W", "ExperimentNr"); ct.makeCode("X", "X", "ExperimentNr"); ct.makeCode("Y", "Y", "ExperimentNr"); ct.makeCode("Z", "Z", "ExperimentNr"); // Codes for SourceType ct.makeCode("1-1", "Eigen fok binnen uw organisatorische werkeenheid", "SourceType"); ct.makeCode("1-2", "Andere organisatorische werkeenheid vd instelling", "SourceType"); ct.makeCode("1-3", "Geregistreerde fok/aflevering in Nederland", "SourceType"); ct.makeCode("2", "Van EU-lid-staten", "SourceType"); ct.makeCode("3", "Niet-geregistreerde fok/afl in Nederland", "SourceType"); ct.makeCode("4", "Niet-geregistreerde fok/afl in andere EU-lid-staat", "SourceType"); ct.makeCode("5", "Andere herkomst", "SourceType"); // Codes for SourceTypeSubproject ct.makeCode("1", "Geregistreerde fok/aflevering in Nederland", "SourceTypeSubproject"); ct.makeCode("2", "Van EU-lid-staten", "SourceTypeSubproject"); ct.makeCode("3", "Niet-geregistreerde fok/afl in Nederland", "SourceTypeSubproject"); ct.makeCode("4", "Niet-geregistreerde fok/afl in andere EU-lid-staat", "SourceTypeSubproject"); ct.makeCode("5", "Andere herkomst", "SourceTypeSubproject"); ct.makeCode("6", "Hergebruik eerste maal in het registratiejaar", "SourceTypeSubproject"); ct.makeCode("7", "Hergebruik tweede, derde enz. maal in het registratiejaar", "SourceTypeSubproject"); // Codes for ParticipantGroup ct.makeCode("04", "Chrono- en gedragsbiologie", "ParticipantGroup"); ct.makeCode("06", "Plantenbiologie", "ParticipantGroup"); ct.makeCode("07", "Dierfysiologie", "ParticipantGroup"); ct.makeCode("Klinische Farmacologie (no code yet)", "Klinische Farmacologie", "ParticipantGroup"); // Codes for Anaestheasia ct.makeCode("1", "A. Is niet toegepast (geen aanleiding)", "Anaesthesia"); ct.makeCode("2", "B. Is niet toegepast (onverenigbaar proef)", "Anaesthesia"); ct.makeCode("3", "C. Is niet toegepast (praktisch onuitvoerbaar)", "Anaesthesia"); ct.makeCode("4", "D. Is wel toegepast", "Anaesthesia"); // Codes for PainManagement ct.makeCode("1", "A. Is niet toegepast (geen aanleiding)", "PainManagement"); ct.makeCode("2", "B. Is niet toegepast (onverenigbaar proef)", "PainManagement"); ct.makeCode("3", "C. Is niet toegepast (praktisch onuitvoerbaar)", "PainManagement"); ct.makeCode("4", "D. Is wel toegepast", "PainManagement"); // Codes for AnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "AnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "AnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "AnimalEndStatus"); // Codes for ExpectedAnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "ExpectedAnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "ExpectedAnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "ExpectedAnimalEndStatus"); // Codes for ActualAnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "ActualAnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "ActualAnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "ActualAnimalEndStatus"); // Codes for LawDef ct.makeCode("1", "A. Geen wettelijke bepaling", "LawDef"); ct.makeCode("2", "B. Uitsluitend Nederland", "LawDef"); ct.makeCode("3", "C. Uitsluitend EU-lidstaten", "LawDef"); ct.makeCode("4", "D. Uitsluitend Lidstaten Raad v. Eur.", "LawDef"); ct.makeCode("5", "E. Uitsluitend Europese landen", "LawDef"); ct.makeCode("6", "F. Ander wettelijke bepaling", "LawDef"); ct.makeCode("7", "G. Combinatie van B. C. D. E. en F", "LawDef"); // Codes for ToxRes ct.makeCode("01", "A. Geen toxicologisch onderzoek", "ToxRes"); ct.makeCode("02", "B. Acuut tox. met letaliteit", "ToxRes"); ct.makeCode("03", "C. Acuut tox. LD50/LC50", "ToxRes"); ct.makeCode("04", "D. Overige acuut tox. (geen letaliteit)", "ToxRes"); ct.makeCode("05", "E. Sub-acuut tox.", "ToxRes"); ct.makeCode("06", "F. Sub-chronisch en chronische tox.", "ToxRes"); ct.makeCode("07", "G. Carcinogeniteitsonderzoek", "ToxRes"); ct.makeCode("08", "H. Mutageniteitsonderzoek", "ToxRes"); ct.makeCode("09", "I. Teratogeniteitsonderz. (segment II)", "ToxRes"); ct.makeCode("10", "J. Reproductie-onderzoek (segment 1 en III)", "ToxRes"); ct.makeCode("11", "K. Overige toxiciteitsonderzoek", "ToxRes"); // Codes for SpecialTechn ct.makeCode("01", "A. Geen van deze technieken/ingrepen", "SpecialTechn"); ct.makeCode("02", "B. Doden zonder voorafgaande handelingen", "SpecialTechn"); ct.makeCode("03", "C. Curare-achtige stoffen zonder anesthesie", "SpecialTechn"); ct.makeCode("04", "D. Technieken/ingrepen verkrijgen transgene dieren", "SpecialTechn"); ct.makeCode("05", "E. Toedienen van mogelijk irriterende stoffen via luchtwegen", "SpecialTechn"); ct.makeCode("06", "E. Toedienen van mogelijk irriterende stoffen op het oog", "SpecialTechn"); ct.makeCode("07", "E. Toedienen van mogelijk irriterende stoffen op andere slijmvliezen of huid", "SpecialTechn"); ct.makeCode("08", "F. Huidsensibilisaties", "SpecialTechn"); ct.makeCode("09", "G. Bestraling, met schadelijke effecten", "SpecialTechn"); ct.makeCode("10", "H. Traumatiserende fysische/chemische prikkels (CZ)", "SpecialTechn"); ct.makeCode("11", "I. Traumatiserende psychische prikkels", "SpecialTechn"); ct.makeCode("12", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van ontstekingen/infecties", "SpecialTechn"); ct.makeCode("13", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van verbrand./fract. of letsel (traum.)", "SpecialTechn"); ct.makeCode("14", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van poly- en monoclonale antistoffen", "SpecialTechn"); ct.makeCode("15", "J. Technieken/ingrepen anders dan C t/m H, gericht: produceren van monoclonale antistoffen", "SpecialTechn"); ct.makeCode("16", "K. Meer dan een onder G t/m J vermelde mogelijkheden", "SpecialTechn"); ct.makeCode("17", "L. Gefokt met ongerief", "SpecialTechn"); // Codes for Concern ct.makeCode("1", "A. Gezondheid/voed. ja", "Concern"); ct.makeCode("2", "B. Gezondheid/voed. nee", "Concern"); // Codes for Goal ct.makeCode("1", "A. Onderzoek m.b.t. de mens: ontw. sera vaccins/biol.produkten", "Goal"); ct.makeCode("2", "A. Onderzoek m.b.t. de mens: prod./contr./ijking sera vaccins/biol. producten", "Goal"); ct.makeCode("3", "A. Onderzoek m.b.t. de mens: ontw. geneesmiddelen", "Goal"); ct.makeCode("4", "A. Onderzoek m.b.t. de mens: prod./contr./ijking geneesmiddelen", "Goal"); ct.makeCode("5", "A. Onderzoek m.b.t. de mens: ontw. med. hulpmiddelen/ toepassingen", "Goal"); ct.makeCode("6", "A. Onderzoek m.b.t. de mens: prod./contr./ijking med.hulpm./toepassingen", "Goal"); ct.makeCode("7", "A. Onderzoek m.b.t. de mens: and. ijkingen", "Goal"); ct.makeCode("8", "A. Onderzoek m.b.t. het dier: ontw. sera vaccins/biol.produkten", "Goal"); ct.makeCode("9", "A. Onderzoek m.b.t. het dier: prod./contr./ijking sera vaccins/biol. producten", "Goal"); ct.makeCode("10", "A. Onderzoek m.b.t. het dier: ontw. geneesmiddelen", "Goal"); ct.makeCode("11", "A. Onderzoek m.b.t. het dier: prod./contr./ijking geneesmiddelen", "Goal"); ct.makeCode("12", "A. Onderzoek m.b.t. het dier: ontw. med. hulpmiddelen/ toepassingen", "Goal"); ct.makeCode("13", "A. Onderzoek m.b.t. het dier: prod./contr./ijking med.hulpm./toepassingen", "Goal"); ct.makeCode("14", "A. Onderzoek m.b.t. het dier: and. ijkingen", "Goal"); ct.makeCode("15", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: agrarische sector", "Goal"); ct.makeCode("16", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: industrie", "Goal"); ct.makeCode("17", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: huishouden", "Goal"); ct.makeCode("18", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: cosm./toiletartikelen", "Goal"); ct.makeCode("19", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: voed.midd.mens.cons.", "Goal"); ct.makeCode("20", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: voed.midd.dier.cons.", "Goal"); ct.makeCode("21", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: tabak/and.rookwaren", "Goal"); ct.makeCode("22", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: stoffen schad.voor milieu", "Goal"); ct.makeCode("23", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: ander", "Goal"); ct.makeCode("24", "C. Opsporen van/ uivoeren van diagnostiek: ziekten bij mensen", "Goal"); ct.makeCode("25", "C. Opsporen van/ uivoeren van diagnostiek: and.lich.kenmerken bij mensen", "Goal"); ct.makeCode("26", "C. Opsporen van/ uivoeren van diagnostiek: ziekten bij dieren", "Goal"); ct.makeCode("27", "C. Opsporen van/ uivoeren van diagnostiek: and. lich.kenmerken bij dieren", "Goal"); ct.makeCode("28", "C. Opsporen van/ uivoeren van diagnostiek: ziekten/kenmerken bij planten", "Goal"); ct.makeCode("29", "D. Onderwijs/Training", "Goal"); ct.makeCode("30", "E. Wetensch.vraag m.b.t.: kanker (excl.carcinogene stoffen) bij mensen", "Goal"); ct.makeCode("31", "E. Wetensch.vraag m.b.t.: hart-en vaatziekten bij mensen", "Goal"); ct.makeCode("32", "E. Wetensch.vraag m.b.t.: geestesz./zenuwz. bij mensen", "Goal"); ct.makeCode("33", "E. Wetensch.vraag m.b.t.: and. ziekten bij mensen", "Goal"); ct.makeCode("34", "E. Wetensch.vraag m.b.t.: and. lich. kenmerken bij mensen", "Goal"); ct.makeCode("35", "E. Wetensch.vraag m.b.t.: gedrag van dieren", "Goal"); ct.makeCode("36", "E. Wetensch.vraag m.b.t.: ziekten bij dieren", "Goal"); ct.makeCode("37", "E. Wetensch.vraag m.b.t.: and. wetenschappelijke vraag", "Goal"); // Codes for ExpectedDiscomfort ct.makeCode("1", "A. Gering", "ExpectedDiscomfort"); ct.makeCode("2", "B. Gering/matig", "ExpectedDiscomfort"); ct.makeCode("3", "C. Matig", "ExpectedDiscomfort"); ct.makeCode("4", "D. Matig/ernstig", "ExpectedDiscomfort"); ct.makeCode("5", "E. Ernstig", "ExpectedDiscomfort"); ct.makeCode("6", "F. Zeer ernstig", "ExpectedDiscomfort"); // Codes for ActualDiscomfort ct.makeCode("1", "A. Gering", "ActualDiscomfort"); ct.makeCode("2", "B. Gering/matig", "ActualDiscomfort"); ct.makeCode("3", "C. Matig", "ActualDiscomfort"); ct.makeCode("4", "D. Matig/ernstig", "ActualDiscomfort"); ct.makeCode("5", "E. Ernstig", "ActualDiscomfort"); ct.makeCode("6", "F. Zeer ernstig", "ActualDiscomfort"); // Codes for AnimalType ct.makeCode("1", "A. Gewoon dier", "AnimalType"); ct.makeCode("2", "B. Transgeen dier", "AnimalType"); ct.makeCode("3", "C. Wildvang", "AnimalType"); ct.makeCode("4", "D. Biotoop", "AnimalType"); // Codes for GeneName ct.makeCode("Cry1", "Cry1", "GeneName"); ct.makeCode("Cry2", "Cry2", "GeneName"); ct.makeCode("Per1", "Per1", "GeneName"); ct.makeCode("Per2", "Per2", "GeneName"); // Codes for GeneState ct.makeCode("0", "-/-", "GeneState"); ct.makeCode("1", "+/-", "GeneState"); ct.makeCode("2", "+/+", "GeneState"); ct.makeCode("3", "ntg", "GeneState"); ct.makeCode("4", "wt", "GeneState"); ct.makeCode("5", "unknown", "GeneState"); ct.makeCode("6", "transgenic", "GeneState"); // Codes for VWASpecies ct.makeCode("01", "Muizen", "VWASpecies"); ct.makeCode("02", "Ratten", "VWASpecies"); ct.makeCode("03", "Hamsters", "VWASpecies"); ct.makeCode("04", "Cavia's", "VWASpecies"); ct.makeCode("09", "And. Knaagdieren", "VWASpecies"); ct.makeCode("11", "Konijnen", "VWASpecies"); ct.makeCode("21", "Honden", "VWASpecies"); ct.makeCode("22", "Katten", "VWASpecies"); ct.makeCode("23", "Fretten", "VWASpecies"); ct.makeCode("29", "And. Vleeseters", "VWASpecies"); ct.makeCode("31", "Prosimians", "VWASpecies"); ct.makeCode("32", "Nieuwe wereld apen", "VWASpecies"); ct.makeCode("33", "Oude wereld apen", "VWASpecies"); ct.makeCode("34", "Mensapen", "VWASpecies"); ct.makeCode("41", "Paarden", "VWASpecies"); ct.makeCode("42", "Varkens", "VWASpecies"); ct.makeCode("43", "Geiten", "VWASpecies"); ct.makeCode("44", "Schapen", "VWASpecies"); ct.makeCode("45", "Runderen", "VWASpecies"); ct.makeCode("49", "And. Zoogdieren", "VWASpecies"); ct.makeCode("51", "Kippen", "VWASpecies"); ct.makeCode("52", "Kwartels", "VWASpecies"); ct.makeCode("59", "And.Vogels", "VWASpecies"); ct.makeCode("69", "Reptielen", "VWASpecies"); ct.makeCode("79", "Amfibieen", "VWASpecies"); ct.makeCode("89", "Vissen", "VWASpecies"); ct.makeCode("91", "Cyclostoma", "VWASpecies"); // Codes for Removal ct.makeCode("0", "dood", "Removal"); ct.makeCode("1", "levend afgevoerd andere organisatorische eenheid RuG", "Removal"); ct.makeCode("2", "levend afgevoerd gereg. onderzoeksinstelling NL", "Removal"); ct.makeCode("3", "levend afgevoerd gereg. onderzoeksinstelling EU", "Removal"); ct.makeCode("4", "levend afgevoerd andere bestemming", "Removal"); // Codes for Earmark ct.makeCode("1 l", "one left", "Earmark"); ct.makeCode("1 r", "one right", "Earmark"); ct.makeCode("1 r 1 l", "one right, one left", "Earmark"); ct.makeCode("1 r 2 l", "one right, two left", "Earmark"); ct.makeCode("2 l", "two left", "Earmark"); ct.makeCode("2 l 1 r", "two left, one right", "Earmark"); ct.makeCode("2 r", "two right", "Earmark"); ct.makeCode("2 r 1 l", "two right, one left", "Earmark"); ct.makeCode("2 r 2 l", "two right, two left", "Earmark"); ct.makeCode("O", "none", "Earmark"); ct.makeCode("x", "", "Earmark"); // Codes for Color ct.makeCode("beige", "beige", "Color"); ct.makeCode("brown", "brown", "Color"); ct.makeCode("yellow", "yellow", "Color"); ct.makeCode("gray", "gray", "Color"); ct.makeCode("gray-brown", "gray-brown", "Color"); ct.makeCode("red-brown", "red-brown", "Color"); ct.makeCode("black", "black", "Color"); ct.makeCode("black-brown", "black-brown", "Color"); ct.makeCode("black-gray", "black-gray", "Color"); ct.makeCode("white", "white", "Color"); ct.makeCode("cinnamon", "cinnamon", "Color"); logger.info("Create Protocols"); // Protocol for Location plugin: SetSublocationOf (feature: Location) List<Integer> featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Location")); ct.makeProtocol(invid, "SetSublocationOf", "To set one location as the sublocation of another.", featureIdList); // Protocol for Breeding module: SetLitterSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Parentgroup")); featureIdList.add(ct.getMeasurementId("DateOfBirth")); featureIdList.add(ct.getMeasurementId("Size")); featureIdList.add(ct.getMeasurementId("Certain")); ct.makeProtocol(invid, "SetLitterSpecs", "To set the specifications of a litter.", featureIdList); // Protocol SetAddress featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Street")); featureIdList.add(ct.getMeasurementId("Housenumber")); featureIdList.add(ct.getMeasurementId("City")); ct.makeProtocol(invid, "SetAddress", "To set an address.", featureIdList); // Protocol SetDecProjectSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("DecNr")); featureIdList.add(ct.getMeasurementId("DecTitle")); featureIdList.add(ct.getMeasurementId("DecApplicantId")); featureIdList.add(ct.getMeasurementId("DecApplicationPdf")); featureIdList.add(ct.getMeasurementId("DecApprovalPdf")); featureIdList.add(ct.getMeasurementId("StartDate")); featureIdList.add(ct.getMeasurementId("EndDate")); ct.makeProtocol(invid, "SetDecProjectSpecs", "To set the specifications of a DEC project.", featureIdList); // Protocol SetDecSubprojectSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("ExperimentNr")); featureIdList.add(ct.getMeasurementId("DecSubprojectApplicationPdf")); featureIdList.add(ct.getMeasurementId("Concern")); featureIdList.add(ct.getMeasurementId("Goal")); featureIdList.add(ct.getMeasurementId("SpecialTechn")); featureIdList.add(ct.getMeasurementId("LawDef")); featureIdList.add(ct.getMeasurementId("ToxRes")); featureIdList.add(ct.getMeasurementId("Anaesthesia")); featureIdList.add(ct.getMeasurementId("PainManagement")); featureIdList.add(ct.getMeasurementId("AnimalEndStatus")); featureIdList.add(ct.getMeasurementId("OldAnimalDBRemarks")); featureIdList.add(ct.getMeasurementId("DecApplication")); featureIdList.add(ct.getMeasurementId("StartDate")); featureIdList.add(ct.getMeasurementId("EndDate")); ct.makeProtocol(invid, "SetDecSubprojectSpecs", "To set the specifications of a DEC subproject.", featureIdList); // Protocol AnimalInSubproject featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Experiment")); featureIdList.add(ct.getMeasurementId("ExperimentTitle")); featureIdList.add(ct.getMeasurementId("SourceTypeSubproject")); featureIdList.add(ct.getMeasurementId("PainManagement")); featureIdList.add(ct.getMeasurementId("Anaesthesia")); featureIdList.add(ct.getMeasurementId("ExpectedDiscomfort")); featureIdList.add(ct.getMeasurementId("ExpectedAnimalEndStatus")); ct.makeProtocol(invid, "AnimalInSubproject", "To add an animal to an experiment.", featureIdList); // Protocol AnimalFromSubproject featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("FromExperiment")); featureIdList.add(ct.getMeasurementId("ActualDiscomfort")); featureIdList.add(ct.getMeasurementId("ActualAnimalEndStatus")); ct.makeProtocol(invid, "AnimalFromSubproject", "To remove an animal from an experiment.", featureIdList); // Protocol SetGenotype featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("GeneName")); featureIdList.add(ct.getMeasurementId("GeneState")); ct.makeProtocol(invid, "SetGenotype", "To set part (one gene) of an animal's genotype.", featureIdList); // Protocol Wean // Discussion: for now we leave out the custom label feature, because that is flexible (set by user). // Discussion: for now we leave out the Genotype features. Genotype is set a few weeks after weaning, // when the PCR results come in. So we'd probably better use a separate set of protocols for that // (Background + X times Genotype protocol). featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Litter")); featureIdList.add(ct.getMeasurementId("Sex")); featureIdList.add(ct.getMeasurementId("WeanDate")); featureIdList.add(ct.getMeasurementId("Active")); featureIdList.add(ct.getMeasurementId("DateOfBirth")); featureIdList.add(ct.getMeasurementId("Species")); featureIdList.add(ct.getMeasurementId("AnimalType")); featureIdList.add(ct.getMeasurementId("Source")); featureIdList.add(ct.getMeasurementId("Color")); featureIdList.add(ct.getMeasurementId("Earmark")); featureIdList.add(ct.getMeasurementId("Sex")); ct.makeProtocol(invid, "Wean", "To wean an animal.", featureIdList); // Init lists that we can later add to the DB at once List<ObservedValue> valuesToAddList = new ArrayList<ObservedValue>(); // Find MolgenisUsers, create corresponding AnimalDB Actors and link them using a value // Obsolete since we will not use Actors anymore, only MolgenisUsers /* logger.info("Find MolgenisUsers and create corresponding Actors"); int protocolId = ct.getProtocolId("SetMolgenisUserId"); int measurementId = ct.getMeasurementId("MolgenisUserId"); int adminActorId = 0; List<MolgenisUser> userList = db.find(MolgenisUser.class); for (MolgenisUser user : userList) { String userName = user.getName(); int animaldbUserId = ct.makeActor(invid, userName); // Link Actor to MolgenisUser valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, animaldbUserId, Integer.toString(user.getId()), 0)); // Keep admin's id for further use if (userName.equals("admin")) { adminActorId = animaldbUserId; } } // Give admin Actor the Article 9 status protocolId = ct.getProtocolId("SetArticle"); measurementId = ct.getMeasurementId("Article"); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, adminActorId, "9", 0)); */ int protocolId = ct.getProtocolId("SetTypeOfGroup"); int measurementId = ct.getMeasurementId("TypeOfGroup"); logger.info("Create Groups"); // Groups -> sex int groupId = ct.makePanel(invid, "Male", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); groupId = ct.makePanel(invid, "Female", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); groupId = ct.makePanel(invid, "UnknownSex", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); // Groups -> species int vwaProtocolId = ct.getProtocolId("SetVWASpecies"); int latinProtocolId = ct.getProtocolId("SetVWASpecies"); int vwaMeasurementId = ct.getMeasurementId("VWASpecies"); int latinMeasurementId = ct.getMeasurementId("LatinSpecies"); groupId = ct.makePanel(invid, "Syrian hamster", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Hamsters", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Mesocricetus auratus", 0)); groupId = ct.makePanel(invid, "European groundsquirrel", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "And. knaagdieren", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Spermophilus citellus", 0)); groupId = ct.makePanel(invid, "House mouse", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Muizen", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Mus musculus", 0)); groupId = ct.makePanel(invid, "Siberian hamster", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Hamsters", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Phodopus sungorus", 0)); groupId = ct.makePanel(invid, "Gray mouse lemur", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Prosimians", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Microcebus murinus", 0)); groupId = ct.makePanel(invid, "Brown rat", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Ratten", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Rattus norvegicus", 0)); // Groups -> Background groupId = ct.makePanel(invid, "CD1", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Background", 0)); groupId = ct.makePanel(invid, "C57black6J", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Background", 0)); // Groups -> Source int sourceProtocolId = ct.getProtocolId("SetSourceType"); int sourceMeasurementId = ct.getMeasurementId("SourceType"); groupId = ct.makePanel(invid, "Harlan", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Geregistreerde fok/aflevering in Nederland", 0)); groupId = ct.makePanel(invid, "Kweek chronobiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Kweek gedragsbiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Kweek dierfysiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Wilde fauna", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Niet-geregistreerde fok/afl in Nederland", 0)); // Sources for Uli Eisel: groupId = ct.makePanel(invid, "UliEisel51and52", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Van EU-lid-staten", 0)); groupId = ct.makePanel(invid, "UliEisel55", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Andere herkomst", 0)); groupId = ct.makePanel(invid, "Kweek moleculaire neurobiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); // Sources for demo purposes: groupId = ct.makePanel(invid, "Max-Planck-Institut fuer Verhaltensfysiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Van EU-lid-staten", 0)); groupId = ct.makePanel(invid, "Unknown source UK", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Niet-geregistreerde fok/afl in andere EU-lid-staat", 0)); // Add everything to DB db.add(valuesToAddList); logger.info("AnimalDB database updated successfully!"); login.logout(db); login.login(db, "anonymous", "anonymous"); } }
false
true
public void populateDB(Login login) throws Exception, HandleRequestDelegationException,DatabaseException, ParseException, IOException { // Login as admin to have enough rights to do this login.login(db, "admin", "admin"); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); Logger logger = Logger.getLogger("FillAnimalDB"); logger.info("Start filling the database with factory defaults for AnimalDB."); // Make investigation logger.info("Create investigation"); Investigation inv = new Investigation(); inv.setName("System"); inv.setOwns_Id(login.getUserId()); int allUsersId = db.find(MolgenisGroup.class, new QueryRule(MolgenisGroup.NAME, Operator.EQUALS, "AllUsers")).get(0).getId(); inv.setCanRead_Id(allUsersId); db.add(inv); int invid = inv.getId(); // Make ontology 'Units' logger.info("Add ontology entries"); Ontology ont = new Ontology(); ont.setName("Units"); db.add(ont); Query<Ontology> q = db.query(Ontology.class); q.eq(Ontology.NAME, "Units"); List<Ontology> ontList = q.find(); int ontid = ontList.get(0).getId(); // Make ontology term entries int targetlinkUnitId = ct.makeOntologyTerm("TargetLink", ontid, "Link to an entry in one of the ObservationTarget tables."); int gramUnitId = ct.makeOntologyTerm("Gram", ontid, "SI unit for mass."); int booleanUnitId = ct.makeOntologyTerm("Boolean", ontid, "True (1) or false (0)."); int datetimeUnitId = ct.makeOntologyTerm("Datetime", ontid, "Timestamp."); int numberUnitId = ct.makeOntologyTerm("Number", ontid, "A discrete number greater than 0."); int stringUnitId = ct.makeOntologyTerm("String", ontid, "Short piece of text."); logger.info("Create measurements"); MolgenisEntity individual = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Individual").find().get(0); MolgenisEntity panel = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Panel").find().get(0); MolgenisEntity location = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Location").find().get(0); // Make features // Because of the MeasurementDecorator a basic protocol with the name Set<MeasurementName> will be auto-generated ct.makeMeasurement(invid, "TypeOfGroup", stringUnitId, null, null, false, "string", "To label a group of targets.", login.getUserId()); ct.makeMeasurement(invid, "Species", targetlinkUnitId, panel, "Species", false, "xref", "To set the species of an animal.", login.getUserId()); ct.makeMeasurement(invid, "Sex", targetlinkUnitId, panel, "Sex", false, "xref", "To set the sex of an animal.", login.getUserId()); ct.makeMeasurement(invid, "Location", targetlinkUnitId, location, null, false, "xref", "To set the location of a target.", login.getUserId()); ct.makeMeasurement(invid, "Weight", gramUnitId, null, null, true, "decimal", "To set the weight of a target.", login.getUserId()); ct.makeMeasurement(invid, "Father", targetlinkUnitId, individual, null, false, "xref", "To link a parent-group to an animal that may be a father.", login.getUserId()); ct.makeMeasurement(invid, "Mother", targetlinkUnitId, individual, null, false, "xref", "To link a parent-group to an animal that may be a mother.", login.getUserId()); ct.makeMeasurement(invid, "Certain", booleanUnitId, null, null, false, "bool", "To indicate whether the parenthood of an animal regarding a parent-group is certain.", login.getUserId()); ct.makeMeasurement(invid, "Group", targetlinkUnitId, panel, null, false, "xref", "To add a target to a panel.", login.getUserId()); ct.makeMeasurement(invid, "Parentgroup", targetlinkUnitId, panel, "Parentgroup", false, "xref", "To link a litter to a parent-group.", login.getUserId()); ct.makeMeasurement(invid, "DateOfBirth", datetimeUnitId, null, null, true, "datetime", "To set a target's or a litter's date of birth.", login.getUserId()); ct.makeMeasurement(invid, "Size", numberUnitId, null, null, true, "int", "To set the size of a target-group, for instance a litter.", login.getUserId()); ct.makeMeasurement(invid, "WeanSize", numberUnitId, null, null, true, "int", "To set the wean size of a litter.", login.getUserId()); ct.makeMeasurement(invid, "WeanSizeFemale", numberUnitId, null, null, true, "int", "To set the number of females in a litter when weaning.", login.getUserId()); ct.makeMeasurement(invid, "Street", stringUnitId, null, null, false, "string", "To set the street part of an address.", login.getUserId()); ct.makeMeasurement(invid, "Housenumber", numberUnitId, null, null, false, "int", "To set the house-number part of an address.", login.getUserId()); ct.makeMeasurement(invid, "City", stringUnitId, null, null, false, "string", "To set the city part of an address.", login.getUserId()); ct.makeMeasurement(invid, "CustomID", stringUnitId, null, null, false, "string", "To set a target's custom ID.", login.getUserId()); ct.makeMeasurement(invid, "WeanDate", datetimeUnitId, null, null, true, "datetime", "To set a litter's or target's date of weaning.", login.getUserId()); ct.makeMeasurement(invid, "GenotypeDate", datetimeUnitId, null, null, true, "datetime", "To set a litter's date of genotyping.", login.getUserId()); ct.makeMeasurement(invid, "CageCleanDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of cage cleaning.", login.getUserId()); ct.makeMeasurement(invid, "DeathDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of death.", login.getUserId()); ct.makeMeasurement(invid, "Active", stringUnitId, null, null, false, "string", "To register a target's activity span.", login.getUserId()); ct.makeMeasurement(invid, "Background", targetlinkUnitId, panel, "Background", false, "xref", "To set an animal's genotypic background.", login.getUserId()); ct.makeMeasurement(invid, "Source", targetlinkUnitId, panel, "Source", false, "xref", "To link an animal or a breeding line to a source.", login.getUserId()); ct.makeMeasurement(invid, "Line", targetlinkUnitId, panel, "Link", false, "xref", "To link a parentgroup to a breeding line.", login.getUserId()); ct.makeMeasurement(invid, "SourceType", stringUnitId, null, null, false, "string", "To set the type of an animal source (used in VWA Report 4).", login.getUserId()); ct.makeMeasurement(invid, "SourceTypeSubproject", stringUnitId, null, null, false, "string", "To set the animal's source type, when it enters a DEC subproject (used in VWA Report 5).", login.getUserId()); ct.makeMeasurement(invid, "ParticipantGroup", stringUnitId, null, null, false, "string", "To set the participant group an animal is considered part of.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBRemarks", stringUnitId, null, null, false, "string", "To store remarks about the animal in the animal table, from the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "Remark", stringUnitId, null, null, false, "string", "To store remarks about the animal.", login.getUserId()); ct.makeMeasurement(invid, "Litter", targetlinkUnitId, panel, "Litter", false, "xref", "To link an animal to a litter.", login.getUserId()); ct.makeMeasurement(invid, "ExperimentNr", stringUnitId, null, null, false, "string", "To set a (sub)experiment's number.", login.getUserId()); ct.makeMeasurement(invid, "ExperimentTitle", stringUnitId, null, null, false, "string", "To set a (sub)experiment's number.", login.getUserId()); ct.makeMeasurement(invid, "DecSubprojectApplicationPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the (sub)experiment's DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecApplicationPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecApprovalPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the DEC approval.", login.getUserId()); ct.makeMeasurement(invid, "DecApplication", targetlinkUnitId, panel, "DecApplication", false, "xref", "To link a DEC subproject (experiment) to a DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecNr", stringUnitId, null, null, false, "string", "To set a DEC application's DEC number.", login.getUserId()); ct.makeMeasurement(invid, "DecTitle", stringUnitId, null, null, false, "string", "To set the title of a DEC project.", login.getUserId()); ct.makeMeasurement(invid, "DecApplicantId", stringUnitId, null, null, false, "string", "To link a DEC application to a user with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "Anaesthesia", stringUnitId, null, null, false, "string", "To set the Anaesthesia value of (an animal in) an experiment.", login.getUserId()); ct.makeMeasurement(invid, "PainManagement", stringUnitId, null, null, false, "string", "To set the PainManagement value of (an animal in) an experiment.", login.getUserId()); ct.makeMeasurement(invid, "AnimalEndStatus", stringUnitId, null, null, false, "string", "To set the AnimalEndStatus value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "LawDef", stringUnitId, null, null, false, "string", "To set the Lawdef value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ToxRes", stringUnitId, null, null, false, "string", "To set the ToxRes value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "SpecialTechn", stringUnitId, null, null, false, "string", "To set the SpecialTechn value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Goal", stringUnitId, null, null, false, "string", "To set the Goal of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Concern", stringUnitId, null, null, false, "string", "To set the Concern value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "FieldBiology", booleanUnitId, null, null, false, "bool", "To indicate whether a DEC application is related to field biology.", login.getUserId()); ct.makeMeasurement(invid, "ExpectedDiscomfort", stringUnitId, null, null, false, "string", "To set the expected discomfort of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ActualDiscomfort", stringUnitId, null, null, false, "string", "To set the actual discomfort of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "AnimalType", stringUnitId, null, null, false, "string", "To set the animal type.", login.getUserId()); ct.makeMeasurement(invid, "ExpectedAnimalEndStatus", stringUnitId, null, null, false, "string", "To set the expected end status of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ActualAnimalEndStatus", stringUnitId, null, null, false, "string", "To set the actual end status of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Experiment", targetlinkUnitId, panel, "Experiment", false, "xref", "To link an animal to a DEC subproject (experiment).", login.getUserId()); ct.makeMeasurement(invid, "FromExperiment", targetlinkUnitId, panel, "Experiment", false, "xref", "To remove an animal from a DEC subproject (experiment).", login.getUserId()); ct.makeMeasurement(invid, "GeneName", stringUnitId, null, null, false, "string", "The name of a gene that may or may not be present in an animal.", login.getUserId()); ct.makeMeasurement(invid, "GeneState", stringUnitId, null, null, false, "string", "To indicate whether an animal is homo- or heterozygous for a gene.", login.getUserId()); ct.makeMeasurement(invid, "VWASpecies", stringUnitId, null, null, false, "string", "To give a species the name the VWA uses for it.", login.getUserId()); ct.makeMeasurement(invid, "LatinSpecies", stringUnitId, null, null, false, "string", "To give a species its scientific (Latin) name.", login.getUserId()); ct.makeMeasurement(invid, "StartDate", datetimeUnitId, null, null, true, "datetime", "To set a (sub)project's start date.", login.getUserId()); ct.makeMeasurement(invid, "EndDate", datetimeUnitId, null, null, true, "datetime", "To set a (sub)project's end date.", login.getUserId()); ct.makeMeasurement(invid, "Removal", stringUnitId, null, null, false, "string", "To register an animal's removal.", login.getUserId()); ct.makeMeasurement(invid, "Article", numberUnitId, null, null, false, "int", "To set an actor's Article status according to the Law, e.g. Article 9.", login.getUserId()); ct.makeMeasurement(invid, "MolgenisUserId", numberUnitId, null, null, false, "int", "To set an actor's corresponding MolgenisUser ID.", login.getUserId()); // For importing old AnimalDB ct.makeMeasurement(invid, "OldAnimalDBAnimalID", stringUnitId, null, null, false, "string", "To set an animal's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBAnimalCustomID", stringUnitId, null, null, false, "string", "To set an animal's Custom ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBLocationID", stringUnitId, null, null, false, "string", "To set a location's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBLitterID", stringUnitId, null, null, false, "string", "To link an animal to a litter with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBExperimentID", stringUnitId, null, null, false, "string", "To set an experiment's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBDecApplicationID", stringUnitId, null, null, false, "string", "To link an experiment to a DEC application with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBBroughtinDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of arrival in the system/ on the location in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBExperimentalManipulationRemark", stringUnitId, null, null, false, "string", "To store Experiment remarks about the animal, from the Experimental manipulation event, from the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBPresetID", stringUnitId, null, null, false, "string", "To link a targetgroup to a preset this ID in the old version of AnimalDB.", login.getUserId()); // For importing old Uli Eisel DB ct.makeMeasurement(invid, "OldUliDbId", stringUnitId, null, null, false, "string", "To set an animal's ID in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbKuerzel", stringUnitId, null, null, false, "string", "To set an animal's 'K�rzel' in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbAktenzeichen", stringUnitId, null, null, false, "string", "To set an animal's 'Aktenzeichen' in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbExperimentator", stringUnitId, null, null, false, "string", "To set an animal's experimenter in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbTierschutzrecht", stringUnitId, null, null, false, "string", "To set an animal's 'Tierschutzrecht' (~ DEC subproject Goal) in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "Color", stringUnitId, null, null, false, "string", "To set an animal's color.", login.getUserId()); ct.makeMeasurement(invid, "Earmark", stringUnitId, null, null, false, "string", "To set an animal's earmark.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbMotherInfo", stringUnitId, null, null, false, "string", "To set an animal's mother info in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbFatherInfo", stringUnitId, null, null, false, "string", "To set an animal's father info in the old Uli Eisel DB.", login.getUserId()); logger.info("Add codes"); // Codes for Subprojects ct.makeCode("A", "A", "ExperimentNr"); ct.makeCode("B", "B", "ExperimentNr"); ct.makeCode("C", "C", "ExperimentNr"); ct.makeCode("D", "D", "ExperimentNr"); ct.makeCode("E", "E", "ExperimentNr"); ct.makeCode("F", "F", "ExperimentNr"); ct.makeCode("G", "G", "ExperimentNr"); ct.makeCode("H", "H", "ExperimentNr"); ct.makeCode("I", "I", "ExperimentNr"); ct.makeCode("J", "J", "ExperimentNr"); ct.makeCode("K", "K", "ExperimentNr"); ct.makeCode("L", "L", "ExperimentNr"); ct.makeCode("M", "M", "ExperimentNr"); ct.makeCode("N", "N", "ExperimentNr"); ct.makeCode("O", "O", "ExperimentNr"); ct.makeCode("P", "P", "ExperimentNr"); ct.makeCode("Q", "Q", "ExperimentNr"); ct.makeCode("R", "R", "ExperimentNr"); ct.makeCode("S", "S", "ExperimentNr"); ct.makeCode("T", "T", "ExperimentNr"); ct.makeCode("U", "U", "ExperimentNr"); ct.makeCode("V", "V", "ExperimentNr"); ct.makeCode("W", "W", "ExperimentNr"); ct.makeCode("X", "X", "ExperimentNr"); ct.makeCode("Y", "Y", "ExperimentNr"); ct.makeCode("Z", "Z", "ExperimentNr"); // Codes for SourceType ct.makeCode("1-1", "Eigen fok binnen uw organisatorische werkeenheid", "SourceType"); ct.makeCode("1-2", "Andere organisatorische werkeenheid vd instelling", "SourceType"); ct.makeCode("1-3", "Geregistreerde fok/aflevering in Nederland", "SourceType"); ct.makeCode("2", "Van EU-lid-staten", "SourceType"); ct.makeCode("3", "Niet-geregistreerde fok/afl in Nederland", "SourceType"); ct.makeCode("4", "Niet-geregistreerde fok/afl in andere EU-lid-staat", "SourceType"); ct.makeCode("5", "Andere herkomst", "SourceType"); // Codes for SourceTypeSubproject ct.makeCode("1", "Geregistreerde fok/aflevering in Nederland", "SourceTypeSubproject"); ct.makeCode("2", "Van EU-lid-staten", "SourceTypeSubproject"); ct.makeCode("3", "Niet-geregistreerde fok/afl in Nederland", "SourceTypeSubproject"); ct.makeCode("4", "Niet-geregistreerde fok/afl in andere EU-lid-staat", "SourceTypeSubproject"); ct.makeCode("5", "Andere herkomst", "SourceTypeSubproject"); ct.makeCode("6", "Hergebruik eerste maal in het registratiejaar", "SourceTypeSubproject"); ct.makeCode("7", "Hergebruik tweede, derde enz. maal in het registratiejaar", "SourceTypeSubproject"); // Codes for ParticipantGroup ct.makeCode("04", "Chrono- en gedragsbiologie", "ParticipantGroup"); ct.makeCode("06", "Plantenbiologie", "ParticipantGroup"); ct.makeCode("07", "Dierfysiologie", "ParticipantGroup"); ct.makeCode("Klinische Farmacologie (no code yet)", "Klinische Farmacologie", "ParticipantGroup"); // Codes for Anaestheasia ct.makeCode("1", "A. Is niet toegepast (geen aanleiding)", "Anaesthesia"); ct.makeCode("2", "B. Is niet toegepast (onverenigbaar proef)", "Anaesthesia"); ct.makeCode("3", "C. Is niet toegepast (praktisch onuitvoerbaar)", "Anaesthesia"); ct.makeCode("4", "D. Is wel toegepast", "Anaesthesia"); // Codes for PainManagement ct.makeCode("1", "A. Is niet toegepast (geen aanleiding)", "PainManagement"); ct.makeCode("2", "B. Is niet toegepast (onverenigbaar proef)", "PainManagement"); ct.makeCode("3", "C. Is niet toegepast (praktisch onuitvoerbaar)", "PainManagement"); ct.makeCode("4", "D. Is wel toegepast", "PainManagement"); // Codes for AnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "AnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "AnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "AnimalEndStatus"); // Codes for ExpectedAnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "ExpectedAnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "ExpectedAnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "ExpectedAnimalEndStatus"); // Codes for ActualAnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "ActualAnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "ActualAnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "ActualAnimalEndStatus"); // Codes for LawDef ct.makeCode("1", "A. Geen wettelijke bepaling", "LawDef"); ct.makeCode("2", "B. Uitsluitend Nederland", "LawDef"); ct.makeCode("3", "C. Uitsluitend EU-lidstaten", "LawDef"); ct.makeCode("4", "D. Uitsluitend Lidstaten Raad v. Eur.", "LawDef"); ct.makeCode("5", "E. Uitsluitend Europese landen", "LawDef"); ct.makeCode("6", "F. Ander wettelijke bepaling", "LawDef"); ct.makeCode("7", "G. Combinatie van B. C. D. E. en F", "LawDef"); // Codes for ToxRes ct.makeCode("01", "A. Geen toxicologisch onderzoek", "ToxRes"); ct.makeCode("02", "B. Acuut tox. met letaliteit", "ToxRes"); ct.makeCode("03", "C. Acuut tox. LD50/LC50", "ToxRes"); ct.makeCode("04", "D. Overige acuut tox. (geen letaliteit)", "ToxRes"); ct.makeCode("05", "E. Sub-acuut tox.", "ToxRes"); ct.makeCode("06", "F. Sub-chronisch en chronische tox.", "ToxRes"); ct.makeCode("07", "G. Carcinogeniteitsonderzoek", "ToxRes"); ct.makeCode("08", "H. Mutageniteitsonderzoek", "ToxRes"); ct.makeCode("09", "I. Teratogeniteitsonderz. (segment II)", "ToxRes"); ct.makeCode("10", "J. Reproductie-onderzoek (segment 1 en III)", "ToxRes"); ct.makeCode("11", "K. Overige toxiciteitsonderzoek", "ToxRes"); // Codes for SpecialTechn ct.makeCode("01", "A. Geen van deze technieken/ingrepen", "SpecialTechn"); ct.makeCode("02", "B. Doden zonder voorafgaande handelingen", "SpecialTechn"); ct.makeCode("03", "C. Curare-achtige stoffen zonder anesthesie", "SpecialTechn"); ct.makeCode("04", "D. Technieken/ingrepen verkrijgen transgene dieren", "SpecialTechn"); ct.makeCode("05", "E. Toedienen van mogelijk irriterende stoffen via luchtwegen", "SpecialTechn"); ct.makeCode("06", "E. Toedienen van mogelijk irriterende stoffen op het oog", "SpecialTechn"); ct.makeCode("07", "E. Toedienen van mogelijk irriterende stoffen op andere slijmvliezen of huid", "SpecialTechn"); ct.makeCode("08", "F. Huidsensibilisaties", "SpecialTechn"); ct.makeCode("09", "G. Bestraling, met schadelijke effecten", "SpecialTechn"); ct.makeCode("10", "H. Traumatiserende fysische/chemische prikkels (CZ)", "SpecialTechn"); ct.makeCode("11", "I. Traumatiserende psychische prikkels", "SpecialTechn"); ct.makeCode("12", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van ontstekingen/infecties", "SpecialTechn"); ct.makeCode("13", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van verbrand./fract. of letsel (traum.)", "SpecialTechn"); ct.makeCode("14", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van poly- en monoclonale antistoffen", "SpecialTechn"); ct.makeCode("15", "J. Technieken/ingrepen anders dan C t/m H, gericht: produceren van monoclonale antistoffen", "SpecialTechn"); ct.makeCode("16", "K. Meer dan een onder G t/m J vermelde mogelijkheden", "SpecialTechn"); ct.makeCode("17", "L. Gefokt met ongerief", "SpecialTechn"); // Codes for Concern ct.makeCode("1", "A. Gezondheid/voed. ja", "Concern"); ct.makeCode("2", "B. Gezondheid/voed. nee", "Concern"); // Codes for Goal ct.makeCode("1", "A. Onderzoek m.b.t. de mens: ontw. sera vaccins/biol.produkten", "Goal"); ct.makeCode("2", "A. Onderzoek m.b.t. de mens: prod./contr./ijking sera vaccins/biol. producten", "Goal"); ct.makeCode("3", "A. Onderzoek m.b.t. de mens: ontw. geneesmiddelen", "Goal"); ct.makeCode("4", "A. Onderzoek m.b.t. de mens: prod./contr./ijking geneesmiddelen", "Goal"); ct.makeCode("5", "A. Onderzoek m.b.t. de mens: ontw. med. hulpmiddelen/ toepassingen", "Goal"); ct.makeCode("6", "A. Onderzoek m.b.t. de mens: prod./contr./ijking med.hulpm./toepassingen", "Goal"); ct.makeCode("7", "A. Onderzoek m.b.t. de mens: and. ijkingen", "Goal"); ct.makeCode("8", "A. Onderzoek m.b.t. het dier: ontw. sera vaccins/biol.produkten", "Goal"); ct.makeCode("9", "A. Onderzoek m.b.t. het dier: prod./contr./ijking sera vaccins/biol. producten", "Goal"); ct.makeCode("10", "A. Onderzoek m.b.t. het dier: ontw. geneesmiddelen", "Goal"); ct.makeCode("11", "A. Onderzoek m.b.t. het dier: prod./contr./ijking geneesmiddelen", "Goal"); ct.makeCode("12", "A. Onderzoek m.b.t. het dier: ontw. med. hulpmiddelen/ toepassingen", "Goal"); ct.makeCode("13", "A. Onderzoek m.b.t. het dier: prod./contr./ijking med.hulpm./toepassingen", "Goal"); ct.makeCode("14", "A. Onderzoek m.b.t. het dier: and. ijkingen", "Goal"); ct.makeCode("15", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: agrarische sector", "Goal"); ct.makeCode("16", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: industrie", "Goal"); ct.makeCode("17", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: huishouden", "Goal"); ct.makeCode("18", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: cosm./toiletartikelen", "Goal"); ct.makeCode("19", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: voed.midd.mens.cons.", "Goal"); ct.makeCode("20", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: voed.midd.dier.cons.", "Goal"); ct.makeCode("21", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: tabak/and.rookwaren", "Goal"); ct.makeCode("22", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: stoffen schad.voor milieu", "Goal"); ct.makeCode("23", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: ander", "Goal"); ct.makeCode("24", "C. Opsporen van/ uivoeren van diagnostiek: ziekten bij mensen", "Goal"); ct.makeCode("25", "C. Opsporen van/ uivoeren van diagnostiek: and.lich.kenmerken bij mensen", "Goal"); ct.makeCode("26", "C. Opsporen van/ uivoeren van diagnostiek: ziekten bij dieren", "Goal"); ct.makeCode("27", "C. Opsporen van/ uivoeren van diagnostiek: and. lich.kenmerken bij dieren", "Goal"); ct.makeCode("28", "C. Opsporen van/ uivoeren van diagnostiek: ziekten/kenmerken bij planten", "Goal"); ct.makeCode("29", "D. Onderwijs/Training", "Goal"); ct.makeCode("30", "E. Wetensch.vraag m.b.t.: kanker (excl.carcinogene stoffen) bij mensen", "Goal"); ct.makeCode("31", "E. Wetensch.vraag m.b.t.: hart-en vaatziekten bij mensen", "Goal"); ct.makeCode("32", "E. Wetensch.vraag m.b.t.: geestesz./zenuwz. bij mensen", "Goal"); ct.makeCode("33", "E. Wetensch.vraag m.b.t.: and. ziekten bij mensen", "Goal"); ct.makeCode("34", "E. Wetensch.vraag m.b.t.: and. lich. kenmerken bij mensen", "Goal"); ct.makeCode("35", "E. Wetensch.vraag m.b.t.: gedrag van dieren", "Goal"); ct.makeCode("36", "E. Wetensch.vraag m.b.t.: ziekten bij dieren", "Goal"); ct.makeCode("37", "E. Wetensch.vraag m.b.t.: and. wetenschappelijke vraag", "Goal"); // Codes for ExpectedDiscomfort ct.makeCode("1", "A. Gering", "ExpectedDiscomfort"); ct.makeCode("2", "B. Gering/matig", "ExpectedDiscomfort"); ct.makeCode("3", "C. Matig", "ExpectedDiscomfort"); ct.makeCode("4", "D. Matig/ernstig", "ExpectedDiscomfort"); ct.makeCode("5", "E. Ernstig", "ExpectedDiscomfort"); ct.makeCode("6", "F. Zeer ernstig", "ExpectedDiscomfort"); // Codes for ActualDiscomfort ct.makeCode("1", "A. Gering", "ActualDiscomfort"); ct.makeCode("2", "B. Gering/matig", "ActualDiscomfort"); ct.makeCode("3", "C. Matig", "ActualDiscomfort"); ct.makeCode("4", "D. Matig/ernstig", "ActualDiscomfort"); ct.makeCode("5", "E. Ernstig", "ActualDiscomfort"); ct.makeCode("6", "F. Zeer ernstig", "ActualDiscomfort"); // Codes for AnimalType ct.makeCode("1", "A. Gewoon dier", "AnimalType"); ct.makeCode("2", "B. Transgeen dier", "AnimalType"); ct.makeCode("3", "C. Wildvang", "AnimalType"); ct.makeCode("4", "D. Biotoop", "AnimalType"); // Codes for GeneName ct.makeCode("Cry1", "Cry1", "GeneName"); ct.makeCode("Cry2", "Cry2", "GeneName"); ct.makeCode("Per1", "Per1", "GeneName"); ct.makeCode("Per2", "Per2", "GeneName"); // Codes for GeneState ct.makeCode("0", "-/-", "GeneState"); ct.makeCode("1", "+/-", "GeneState"); ct.makeCode("2", "+/+", "GeneState"); ct.makeCode("3", "ntg", "GeneState"); ct.makeCode("4", "wt", "GeneState"); ct.makeCode("5", "unknown", "GeneState"); ct.makeCode("6", "transgenic", "GeneState"); // Codes for VWASpecies ct.makeCode("01", "Muizen", "VWASpecies"); ct.makeCode("02", "Ratten", "VWASpecies"); ct.makeCode("03", "Hamsters", "VWASpecies"); ct.makeCode("04", "Cavia's", "VWASpecies"); ct.makeCode("09", "And. Knaagdieren", "VWASpecies"); ct.makeCode("11", "Konijnen", "VWASpecies"); ct.makeCode("21", "Honden", "VWASpecies"); ct.makeCode("22", "Katten", "VWASpecies"); ct.makeCode("23", "Fretten", "VWASpecies"); ct.makeCode("29", "And. Vleeseters", "VWASpecies"); ct.makeCode("31", "Prosimians", "VWASpecies"); ct.makeCode("32", "Nieuwe wereld apen", "VWASpecies"); ct.makeCode("33", "Oude wereld apen", "VWASpecies"); ct.makeCode("34", "Mensapen", "VWASpecies"); ct.makeCode("41", "Paarden", "VWASpecies"); ct.makeCode("42", "Varkens", "VWASpecies"); ct.makeCode("43", "Geiten", "VWASpecies"); ct.makeCode("44", "Schapen", "VWASpecies"); ct.makeCode("45", "Runderen", "VWASpecies"); ct.makeCode("49", "And. Zoogdieren", "VWASpecies"); ct.makeCode("51", "Kippen", "VWASpecies"); ct.makeCode("52", "Kwartels", "VWASpecies"); ct.makeCode("59", "And.Vogels", "VWASpecies"); ct.makeCode("69", "Reptielen", "VWASpecies"); ct.makeCode("79", "Amfibieen", "VWASpecies"); ct.makeCode("89", "Vissen", "VWASpecies"); ct.makeCode("91", "Cyclostoma", "VWASpecies"); // Codes for Removal ct.makeCode("0", "dood", "Removal"); ct.makeCode("1", "levend afgevoerd andere organisatorische eenheid RuG", "Removal"); ct.makeCode("2", "levend afgevoerd gereg. onderzoeksinstelling NL", "Removal"); ct.makeCode("3", "levend afgevoerd gereg. onderzoeksinstelling EU", "Removal"); ct.makeCode("4", "levend afgevoerd andere bestemming", "Removal"); // Codes for Earmark ct.makeCode("1 l", "one left", "Earmark"); ct.makeCode("1 r", "one right", "Earmark"); ct.makeCode("1 r 1 l", "one right, one left", "Earmark"); ct.makeCode("1 r 2 l", "one right, two left", "Earmark"); ct.makeCode("2 l", "two left", "Earmark"); ct.makeCode("2 l 1 r", "two left, one right", "Earmark"); ct.makeCode("2 r", "two right", "Earmark"); ct.makeCode("2 r 1 l", "two right, one left", "Earmark"); ct.makeCode("2 r 2 l", "two right, two left", "Earmark"); ct.makeCode("O", "none", "Earmark"); ct.makeCode("x", "", "Earmark"); // Codes for Color ct.makeCode("beige", "beige", "Color"); ct.makeCode("brown", "brown", "Color"); ct.makeCode("yellow", "yellow", "Color"); ct.makeCode("gray", "gray", "Color"); ct.makeCode("gray-brown", "gray-brown", "Color"); ct.makeCode("red-brown", "red-brown", "Color"); ct.makeCode("black", "black", "Color"); ct.makeCode("black-brown", "black-brown", "Color"); ct.makeCode("black-gray", "black-gray", "Color"); ct.makeCode("white", "white", "Color"); ct.makeCode("cinnamon", "cinnamon", "Color"); logger.info("Create Protocols"); // Protocol for Location plugin: SetSublocationOf (feature: Location) List<Integer> featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Location")); ct.makeProtocol(invid, "SetSublocationOf", "To set one location as the sublocation of another.", featureIdList); // Protocol for Breeding module: SetLitterSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Parentgroup")); featureIdList.add(ct.getMeasurementId("DateOfBirth")); featureIdList.add(ct.getMeasurementId("Size")); featureIdList.add(ct.getMeasurementId("Certain")); ct.makeProtocol(invid, "SetLitterSpecs", "To set the specifications of a litter.", featureIdList); // Protocol SetAddress featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Street")); featureIdList.add(ct.getMeasurementId("Housenumber")); featureIdList.add(ct.getMeasurementId("City")); ct.makeProtocol(invid, "SetAddress", "To set an address.", featureIdList); // Protocol SetDecProjectSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("DecNr")); featureIdList.add(ct.getMeasurementId("DecTitle")); featureIdList.add(ct.getMeasurementId("DecApplicantId")); featureIdList.add(ct.getMeasurementId("DecApplicationPdf")); featureIdList.add(ct.getMeasurementId("DecApprovalPdf")); featureIdList.add(ct.getMeasurementId("StartDate")); featureIdList.add(ct.getMeasurementId("EndDate")); ct.makeProtocol(invid, "SetDecProjectSpecs", "To set the specifications of a DEC project.", featureIdList); // Protocol SetDecSubprojectSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("ExperimentNr")); featureIdList.add(ct.getMeasurementId("DecSubprojectApplicationPdf")); featureIdList.add(ct.getMeasurementId("Concern")); featureIdList.add(ct.getMeasurementId("Goal")); featureIdList.add(ct.getMeasurementId("SpecialTechn")); featureIdList.add(ct.getMeasurementId("LawDef")); featureIdList.add(ct.getMeasurementId("ToxRes")); featureIdList.add(ct.getMeasurementId("Anaesthesia")); featureIdList.add(ct.getMeasurementId("PainManagement")); featureIdList.add(ct.getMeasurementId("AnimalEndStatus")); featureIdList.add(ct.getMeasurementId("OldAnimalDBRemarks")); featureIdList.add(ct.getMeasurementId("DecApplication")); featureIdList.add(ct.getMeasurementId("StartDate")); featureIdList.add(ct.getMeasurementId("EndDate")); ct.makeProtocol(invid, "SetDecSubprojectSpecs", "To set the specifications of a DEC subproject.", featureIdList); // Protocol AnimalInSubproject featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Experiment")); featureIdList.add(ct.getMeasurementId("ExperimentTitle")); featureIdList.add(ct.getMeasurementId("SourceTypeSubproject")); featureIdList.add(ct.getMeasurementId("PainManagement")); featureIdList.add(ct.getMeasurementId("Anaesthesia")); featureIdList.add(ct.getMeasurementId("ExpectedDiscomfort")); featureIdList.add(ct.getMeasurementId("ExpectedAnimalEndStatus")); ct.makeProtocol(invid, "AnimalInSubproject", "To add an animal to an experiment.", featureIdList); // Protocol AnimalFromSubproject featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("FromExperiment")); featureIdList.add(ct.getMeasurementId("ActualDiscomfort")); featureIdList.add(ct.getMeasurementId("ActualAnimalEndStatus")); ct.makeProtocol(invid, "AnimalFromSubproject", "To remove an animal from an experiment.", featureIdList); // Protocol SetGenotype featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("GeneName")); featureIdList.add(ct.getMeasurementId("GeneState")); ct.makeProtocol(invid, "SetGenotype", "To set part (one gene) of an animal's genotype.", featureIdList); // Protocol Wean // Discussion: for now we leave out the custom label feature, because that is flexible (set by user). // Discussion: for now we leave out the Genotype features. Genotype is set a few weeks after weaning, // when the PCR results come in. So we'd probably better use a separate set of protocols for that // (Background + X times Genotype protocol). featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Litter")); featureIdList.add(ct.getMeasurementId("Sex")); featureIdList.add(ct.getMeasurementId("WeanDate")); featureIdList.add(ct.getMeasurementId("Active")); featureIdList.add(ct.getMeasurementId("DateOfBirth")); featureIdList.add(ct.getMeasurementId("Species")); featureIdList.add(ct.getMeasurementId("AnimalType")); featureIdList.add(ct.getMeasurementId("Source")); featureIdList.add(ct.getMeasurementId("Color")); featureIdList.add(ct.getMeasurementId("Earmark")); featureIdList.add(ct.getMeasurementId("Sex")); ct.makeProtocol(invid, "Wean", "To wean an animal.", featureIdList); // Init lists that we can later add to the DB at once List<ObservedValue> valuesToAddList = new ArrayList<ObservedValue>(); // Find MolgenisUsers, create corresponding AnimalDB Actors and link them using a value // Obsolete since we will not use Actors anymore, only MolgenisUsers /* logger.info("Find MolgenisUsers and create corresponding Actors"); int protocolId = ct.getProtocolId("SetMolgenisUserId"); int measurementId = ct.getMeasurementId("MolgenisUserId"); int adminActorId = 0; List<MolgenisUser> userList = db.find(MolgenisUser.class); for (MolgenisUser user : userList) { String userName = user.getName(); int animaldbUserId = ct.makeActor(invid, userName); // Link Actor to MolgenisUser valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, animaldbUserId, Integer.toString(user.getId()), 0)); // Keep admin's id for further use if (userName.equals("admin")) { adminActorId = animaldbUserId; } } // Give admin Actor the Article 9 status protocolId = ct.getProtocolId("SetArticle"); measurementId = ct.getMeasurementId("Article"); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, adminActorId, "9", 0)); */ int protocolId = ct.getProtocolId("SetTypeOfGroup"); int measurementId = ct.getMeasurementId("TypeOfGroup"); logger.info("Create Groups"); // Groups -> sex int groupId = ct.makePanel(invid, "Male", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); groupId = ct.makePanel(invid, "Female", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); groupId = ct.makePanel(invid, "UnknownSex", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); // Groups -> species int vwaProtocolId = ct.getProtocolId("SetVWASpecies"); int latinProtocolId = ct.getProtocolId("SetVWASpecies"); int vwaMeasurementId = ct.getMeasurementId("VWASpecies"); int latinMeasurementId = ct.getMeasurementId("LatinSpecies"); groupId = ct.makePanel(invid, "Syrian hamster", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Hamsters", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Mesocricetus auratus", 0)); groupId = ct.makePanel(invid, "European groundsquirrel", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "And. knaagdieren", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Spermophilus citellus", 0)); groupId = ct.makePanel(invid, "House mouse", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Muizen", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Mus musculus", 0)); groupId = ct.makePanel(invid, "Siberian hamster", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Hamsters", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Phodopus sungorus", 0)); groupId = ct.makePanel(invid, "Gray mouse lemur", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Prosimians", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Microcebus murinus", 0)); groupId = ct.makePanel(invid, "Brown rat", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Ratten", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Rattus norvegicus", 0)); // Groups -> Background groupId = ct.makePanel(invid, "CD1", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Background", 0)); groupId = ct.makePanel(invid, "C57black6J", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Background", 0)); // Groups -> Source int sourceProtocolId = ct.getProtocolId("SetSourceType"); int sourceMeasurementId = ct.getMeasurementId("SourceType"); groupId = ct.makePanel(invid, "Harlan", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Geregistreerde fok/aflevering in Nederland", 0)); groupId = ct.makePanel(invid, "Kweek chronobiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Kweek gedragsbiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Kweek dierfysiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Wilde fauna", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Niet-geregistreerde fok/afl in Nederland", 0)); // Sources for Uli Eisel: groupId = ct.makePanel(invid, "UliEisel51and52", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Van EU-lid-staten", 0)); groupId = ct.makePanel(invid, "UliEisel55", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Andere herkomst", 0)); groupId = ct.makePanel(invid, "Kweek moleculaire neurobiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); // Sources for demo purposes: groupId = ct.makePanel(invid, "Max-Planck-Institut fuer Verhaltensfysiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Van EU-lid-staten", 0)); groupId = ct.makePanel(invid, "Unknown source UK", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Niet-geregistreerde fok/afl in andere EU-lid-staat", 0)); // Add everything to DB db.add(valuesToAddList); logger.info("AnimalDB database updated successfully!"); login.logout(db); login.login(db, "anonymous", "anonymous"); }
public void populateDB(Login login) throws Exception, HandleRequestDelegationException,DatabaseException, ParseException, IOException { // Login as admin to have enough rights to do this login.login(db, "admin", "admin"); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); Logger logger = Logger.getLogger("FillAnimalDB"); logger.info("Start filling the database with factory defaults for AnimalDB."); // Make investigation logger.info("Create investigation"); Investigation inv = new Investigation(); inv.setName("System"); inv.setOwns_Id(login.getUserId()); int allUsersId = db.find(MolgenisGroup.class, new QueryRule(MolgenisGroup.NAME, Operator.EQUALS, "AllUsers")).get(0).getId(); inv.setCanRead_Id(allUsersId); db.add(inv); int invid = inv.getId(); // Make ontology 'Units' logger.info("Add ontology entries"); Ontology ont = new Ontology(); ont.setName("Units"); db.add(ont); Query<Ontology> q = db.query(Ontology.class); q.eq(Ontology.NAME, "Units"); List<Ontology> ontList = q.find(); int ontid = ontList.get(0).getId(); // Make ontology term entries int targetlinkUnitId = ct.makeOntologyTerm("TargetLink", ontid, "Link to an entry in one of the ObservationTarget tables."); int gramUnitId = ct.makeOntologyTerm("Gram", ontid, "SI unit for mass."); int booleanUnitId = ct.makeOntologyTerm("Boolean", ontid, "True (1) or false (0)."); int datetimeUnitId = ct.makeOntologyTerm("Datetime", ontid, "Timestamp."); int numberUnitId = ct.makeOntologyTerm("Number", ontid, "A discrete number greater than 0."); int stringUnitId = ct.makeOntologyTerm("String", ontid, "Short piece of text."); logger.info("Create measurements"); MolgenisEntity individual = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Individual").find().get(0); MolgenisEntity panel = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Panel").find().get(0); MolgenisEntity location = db.query(MolgenisEntity.class).equals(MolgenisEntity.NAME, "Location").find().get(0); // Make features // Because of the MeasurementDecorator a basic protocol with the name Set<MeasurementName> will be auto-generated ct.makeMeasurement(invid, "TypeOfGroup", stringUnitId, null, null, false, "string", "To label a group of targets.", login.getUserId()); ct.makeMeasurement(invid, "Species", targetlinkUnitId, panel, "Species", false, "xref", "To set the species of an animal.", login.getUserId()); ct.makeMeasurement(invid, "Sex", targetlinkUnitId, panel, "Sex", false, "xref", "To set the sex of an animal.", login.getUserId()); ct.makeMeasurement(invid, "Location", targetlinkUnitId, location, null, false, "xref", "To set the location of a target.", login.getUserId()); ct.makeMeasurement(invid, "Weight", gramUnitId, null, null, true, "decimal", "To set the weight of a target.", login.getUserId()); ct.makeMeasurement(invid, "Father", targetlinkUnitId, individual, null, false, "xref", "To link a parent-group to an animal that may be a father.", login.getUserId()); ct.makeMeasurement(invid, "Mother", targetlinkUnitId, individual, null, false, "xref", "To link a parent-group to an animal that may be a mother.", login.getUserId()); ct.makeMeasurement(invid, "Certain", booleanUnitId, null, null, false, "bool", "To indicate whether the parenthood of an animal regarding a parent-group is certain.", login.getUserId()); ct.makeMeasurement(invid, "Group", targetlinkUnitId, panel, null, false, "xref", "To add a target to a panel.", login.getUserId()); ct.makeMeasurement(invid, "Parentgroup", targetlinkUnitId, panel, "Parentgroup", false, "xref", "To link a litter to a parent-group.", login.getUserId()); ct.makeMeasurement(invid, "DateOfBirth", datetimeUnitId, null, null, true, "datetime", "To set a target's or a litter's date of birth.", login.getUserId()); ct.makeMeasurement(invid, "Size", numberUnitId, null, null, true, "int", "To set the size of a target-group, for instance a litter.", login.getUserId()); ct.makeMeasurement(invid, "WeanSize", numberUnitId, null, null, true, "int", "To set the wean size of a litter.", login.getUserId()); ct.makeMeasurement(invid, "WeanSizeFemale", numberUnitId, null, null, true, "int", "To set the number of females in a litter when weaning.", login.getUserId()); ct.makeMeasurement(invid, "Street", stringUnitId, null, null, false, "string", "To set the street part of an address.", login.getUserId()); ct.makeMeasurement(invid, "Housenumber", numberUnitId, null, null, false, "int", "To set the house-number part of an address.", login.getUserId()); ct.makeMeasurement(invid, "City", stringUnitId, null, null, false, "string", "To set the city part of an address.", login.getUserId()); ct.makeMeasurement(invid, "CustomID", stringUnitId, null, null, false, "string", "To set a target's custom ID.", login.getUserId()); ct.makeMeasurement(invid, "WeanDate", datetimeUnitId, null, null, true, "datetime", "To set a litter's or target's date of weaning.", login.getUserId()); ct.makeMeasurement(invid, "GenotypeDate", datetimeUnitId, null, null, true, "datetime", "To set a litter's date of genotyping.", login.getUserId()); ct.makeMeasurement(invid, "CageCleanDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of cage cleaning.", login.getUserId()); ct.makeMeasurement(invid, "DeathDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of death.", login.getUserId()); ct.makeMeasurement(invid, "Active", stringUnitId, null, null, false, "string", "To register a target's activity span.", login.getUserId()); ct.makeMeasurement(invid, "Background", targetlinkUnitId, panel, "Background", false, "xref", "To set an animal's genotypic background.", login.getUserId()); ct.makeMeasurement(invid, "Source", targetlinkUnitId, panel, "Source", false, "xref", "To link an animal or a breeding line to a source.", login.getUserId()); ct.makeMeasurement(invid, "Line", targetlinkUnitId, panel, "Link", false, "xref", "To link a parentgroup to a breeding line.", login.getUserId()); ct.makeMeasurement(invid, "SourceType", stringUnitId, null, null, false, "string", "To set the type of an animal source (used in VWA Report 4).", login.getUserId()); ct.makeMeasurement(invid, "SourceTypeSubproject", stringUnitId, null, null, false, "string", "To set the animal's source type, when it enters a DEC subproject (used in VWA Report 5).", login.getUserId()); ct.makeMeasurement(invid, "ParticipantGroup", stringUnitId, null, null, false, "string", "To set the participant group an animal is considered part of.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBRemarks", stringUnitId, null, null, false, "string", "To store remarks about the animal in the animal table, from the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "Remark", stringUnitId, null, null, false, "string", "To store remarks about the animal.", login.getUserId()); ct.makeMeasurement(invid, "Litter", targetlinkUnitId, panel, "Litter", false, "xref", "To link an animal to a litter.", login.getUserId()); ct.makeMeasurement(invid, "ExperimentNr", stringUnitId, null, null, false, "string", "To set a (sub)experiment's number.", login.getUserId()); ct.makeMeasurement(invid, "ExperimentTitle", stringUnitId, null, null, false, "string", "To set a (sub)experiment's title.", login.getUserId()); ct.makeMeasurement(invid, "DecSubprojectApplicationPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the (sub)experiment's DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecApplicationPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecApprovalPdf", stringUnitId, null, null, false, "string", "To set a link to a PDF file with the DEC approval.", login.getUserId()); ct.makeMeasurement(invid, "DecApplication", targetlinkUnitId, panel, "DecApplication", false, "xref", "To link a DEC subproject (experiment) to a DEC application.", login.getUserId()); ct.makeMeasurement(invid, "DecNr", stringUnitId, null, null, false, "string", "To set a DEC application's DEC number.", login.getUserId()); ct.makeMeasurement(invid, "DecTitle", stringUnitId, null, null, false, "string", "To set the title of a DEC project.", login.getUserId()); ct.makeMeasurement(invid, "DecApplicantId", stringUnitId, null, null, false, "string", "To link a DEC application to a user with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "Anaesthesia", stringUnitId, null, null, false, "string", "To set the Anaesthesia value of (an animal in) an experiment.", login.getUserId()); ct.makeMeasurement(invid, "PainManagement", stringUnitId, null, null, false, "string", "To set the PainManagement value of (an animal in) an experiment.", login.getUserId()); ct.makeMeasurement(invid, "AnimalEndStatus", stringUnitId, null, null, false, "string", "To set the AnimalEndStatus value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "LawDef", stringUnitId, null, null, false, "string", "To set the Lawdef value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ToxRes", stringUnitId, null, null, false, "string", "To set the ToxRes value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "SpecialTechn", stringUnitId, null, null, false, "string", "To set the SpecialTechn value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Goal", stringUnitId, null, null, false, "string", "To set the Goal of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Concern", stringUnitId, null, null, false, "string", "To set the Concern value of an experiment.", login.getUserId()); ct.makeMeasurement(invid, "FieldBiology", booleanUnitId, null, null, false, "bool", "To indicate whether a DEC application is related to field biology.", login.getUserId()); ct.makeMeasurement(invid, "ExpectedDiscomfort", stringUnitId, null, null, false, "string", "To set the expected discomfort of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ActualDiscomfort", stringUnitId, null, null, false, "string", "To set the actual discomfort of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "AnimalType", stringUnitId, null, null, false, "string", "To set the animal type.", login.getUserId()); ct.makeMeasurement(invid, "ExpectedAnimalEndStatus", stringUnitId, null, null, false, "string", "To set the expected end status of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "ActualAnimalEndStatus", stringUnitId, null, null, false, "string", "To set the actual end status of an animal in an experiment.", login.getUserId()); ct.makeMeasurement(invid, "Experiment", targetlinkUnitId, panel, "Experiment", false, "xref", "To link an animal to a DEC subproject (experiment).", login.getUserId()); ct.makeMeasurement(invid, "FromExperiment", targetlinkUnitId, panel, "Experiment", false, "xref", "To remove an animal from a DEC subproject (experiment).", login.getUserId()); ct.makeMeasurement(invid, "GeneName", stringUnitId, null, null, false, "string", "The name of a gene that may or may not be present in an animal.", login.getUserId()); ct.makeMeasurement(invid, "GeneState", stringUnitId, null, null, false, "string", "To indicate whether an animal is homo- or heterozygous for a gene.", login.getUserId()); ct.makeMeasurement(invid, "VWASpecies", stringUnitId, null, null, false, "string", "To give a species the name the VWA uses for it.", login.getUserId()); ct.makeMeasurement(invid, "LatinSpecies", stringUnitId, null, null, false, "string", "To give a species its scientific (Latin) name.", login.getUserId()); ct.makeMeasurement(invid, "StartDate", datetimeUnitId, null, null, true, "datetime", "To set a (sub)project's start date.", login.getUserId()); ct.makeMeasurement(invid, "EndDate", datetimeUnitId, null, null, true, "datetime", "To set a (sub)project's end date.", login.getUserId()); ct.makeMeasurement(invid, "Removal", stringUnitId, null, null, false, "string", "To register an animal's removal.", login.getUserId()); ct.makeMeasurement(invid, "Article", numberUnitId, null, null, false, "int", "To set an actor's Article status according to the Law, e.g. Article 9.", login.getUserId()); ct.makeMeasurement(invid, "MolgenisUserId", numberUnitId, null, null, false, "int", "To set an actor's corresponding MolgenisUser ID.", login.getUserId()); // For importing old AnimalDB ct.makeMeasurement(invid, "OldAnimalDBAnimalID", stringUnitId, null, null, false, "string", "To set an animal's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBAnimalCustomID", stringUnitId, null, null, false, "string", "To set an animal's Custom ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBLocationID", stringUnitId, null, null, false, "string", "To set a location's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBLitterID", stringUnitId, null, null, false, "string", "To link an animal to a litter with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBExperimentID", stringUnitId, null, null, false, "string", "To set an experiment's ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBDecApplicationID", stringUnitId, null, null, false, "string", "To link an experiment to a DEC application with this ID in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBBroughtinDate", datetimeUnitId, null, null, true, "datetime", "To set a target's date of arrival in the system/ on the location in the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBExperimentalManipulationRemark", stringUnitId, null, null, false, "string", "To store Experiment remarks about the animal, from the Experimental manipulation event, from the old version of AnimalDB.", login.getUserId()); ct.makeMeasurement(invid, "OldAnimalDBPresetID", stringUnitId, null, null, false, "string", "To link a targetgroup to a preset this ID in the old version of AnimalDB.", login.getUserId()); // For importing old Uli Eisel DB ct.makeMeasurement(invid, "OldUliDbId", stringUnitId, null, null, false, "string", "To set an animal's ID in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbKuerzel", stringUnitId, null, null, false, "string", "To set an animal's 'Kürzel' in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbAktenzeichen", stringUnitId, null, null, false, "string", "To set an animal's 'Aktenzeichen' in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbExperimentator", stringUnitId, null, null, false, "string", "To set an animal's experimenter in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbTierschutzrecht", stringUnitId, null, null, false, "string", "To set an animal's 'Tierschutzrecht' (~ DEC subproject Goal) in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "Color", stringUnitId, null, null, false, "string", "To set an animal's color.", login.getUserId()); ct.makeMeasurement(invid, "Earmark", stringUnitId, null, null, false, "string", "To set an animal's earmark.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbMotherInfo", stringUnitId, null, null, false, "string", "To set an animal's mother info in the old Uli Eisel DB.", login.getUserId()); ct.makeMeasurement(invid, "OldUliDbFatherInfo", stringUnitId, null, null, false, "string", "To set an animal's father info in the old Uli Eisel DB.", login.getUserId()); logger.info("Add codes"); // Codes for Subprojects ct.makeCode("A", "A", "ExperimentNr"); ct.makeCode("B", "B", "ExperimentNr"); ct.makeCode("C", "C", "ExperimentNr"); ct.makeCode("D", "D", "ExperimentNr"); ct.makeCode("E", "E", "ExperimentNr"); ct.makeCode("F", "F", "ExperimentNr"); ct.makeCode("G", "G", "ExperimentNr"); ct.makeCode("H", "H", "ExperimentNr"); ct.makeCode("I", "I", "ExperimentNr"); ct.makeCode("J", "J", "ExperimentNr"); ct.makeCode("K", "K", "ExperimentNr"); ct.makeCode("L", "L", "ExperimentNr"); ct.makeCode("M", "M", "ExperimentNr"); ct.makeCode("N", "N", "ExperimentNr"); ct.makeCode("O", "O", "ExperimentNr"); ct.makeCode("P", "P", "ExperimentNr"); ct.makeCode("Q", "Q", "ExperimentNr"); ct.makeCode("R", "R", "ExperimentNr"); ct.makeCode("S", "S", "ExperimentNr"); ct.makeCode("T", "T", "ExperimentNr"); ct.makeCode("U", "U", "ExperimentNr"); ct.makeCode("V", "V", "ExperimentNr"); ct.makeCode("W", "W", "ExperimentNr"); ct.makeCode("X", "X", "ExperimentNr"); ct.makeCode("Y", "Y", "ExperimentNr"); ct.makeCode("Z", "Z", "ExperimentNr"); // Codes for SourceType ct.makeCode("1-1", "Eigen fok binnen uw organisatorische werkeenheid", "SourceType"); ct.makeCode("1-2", "Andere organisatorische werkeenheid vd instelling", "SourceType"); ct.makeCode("1-3", "Geregistreerde fok/aflevering in Nederland", "SourceType"); ct.makeCode("2", "Van EU-lid-staten", "SourceType"); ct.makeCode("3", "Niet-geregistreerde fok/afl in Nederland", "SourceType"); ct.makeCode("4", "Niet-geregistreerde fok/afl in andere EU-lid-staat", "SourceType"); ct.makeCode("5", "Andere herkomst", "SourceType"); // Codes for SourceTypeSubproject ct.makeCode("1", "Geregistreerde fok/aflevering in Nederland", "SourceTypeSubproject"); ct.makeCode("2", "Van EU-lid-staten", "SourceTypeSubproject"); ct.makeCode("3", "Niet-geregistreerde fok/afl in Nederland", "SourceTypeSubproject"); ct.makeCode("4", "Niet-geregistreerde fok/afl in andere EU-lid-staat", "SourceTypeSubproject"); ct.makeCode("5", "Andere herkomst", "SourceTypeSubproject"); ct.makeCode("6", "Hergebruik eerste maal in het registratiejaar", "SourceTypeSubproject"); ct.makeCode("7", "Hergebruik tweede, derde enz. maal in het registratiejaar", "SourceTypeSubproject"); // Codes for ParticipantGroup ct.makeCode("04", "Chrono- en gedragsbiologie", "ParticipantGroup"); ct.makeCode("06", "Plantenbiologie", "ParticipantGroup"); ct.makeCode("07", "Dierfysiologie", "ParticipantGroup"); ct.makeCode("Klinische Farmacologie (no code yet)", "Klinische Farmacologie", "ParticipantGroup"); // Codes for Anaestheasia ct.makeCode("1", "A. Is niet toegepast (geen aanleiding)", "Anaesthesia"); ct.makeCode("2", "B. Is niet toegepast (onverenigbaar proef)", "Anaesthesia"); ct.makeCode("3", "C. Is niet toegepast (praktisch onuitvoerbaar)", "Anaesthesia"); ct.makeCode("4", "D. Is wel toegepast", "Anaesthesia"); // Codes for PainManagement ct.makeCode("1", "A. Is niet toegepast (geen aanleiding)", "PainManagement"); ct.makeCode("2", "B. Is niet toegepast (onverenigbaar proef)", "PainManagement"); ct.makeCode("3", "C. Is niet toegepast (praktisch onuitvoerbaar)", "PainManagement"); ct.makeCode("4", "D. Is wel toegepast", "PainManagement"); // Codes for AnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "AnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "AnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "AnimalEndStatus"); // Codes for ExpectedAnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "ExpectedAnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "ExpectedAnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "ExpectedAnimalEndStatus"); // Codes for ActualAnimalEndStatus ct.makeCode("1", "A. Dood in het kader van de proef", "ActualAnimalEndStatus"); ct.makeCode("2", "B. Gedood na beeindiging van de proef", "ActualAnimalEndStatus"); ct.makeCode("3", "C. Na einde proef in leven gelaten", "ActualAnimalEndStatus"); // Codes for LawDef ct.makeCode("1", "A. Geen wettelijke bepaling", "LawDef"); ct.makeCode("2", "B. Uitsluitend Nederland", "LawDef"); ct.makeCode("3", "C. Uitsluitend EU-lidstaten", "LawDef"); ct.makeCode("4", "D. Uitsluitend Lidstaten Raad v. Eur.", "LawDef"); ct.makeCode("5", "E. Uitsluitend Europese landen", "LawDef"); ct.makeCode("6", "F. Ander wettelijke bepaling", "LawDef"); ct.makeCode("7", "G. Combinatie van B. C. D. E. en F", "LawDef"); // Codes for ToxRes ct.makeCode("01", "A. Geen toxicologisch onderzoek", "ToxRes"); ct.makeCode("02", "B. Acuut tox. met letaliteit", "ToxRes"); ct.makeCode("03", "C. Acuut tox. LD50/LC50", "ToxRes"); ct.makeCode("04", "D. Overige acuut tox. (geen letaliteit)", "ToxRes"); ct.makeCode("05", "E. Sub-acuut tox.", "ToxRes"); ct.makeCode("06", "F. Sub-chronisch en chronische tox.", "ToxRes"); ct.makeCode("07", "G. Carcinogeniteitsonderzoek", "ToxRes"); ct.makeCode("08", "H. Mutageniteitsonderzoek", "ToxRes"); ct.makeCode("09", "I. Teratogeniteitsonderz. (segment II)", "ToxRes"); ct.makeCode("10", "J. Reproductie-onderzoek (segment 1 en III)", "ToxRes"); ct.makeCode("11", "K. Overige toxiciteitsonderzoek", "ToxRes"); // Codes for SpecialTechn ct.makeCode("01", "A. Geen van deze technieken/ingrepen", "SpecialTechn"); ct.makeCode("02", "B. Doden zonder voorafgaande handelingen", "SpecialTechn"); ct.makeCode("03", "C. Curare-achtige stoffen zonder anesthesie", "SpecialTechn"); ct.makeCode("04", "D. Technieken/ingrepen verkrijgen transgene dieren", "SpecialTechn"); ct.makeCode("05", "E. Toedienen van mogelijk irriterende stoffen via luchtwegen", "SpecialTechn"); ct.makeCode("06", "E. Toedienen van mogelijk irriterende stoffen op het oog", "SpecialTechn"); ct.makeCode("07", "E. Toedienen van mogelijk irriterende stoffen op andere slijmvliezen of huid", "SpecialTechn"); ct.makeCode("08", "F. Huidsensibilisaties", "SpecialTechn"); ct.makeCode("09", "G. Bestraling, met schadelijke effecten", "SpecialTechn"); ct.makeCode("10", "H. Traumatiserende fysische/chemische prikkels (CZ)", "SpecialTechn"); ct.makeCode("11", "I. Traumatiserende psychische prikkels", "SpecialTechn"); ct.makeCode("12", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van ontstekingen/infecties", "SpecialTechn"); ct.makeCode("13", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van verbrand./fract. of letsel (traum.)", "SpecialTechn"); ct.makeCode("14", "J. Technieken/ingrepen anders dan C t/m H, gericht: opwekken van poly- en monoclonale antistoffen", "SpecialTechn"); ct.makeCode("15", "J. Technieken/ingrepen anders dan C t/m H, gericht: produceren van monoclonale antistoffen", "SpecialTechn"); ct.makeCode("16", "K. Meer dan een onder G t/m J vermelde mogelijkheden", "SpecialTechn"); ct.makeCode("17", "L. Gefokt met ongerief", "SpecialTechn"); // Codes for Concern ct.makeCode("1", "A. Gezondheid/voed. ja", "Concern"); ct.makeCode("2", "B. Gezondheid/voed. nee", "Concern"); // Codes for Goal ct.makeCode("1", "A. Onderzoek m.b.t. de mens: ontw. sera vaccins/biol.produkten", "Goal"); ct.makeCode("2", "A. Onderzoek m.b.t. de mens: prod./contr./ijking sera vaccins/biol. producten", "Goal"); ct.makeCode("3", "A. Onderzoek m.b.t. de mens: ontw. geneesmiddelen", "Goal"); ct.makeCode("4", "A. Onderzoek m.b.t. de mens: prod./contr./ijking geneesmiddelen", "Goal"); ct.makeCode("5", "A. Onderzoek m.b.t. de mens: ontw. med. hulpmiddelen/ toepassingen", "Goal"); ct.makeCode("6", "A. Onderzoek m.b.t. de mens: prod./contr./ijking med.hulpm./toepassingen", "Goal"); ct.makeCode("7", "A. Onderzoek m.b.t. de mens: and. ijkingen", "Goal"); ct.makeCode("8", "A. Onderzoek m.b.t. het dier: ontw. sera vaccins/biol.produkten", "Goal"); ct.makeCode("9", "A. Onderzoek m.b.t. het dier: prod./contr./ijking sera vaccins/biol. producten", "Goal"); ct.makeCode("10", "A. Onderzoek m.b.t. het dier: ontw. geneesmiddelen", "Goal"); ct.makeCode("11", "A. Onderzoek m.b.t. het dier: prod./contr./ijking geneesmiddelen", "Goal"); ct.makeCode("12", "A. Onderzoek m.b.t. het dier: ontw. med. hulpmiddelen/ toepassingen", "Goal"); ct.makeCode("13", "A. Onderzoek m.b.t. het dier: prod./contr./ijking med.hulpm./toepassingen", "Goal"); ct.makeCode("14", "A. Onderzoek m.b.t. het dier: and. ijkingen", "Goal"); ct.makeCode("15", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: agrarische sector", "Goal"); ct.makeCode("16", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: industrie", "Goal"); ct.makeCode("17", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: huishouden", "Goal"); ct.makeCode("18", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: cosm./toiletartikelen", "Goal"); ct.makeCode("19", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: voed.midd.mens.cons.", "Goal"); ct.makeCode("20", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: voed.midd.dier.cons.", "Goal"); ct.makeCode("21", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: tabak/and.rookwaren", "Goal"); ct.makeCode("22", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: stoffen schad.voor milieu", "Goal"); ct.makeCode("23", "B. Onderzoek m.b.t. schadelijkheid van stoffen voor: ander", "Goal"); ct.makeCode("24", "C. Opsporen van/ uivoeren van diagnostiek: ziekten bij mensen", "Goal"); ct.makeCode("25", "C. Opsporen van/ uivoeren van diagnostiek: and.lich.kenmerken bij mensen", "Goal"); ct.makeCode("26", "C. Opsporen van/ uivoeren van diagnostiek: ziekten bij dieren", "Goal"); ct.makeCode("27", "C. Opsporen van/ uivoeren van diagnostiek: and. lich.kenmerken bij dieren", "Goal"); ct.makeCode("28", "C. Opsporen van/ uivoeren van diagnostiek: ziekten/kenmerken bij planten", "Goal"); ct.makeCode("29", "D. Onderwijs/Training", "Goal"); ct.makeCode("30", "E. Wetensch.vraag m.b.t.: kanker (excl.carcinogene stoffen) bij mensen", "Goal"); ct.makeCode("31", "E. Wetensch.vraag m.b.t.: hart-en vaatziekten bij mensen", "Goal"); ct.makeCode("32", "E. Wetensch.vraag m.b.t.: geestesz./zenuwz. bij mensen", "Goal"); ct.makeCode("33", "E. Wetensch.vraag m.b.t.: and. ziekten bij mensen", "Goal"); ct.makeCode("34", "E. Wetensch.vraag m.b.t.: and. lich. kenmerken bij mensen", "Goal"); ct.makeCode("35", "E. Wetensch.vraag m.b.t.: gedrag van dieren", "Goal"); ct.makeCode("36", "E. Wetensch.vraag m.b.t.: ziekten bij dieren", "Goal"); ct.makeCode("37", "E. Wetensch.vraag m.b.t.: and. wetenschappelijke vraag", "Goal"); // Codes for ExpectedDiscomfort ct.makeCode("1", "A. Gering", "ExpectedDiscomfort"); ct.makeCode("2", "B. Gering/matig", "ExpectedDiscomfort"); ct.makeCode("3", "C. Matig", "ExpectedDiscomfort"); ct.makeCode("4", "D. Matig/ernstig", "ExpectedDiscomfort"); ct.makeCode("5", "E. Ernstig", "ExpectedDiscomfort"); ct.makeCode("6", "F. Zeer ernstig", "ExpectedDiscomfort"); // Codes for ActualDiscomfort ct.makeCode("1", "A. Gering", "ActualDiscomfort"); ct.makeCode("2", "B. Gering/matig", "ActualDiscomfort"); ct.makeCode("3", "C. Matig", "ActualDiscomfort"); ct.makeCode("4", "D. Matig/ernstig", "ActualDiscomfort"); ct.makeCode("5", "E. Ernstig", "ActualDiscomfort"); ct.makeCode("6", "F. Zeer ernstig", "ActualDiscomfort"); // Codes for AnimalType ct.makeCode("1", "A. Gewoon dier", "AnimalType"); ct.makeCode("2", "B. Transgeen dier", "AnimalType"); ct.makeCode("3", "C. Wildvang", "AnimalType"); ct.makeCode("4", "D. Biotoop", "AnimalType"); // Codes for GeneName ct.makeCode("Cry1", "Cry1", "GeneName"); ct.makeCode("Cry2", "Cry2", "GeneName"); ct.makeCode("Per1", "Per1", "GeneName"); ct.makeCode("Per2", "Per2", "GeneName"); // Codes for GeneState ct.makeCode("0", "-/-", "GeneState"); ct.makeCode("1", "+/-", "GeneState"); ct.makeCode("2", "+/+", "GeneState"); ct.makeCode("3", "ntg", "GeneState"); ct.makeCode("4", "wt", "GeneState"); ct.makeCode("5", "unknown", "GeneState"); ct.makeCode("6", "transgenic", "GeneState"); // Codes for VWASpecies ct.makeCode("01", "Muizen", "VWASpecies"); ct.makeCode("02", "Ratten", "VWASpecies"); ct.makeCode("03", "Hamsters", "VWASpecies"); ct.makeCode("04", "Cavia's", "VWASpecies"); ct.makeCode("09", "And. Knaagdieren", "VWASpecies"); ct.makeCode("11", "Konijnen", "VWASpecies"); ct.makeCode("21", "Honden", "VWASpecies"); ct.makeCode("22", "Katten", "VWASpecies"); ct.makeCode("23", "Fretten", "VWASpecies"); ct.makeCode("29", "And. Vleeseters", "VWASpecies"); ct.makeCode("31", "Prosimians", "VWASpecies"); ct.makeCode("32", "Nieuwe wereld apen", "VWASpecies"); ct.makeCode("33", "Oude wereld apen", "VWASpecies"); ct.makeCode("34", "Mensapen", "VWASpecies"); ct.makeCode("41", "Paarden", "VWASpecies"); ct.makeCode("42", "Varkens", "VWASpecies"); ct.makeCode("43", "Geiten", "VWASpecies"); ct.makeCode("44", "Schapen", "VWASpecies"); ct.makeCode("45", "Runderen", "VWASpecies"); ct.makeCode("49", "And. Zoogdieren", "VWASpecies"); ct.makeCode("51", "Kippen", "VWASpecies"); ct.makeCode("52", "Kwartels", "VWASpecies"); ct.makeCode("59", "And.Vogels", "VWASpecies"); ct.makeCode("69", "Reptielen", "VWASpecies"); ct.makeCode("79", "Amfibieen", "VWASpecies"); ct.makeCode("89", "Vissen", "VWASpecies"); ct.makeCode("91", "Cyclostoma", "VWASpecies"); // Codes for Removal ct.makeCode("0", "dood", "Removal"); ct.makeCode("1", "levend afgevoerd andere organisatorische eenheid RuG", "Removal"); ct.makeCode("2", "levend afgevoerd gereg. onderzoeksinstelling NL", "Removal"); ct.makeCode("3", "levend afgevoerd gereg. onderzoeksinstelling EU", "Removal"); ct.makeCode("4", "levend afgevoerd andere bestemming", "Removal"); // Codes for Earmark ct.makeCode("1 l", "one left", "Earmark"); ct.makeCode("1 r", "one right", "Earmark"); ct.makeCode("1 r 1 l", "one right, one left", "Earmark"); ct.makeCode("1 r 2 l", "one right, two left", "Earmark"); ct.makeCode("2 l", "two left", "Earmark"); ct.makeCode("2 l 1 r", "two left, one right", "Earmark"); ct.makeCode("2 r", "two right", "Earmark"); ct.makeCode("2 r 1 l", "two right, one left", "Earmark"); ct.makeCode("2 r 2 l", "two right, two left", "Earmark"); ct.makeCode("O", "none", "Earmark"); ct.makeCode("x", "", "Earmark"); // Codes for Color ct.makeCode("beige", "beige", "Color"); ct.makeCode("brown", "brown", "Color"); ct.makeCode("yellow", "yellow", "Color"); ct.makeCode("gray", "gray", "Color"); ct.makeCode("gray-brown", "gray-brown", "Color"); ct.makeCode("red-brown", "red-brown", "Color"); ct.makeCode("black", "black", "Color"); ct.makeCode("black-brown", "black-brown", "Color"); ct.makeCode("black-gray", "black-gray", "Color"); ct.makeCode("white", "white", "Color"); ct.makeCode("cinnamon", "cinnamon", "Color"); logger.info("Create Protocols"); // Protocol for Location plugin: SetSublocationOf (feature: Location) List<Integer> featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Location")); ct.makeProtocol(invid, "SetSublocationOf", "To set one location as the sublocation of another.", featureIdList); // Protocol for Breeding module: SetLitterSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Parentgroup")); featureIdList.add(ct.getMeasurementId("DateOfBirth")); featureIdList.add(ct.getMeasurementId("Size")); featureIdList.add(ct.getMeasurementId("Certain")); ct.makeProtocol(invid, "SetLitterSpecs", "To set the specifications of a litter.", featureIdList); // Protocol SetAddress featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Street")); featureIdList.add(ct.getMeasurementId("Housenumber")); featureIdList.add(ct.getMeasurementId("City")); ct.makeProtocol(invid, "SetAddress", "To set an address.", featureIdList); // Protocol SetDecProjectSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("DecNr")); featureIdList.add(ct.getMeasurementId("DecTitle")); featureIdList.add(ct.getMeasurementId("DecApplicantId")); featureIdList.add(ct.getMeasurementId("DecApplicationPdf")); featureIdList.add(ct.getMeasurementId("DecApprovalPdf")); featureIdList.add(ct.getMeasurementId("StartDate")); featureIdList.add(ct.getMeasurementId("EndDate")); ct.makeProtocol(invid, "SetDecProjectSpecs", "To set the specifications of a DEC project.", featureIdList); // Protocol SetDecSubprojectSpecs featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("ExperimentNr")); featureIdList.add(ct.getMeasurementId("DecSubprojectApplicationPdf")); featureIdList.add(ct.getMeasurementId("Concern")); featureIdList.add(ct.getMeasurementId("Goal")); featureIdList.add(ct.getMeasurementId("SpecialTechn")); featureIdList.add(ct.getMeasurementId("LawDef")); featureIdList.add(ct.getMeasurementId("ToxRes")); featureIdList.add(ct.getMeasurementId("Anaesthesia")); featureIdList.add(ct.getMeasurementId("PainManagement")); featureIdList.add(ct.getMeasurementId("AnimalEndStatus")); featureIdList.add(ct.getMeasurementId("OldAnimalDBRemarks")); featureIdList.add(ct.getMeasurementId("DecApplication")); featureIdList.add(ct.getMeasurementId("StartDate")); featureIdList.add(ct.getMeasurementId("EndDate")); ct.makeProtocol(invid, "SetDecSubprojectSpecs", "To set the specifications of a DEC subproject.", featureIdList); // Protocol AnimalInSubproject featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Experiment")); featureIdList.add(ct.getMeasurementId("ExperimentTitle")); featureIdList.add(ct.getMeasurementId("SourceTypeSubproject")); featureIdList.add(ct.getMeasurementId("PainManagement")); featureIdList.add(ct.getMeasurementId("Anaesthesia")); featureIdList.add(ct.getMeasurementId("ExpectedDiscomfort")); featureIdList.add(ct.getMeasurementId("ExpectedAnimalEndStatus")); ct.makeProtocol(invid, "AnimalInSubproject", "To add an animal to an experiment.", featureIdList); // Protocol AnimalFromSubproject featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("FromExperiment")); featureIdList.add(ct.getMeasurementId("ActualDiscomfort")); featureIdList.add(ct.getMeasurementId("ActualAnimalEndStatus")); ct.makeProtocol(invid, "AnimalFromSubproject", "To remove an animal from an experiment.", featureIdList); // Protocol SetGenotype featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("GeneName")); featureIdList.add(ct.getMeasurementId("GeneState")); ct.makeProtocol(invid, "SetGenotype", "To set part (one gene) of an animal's genotype.", featureIdList); // Protocol Wean // Discussion: for now we leave out the custom label feature, because that is flexible (set by user). // Discussion: for now we leave out the Genotype features. Genotype is set a few weeks after weaning, // when the PCR results come in. So we'd probably better use a separate set of protocols for that // (Background + X times Genotype protocol). featureIdList = new ArrayList<Integer>(); featureIdList.add(ct.getMeasurementId("Litter")); featureIdList.add(ct.getMeasurementId("Sex")); featureIdList.add(ct.getMeasurementId("WeanDate")); featureIdList.add(ct.getMeasurementId("Active")); featureIdList.add(ct.getMeasurementId("DateOfBirth")); featureIdList.add(ct.getMeasurementId("Species")); featureIdList.add(ct.getMeasurementId("AnimalType")); featureIdList.add(ct.getMeasurementId("Source")); featureIdList.add(ct.getMeasurementId("Color")); featureIdList.add(ct.getMeasurementId("Earmark")); featureIdList.add(ct.getMeasurementId("Sex")); ct.makeProtocol(invid, "Wean", "To wean an animal.", featureIdList); // Init lists that we can later add to the DB at once List<ObservedValue> valuesToAddList = new ArrayList<ObservedValue>(); // Find MolgenisUsers, create corresponding AnimalDB Actors and link them using a value // Obsolete since we will not use Actors anymore, only MolgenisUsers /* logger.info("Find MolgenisUsers and create corresponding Actors"); int protocolId = ct.getProtocolId("SetMolgenisUserId"); int measurementId = ct.getMeasurementId("MolgenisUserId"); int adminActorId = 0; List<MolgenisUser> userList = db.find(MolgenisUser.class); for (MolgenisUser user : userList) { String userName = user.getName(); int animaldbUserId = ct.makeActor(invid, userName); // Link Actor to MolgenisUser valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, animaldbUserId, Integer.toString(user.getId()), 0)); // Keep admin's id for further use if (userName.equals("admin")) { adminActorId = animaldbUserId; } } // Give admin Actor the Article 9 status protocolId = ct.getProtocolId("SetArticle"); measurementId = ct.getMeasurementId("Article"); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, adminActorId, "9", 0)); */ int protocolId = ct.getProtocolId("SetTypeOfGroup"); int measurementId = ct.getMeasurementId("TypeOfGroup"); logger.info("Create Groups"); // Groups -> sex int groupId = ct.makePanel(invid, "Male", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); groupId = ct.makePanel(invid, "Female", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); groupId = ct.makePanel(invid, "UnknownSex", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Sex", 0)); // Groups -> species int vwaProtocolId = ct.getProtocolId("SetVWASpecies"); int latinProtocolId = ct.getProtocolId("SetVWASpecies"); int vwaMeasurementId = ct.getMeasurementId("VWASpecies"); int latinMeasurementId = ct.getMeasurementId("LatinSpecies"); groupId = ct.makePanel(invid, "Syrian hamster", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Hamsters", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Mesocricetus auratus", 0)); groupId = ct.makePanel(invid, "European groundsquirrel", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "And. knaagdieren", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Spermophilus citellus", 0)); groupId = ct.makePanel(invid, "House mouse", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Muizen", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Mus musculus", 0)); groupId = ct.makePanel(invid, "Siberian hamster", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Hamsters", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Phodopus sungorus", 0)); groupId = ct.makePanel(invid, "Gray mouse lemur", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Prosimians", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Microcebus murinus", 0)); groupId = ct.makePanel(invid, "Brown rat", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Species", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, vwaProtocolId, vwaMeasurementId, groupId, "Ratten", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, latinProtocolId, latinMeasurementId, groupId, "Rattus norvegicus", 0)); // Groups -> Background groupId = ct.makePanel(invid, "CD1", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Background", 0)); groupId = ct.makePanel(invid, "C57black6J", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Background", 0)); // Groups -> Source int sourceProtocolId = ct.getProtocolId("SetSourceType"); int sourceMeasurementId = ct.getMeasurementId("SourceType"); groupId = ct.makePanel(invid, "Harlan", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Geregistreerde fok/aflevering in Nederland", 0)); groupId = ct.makePanel(invid, "Kweek chronobiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Kweek gedragsbiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Kweek dierfysiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); groupId = ct.makePanel(invid, "Wilde fauna", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Niet-geregistreerde fok/afl in Nederland", 0)); // Sources for Uli Eisel: groupId = ct.makePanel(invid, "UliEisel51and52", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Van EU-lid-staten", 0)); groupId = ct.makePanel(invid, "UliEisel55", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Andere herkomst", 0)); groupId = ct.makePanel(invid, "Kweek moleculaire neurobiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Eigen fok binnen uw organisatorische werkeenheid", 0)); // Sources for demo purposes: groupId = ct.makePanel(invid, "Max-Planck-Institut fuer Verhaltensfysiologie", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Van EU-lid-staten", 0)); groupId = ct.makePanel(invid, "Unknown source UK", login.getUserId()); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, protocolId, measurementId, groupId, "Source", 0)); valuesToAddList.add(ct.createObservedValueWithProtocolApplication(invid, now, null, sourceProtocolId, sourceMeasurementId, groupId, "Niet-geregistreerde fok/afl in andere EU-lid-staat", 0)); // Add everything to DB db.add(valuesToAddList); logger.info("AnimalDB database updated successfully!"); login.logout(db); login.login(db, "anonymous", "anonymous"); }
diff --git a/hazelcast/src/main/java/com/hazelcast/spi/impl/BasicInvocation.java b/hazelcast/src/main/java/com/hazelcast/spi/impl/BasicInvocation.java index eca15fd003..01d222298d 100644 --- a/hazelcast/src/main/java/com/hazelcast/spi/impl/BasicInvocation.java +++ b/hazelcast/src/main/java/com/hazelcast/spi/impl/BasicInvocation.java @@ -1,496 +1,496 @@ /* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spi.impl; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.instance.MemberImpl; import com.hazelcast.logging.ILogger; import com.hazelcast.nio.Address; import com.hazelcast.partition.InternalPartition; import com.hazelcast.spi.BackupAwareOperation; import com.hazelcast.spi.Callback; import com.hazelcast.spi.ExceptionAction; import com.hazelcast.spi.ExecutionService; import com.hazelcast.spi.Operation; import com.hazelcast.spi.ResponseHandler; import com.hazelcast.spi.WaitSupport; import com.hazelcast.spi.exception.CallTimeoutException; import com.hazelcast.spi.exception.ResponseAlreadySentException; import com.hazelcast.spi.exception.RetryableException; import com.hazelcast.spi.exception.RetryableIOException; import com.hazelcast.spi.exception.TargetNotMemberException; import com.hazelcast.spi.exception.WrongTargetException; import com.hazelcast.util.ExceptionUtil; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import static com.hazelcast.spi.OperationAccessor.isJoinOperation; import static com.hazelcast.spi.OperationAccessor.isMigrationOperation; import static com.hazelcast.spi.OperationAccessor.setCallTimeout; import static com.hazelcast.spi.OperationAccessor.setCallerAddress; import static com.hazelcast.spi.OperationAccessor.setInvocationTime; /** * The BasicInvocation evaluates a OperationInvocation for the {@link com.hazelcast.spi.impl.BasicOperationService}. * <p/> * A handle to wait for the completion of this BasicInvocation is the * {@link com.hazelcast.spi.impl.BasicInvocationFuture}. */ abstract class BasicInvocation implements ResponseHandler, Runnable { private final static AtomicReferenceFieldUpdater RESPONSE_RECEIVED_FIELD_UPDATER = AtomicReferenceFieldUpdater.newUpdater(BasicInvocation.class, Boolean.class, "responseReceived"); static final Object NULL_RESPONSE = new InternalResponse("Invocation::NULL_RESPONSE"); static final Object RETRY_RESPONSE = new InternalResponse("Invocation::RETRY_RESPONSE"); static final Object WAIT_RESPONSE = new InternalResponse("Invocation::WAIT_RESPONSE"); static final Object TIMEOUT_RESPONSE = new InternalResponse("Invocation::TIMEOUT_RESPONSE"); static final Object INTERRUPTED_RESPONSE = new InternalResponse("Invocation::INTERRUPTED_RESPONSE"); static class InternalResponse { private String toString; private InternalResponse(String toString) { this.toString = toString; } @Override public String toString() { return toString; } } private static final long MIN_TIMEOUT = 10000; protected final long callTimeout; protected final NodeEngineImpl nodeEngine; protected final String serviceName; protected final Operation op; protected final int partitionId; protected final int replicaIndex; protected final int tryCount; protected final long tryPauseMillis; protected final ILogger logger; private final BasicInvocationFuture invocationFuture; //needs to be a Boolean because it is updated through the RESPONSE_RECEIVED_FIELD_UPDATER private volatile Boolean responseReceived = Boolean.FALSE; private volatile int invokeCount = 0; boolean remote = false; private final String executorName; final boolean resultDeserialized; private Address invTarget; private MemberImpl invTargetMember; BasicInvocation(NodeEngineImpl nodeEngine, String serviceName, Operation op, int partitionId, int replicaIndex, int tryCount, long tryPauseMillis, long callTimeout, Callback<Object> callback, String executorName, boolean resultDeserialized) { this.logger = nodeEngine.getLogger(BasicInvocation.class); this.nodeEngine = nodeEngine; this.serviceName = serviceName; this.op = op; this.partitionId = partitionId; this.replicaIndex = replicaIndex; this.tryCount = tryCount; this.tryPauseMillis = tryPauseMillis; this.callTimeout = getCallTimeout(callTimeout); this.invocationFuture = new BasicInvocationFuture(this, callback); this.executorName = executorName; this.resultDeserialized = resultDeserialized; } abstract ExceptionAction onException(Throwable t); public String getServiceName() { return serviceName; } InternalPartition getPartition() { return nodeEngine.getPartitionService().getPartition(partitionId); } public int getReplicaIndex() { return replicaIndex; } public int getPartitionId() { return partitionId; } ExecutorService getAsyncExecutor() { return nodeEngine.getExecutionService().getExecutor(ExecutionService.ASYNC_EXECUTOR); } private long getCallTimeout(long callTimeout) { if (callTimeout > 0) { return callTimeout; } BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService; final long defaultCallTimeout = operationService.getDefaultCallTimeout(); if (op instanceof WaitSupport) { final long waitTimeoutMillis = op.getWaitTimeout(); if (waitTimeoutMillis > 0 && waitTimeoutMillis < Long.MAX_VALUE) { /* * final long minTimeout = Math.min(defaultCallTimeout, MIN_TIMEOUT); * long callTimeout = Math.min(waitTimeoutMillis, defaultCallTimeout); * callTimeout = Math.max(a, minTimeout); * return callTimeout; * * Below two lines are shortened version of above* * using min(max(x,y),z)=max(min(x,z),min(y,z)) */ final long max = Math.max(waitTimeoutMillis, MIN_TIMEOUT); return Math.min(max, defaultCallTimeout); } } return defaultCallTimeout; } public final BasicInvocationFuture invoke() { if (invokeCount > 0) { // no need to be pessimistic. throw new IllegalStateException("An invocation can not be invoked more than once!"); } if (op.getCallId() != 0) { throw new IllegalStateException("An operation[" + op + "] can not be used for multiple invocations!"); } try { setCallTimeout(op, callTimeout); setCallerAddress(op, nodeEngine.getThisAddress()); op.setNodeEngine(nodeEngine) .setServiceName(serviceName) .setPartitionId(partitionId) .setReplicaIndex(replicaIndex) .setExecutorName(executorName); if (op.getCallerUuid() == null) { op.setCallerUuid(nodeEngine.getLocalMember().getUuid()); } BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService; if (!operationService.scheduler.isInvocationAllowedFromCurrentThread(op) && !isMigrationOperation(op)) { throw new IllegalThreadStateException(Thread.currentThread() + " cannot make remote call: " + op); } doInvoke(); } catch (Exception e) { if (e instanceof RetryableException) { notify(e); } else { throw ExceptionUtil.rethrow(e); } } return invocationFuture; } private void resetAndReInvoke() { invokeCount = 0; potentialResponse = null; expectedBackupCount = -1; doInvoke(); } private void doInvoke() { if (!nodeEngine.isActive()) { remote = false; notify(new HazelcastInstanceNotActiveException()); return; } invTarget = getTarget(); invokeCount++; final Address thisAddress = nodeEngine.getThisAddress(); if (invTarget == null) { remote = false; if (nodeEngine.isActive()) { notify(new WrongTargetException(thisAddress, null, partitionId, replicaIndex, op.getClass().getName(), serviceName)); } else { notify(new HazelcastInstanceNotActiveException()); } return; } invTargetMember = nodeEngine.getClusterService().getMember(invTarget); if (!isJoinOperation(op) && invTargetMember == null) { notify(new TargetNotMemberException(invTarget, partitionId, op.getClass().getName(), serviceName)); return; } if (op.getPartitionId() != partitionId) { notify(new IllegalStateException("Partition id of operation: " + op.getPartitionId() + " is not equal to the partition id of invocation: " + partitionId)); return; } if (op.getReplicaIndex() != replicaIndex) { notify(new IllegalStateException("Replica index of operation: " + op.getReplicaIndex() + " is not equal to the replica index of invocation: " + replicaIndex)); return; } final BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService; setInvocationTime(op, nodeEngine.getClusterTime()); remote = !thisAddress.equals(invTarget); if (remote) { final long callId = operationService.registerInvocation(this); boolean sent = operationService.send(op, invTarget); if (!sent) { operationService.deregisterInvocation(callId); - notify(new RetryableIOException("Packet not responseReceived to -> " + invTarget)); + notify(new RetryableIOException("Packet not send to -> " + invTarget)); } } else { if (op instanceof BackupAwareOperation) { operationService.registerInvocation(this); } responseReceived = Boolean.FALSE; op.setResponseHandler(this); //todo: should move to the operationService. if (operationService.scheduler.isAllowedToRunInCurrentThread(op)) { operationService.runOperationOnCallingThread(op); } else { operationService.executeOperation(op); } } } private static Throwable getError(Object obj) { if (obj == null) { return null; } if (obj instanceof Throwable) { return (Throwable) obj; } if (!(obj instanceof NormalResponse)) { return null; } NormalResponse response = (NormalResponse) obj; if (!(response.getValue() instanceof Throwable)) { return null; } return (Throwable) response.getValue(); } @Override public void sendResponse(Object obj) { if (!RESPONSE_RECEIVED_FIELD_UPDATER.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) { throw new ResponseAlreadySentException("NormalResponse already responseReceived for callback: " + this + ", current-response: : " + obj); } notify(obj); } @Override public boolean isLocal() { return true; } public boolean isCallTarget(MemberImpl leftMember) { if (invTargetMember == null) { return leftMember.getAddress().equals(invTarget); } else { return leftMember.getUuid().equals(invTargetMember.getUuid()); } } //this method is called by the operation service to signal the invocation that something has happened, e.g. //a response is returned. //@Override public void notify(Object obj) { Object response = resolveResponse(obj); if (response == RETRY_RESPONSE) { handleRetryResponse(); return; } if (response == WAIT_RESPONSE) { handleWaitResponse(); return; } //if a regular response came and there are backups, we need to wait for the backs. //when the backups complete, the response will be send by the last backup. if (response instanceof NormalResponse && op instanceof BackupAwareOperation) { final NormalResponse resp = (NormalResponse) response; if (resp.getBackupCount() > 0) { waitForBackups(resp.getBackupCount(), 5, TimeUnit.SECONDS, resp); return; } } //we don't need to wait for a backup, so we can set the response immediately. invocationFuture.set(response); } private void handleWaitResponse() { invocationFuture.set(WAIT_RESPONSE); } private void handleRetryResponse() { if (invocationFuture.interrupted) { invocationFuture.set(INTERRUPTED_RESPONSE); } else { invocationFuture.set(WAIT_RESPONSE); final ExecutionService ex = nodeEngine.getExecutionService(); // fast retry for the first few invocations if (invokeCount < 5) { getAsyncExecutor().execute(this); } else { ex.schedule(ExecutionService.ASYNC_EXECUTOR, this, tryPauseMillis, TimeUnit.MILLISECONDS); } } } private Object resolveResponse(Object obj) { if (obj == null) { return NULL_RESPONSE; } Throwable error = getError(obj); if (error == null) { return obj; } if (error instanceof CallTimeoutException) { if (logger.isFinestEnabled()) { logger.finest("Call timed-out during wait-notify phase, retrying call: " + toString()); } if (op instanceof WaitSupport) { // decrement wait-timeout by call-timeout long waitTimeout = op.getWaitTimeout(); waitTimeout -= callTimeout; op.setWaitTimeout(waitTimeout); } invokeCount--; return RETRY_RESPONSE; } final ExceptionAction action = onException(error); final int localInvokeCount = invokeCount; if (action == ExceptionAction.RETRY_INVOCATION && localInvokeCount < tryCount) { if (localInvokeCount > 99 && localInvokeCount % 10 == 0) { logger.warning("Retrying invocation: " + toString() + ", Reason: " + error); } return RETRY_RESPONSE; } if (action == ExceptionAction.CONTINUE_WAIT) { return WAIT_RESPONSE; } return error; } protected abstract Address getTarget(); @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("BasicInvocation"); sb.append("{ serviceName='").append(serviceName).append('\''); sb.append(", op=").append(op); sb.append(", partitionId=").append(partitionId); sb.append(", replicaIndex=").append(replicaIndex); sb.append(", tryCount=").append(tryCount); sb.append(", tryPauseMillis=").append(tryPauseMillis); sb.append(", invokeCount=").append(invokeCount); sb.append(", callTimeout=").append(callTimeout); sb.append(", target=").append(invTarget); sb.append('}'); return sb.toString(); } private volatile int availableBackups; private volatile NormalResponse potentialResponse; private volatile int expectedBackupCount; //availableBackups is incremented while a lock is hold. @edu.umd.cs.findbugs.annotations.SuppressWarnings("VO_VOLATILE_INCREMENT") public void signalOneBackupComplete() { synchronized (this) { availableBackups++; if (expectedBackupCount == -1) { return; } if (expectedBackupCount != availableBackups) { return; } if (potentialResponse != null) { invocationFuture.set(potentialResponse); } } } private void waitForBackups(int backupCount, long timeout, TimeUnit unit, NormalResponse response) { synchronized (this) { this.expectedBackupCount = backupCount; if (availableBackups == expectedBackupCount) { invocationFuture.set(response); return; } this.potentialResponse = response; } nodeEngine.getExecutionService().schedule(ExecutionService.ASYNC_EXECUTOR, new Runnable() { @Override public void run() { synchronized (BasicInvocation.this) { if (expectedBackupCount == availableBackups) { return; } } if (nodeEngine.getClusterService().getMember(invTarget) != null) { synchronized (BasicInvocation.this) { if (BasicInvocation.this.potentialResponse != null) { invocationFuture.set(BasicInvocation.this.potentialResponse); BasicInvocation.this.potentialResponse = null; } } return; } resetAndReInvoke(); } }, timeout, unit); } @Override public void run() { doInvoke(); } }
true
true
private void doInvoke() { if (!nodeEngine.isActive()) { remote = false; notify(new HazelcastInstanceNotActiveException()); return; } invTarget = getTarget(); invokeCount++; final Address thisAddress = nodeEngine.getThisAddress(); if (invTarget == null) { remote = false; if (nodeEngine.isActive()) { notify(new WrongTargetException(thisAddress, null, partitionId, replicaIndex, op.getClass().getName(), serviceName)); } else { notify(new HazelcastInstanceNotActiveException()); } return; } invTargetMember = nodeEngine.getClusterService().getMember(invTarget); if (!isJoinOperation(op) && invTargetMember == null) { notify(new TargetNotMemberException(invTarget, partitionId, op.getClass().getName(), serviceName)); return; } if (op.getPartitionId() != partitionId) { notify(new IllegalStateException("Partition id of operation: " + op.getPartitionId() + " is not equal to the partition id of invocation: " + partitionId)); return; } if (op.getReplicaIndex() != replicaIndex) { notify(new IllegalStateException("Replica index of operation: " + op.getReplicaIndex() + " is not equal to the replica index of invocation: " + replicaIndex)); return; } final BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService; setInvocationTime(op, nodeEngine.getClusterTime()); remote = !thisAddress.equals(invTarget); if (remote) { final long callId = operationService.registerInvocation(this); boolean sent = operationService.send(op, invTarget); if (!sent) { operationService.deregisterInvocation(callId); notify(new RetryableIOException("Packet not responseReceived to -> " + invTarget)); } } else { if (op instanceof BackupAwareOperation) { operationService.registerInvocation(this); } responseReceived = Boolean.FALSE; op.setResponseHandler(this); //todo: should move to the operationService. if (operationService.scheduler.isAllowedToRunInCurrentThread(op)) { operationService.runOperationOnCallingThread(op); } else { operationService.executeOperation(op); } } }
private void doInvoke() { if (!nodeEngine.isActive()) { remote = false; notify(new HazelcastInstanceNotActiveException()); return; } invTarget = getTarget(); invokeCount++; final Address thisAddress = nodeEngine.getThisAddress(); if (invTarget == null) { remote = false; if (nodeEngine.isActive()) { notify(new WrongTargetException(thisAddress, null, partitionId, replicaIndex, op.getClass().getName(), serviceName)); } else { notify(new HazelcastInstanceNotActiveException()); } return; } invTargetMember = nodeEngine.getClusterService().getMember(invTarget); if (!isJoinOperation(op) && invTargetMember == null) { notify(new TargetNotMemberException(invTarget, partitionId, op.getClass().getName(), serviceName)); return; } if (op.getPartitionId() != partitionId) { notify(new IllegalStateException("Partition id of operation: " + op.getPartitionId() + " is not equal to the partition id of invocation: " + partitionId)); return; } if (op.getReplicaIndex() != replicaIndex) { notify(new IllegalStateException("Replica index of operation: " + op.getReplicaIndex() + " is not equal to the replica index of invocation: " + replicaIndex)); return; } final BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService; setInvocationTime(op, nodeEngine.getClusterTime()); remote = !thisAddress.equals(invTarget); if (remote) { final long callId = operationService.registerInvocation(this); boolean sent = operationService.send(op, invTarget); if (!sent) { operationService.deregisterInvocation(callId); notify(new RetryableIOException("Packet not send to -> " + invTarget)); } } else { if (op instanceof BackupAwareOperation) { operationService.registerInvocation(this); } responseReceived = Boolean.FALSE; op.setResponseHandler(this); //todo: should move to the operationService. if (operationService.scheduler.isAllowedToRunInCurrentThread(op)) { operationService.runOperationOnCallingThread(op); } else { operationService.executeOperation(op); } } }
diff --git a/src/main/java/org/mattstep/platform/samples/contact/MainModule.java b/src/main/java/org/mattstep/platform/samples/contact/MainModule.java index f78ac32..cc50529 100644 --- a/src/main/java/org/mattstep/platform/samples/contact/MainModule.java +++ b/src/main/java/org/mattstep/platform/samples/contact/MainModule.java @@ -1,20 +1,20 @@ package org.mattstep.platform.samples.contact; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.proofpoint.discovery.client.DiscoveryBinder; public class MainModule implements Module { public void configure(Binder binder) { binder.requireExplicitBindings(); binder.disableCircularProxies(); binder.bind(ContactResource.class).in(Scopes.SINGLETON); - DiscoveryBinder.discoveryBinder(binder).bindHttpAnnouncement("skeleton"); + DiscoveryBinder.discoveryBinder(binder).bindHttpAnnouncement("contact"); } }
true
true
public void configure(Binder binder) { binder.requireExplicitBindings(); binder.disableCircularProxies(); binder.bind(ContactResource.class).in(Scopes.SINGLETON); DiscoveryBinder.discoveryBinder(binder).bindHttpAnnouncement("skeleton"); }
public void configure(Binder binder) { binder.requireExplicitBindings(); binder.disableCircularProxies(); binder.bind(ContactResource.class).in(Scopes.SINGLETON); DiscoveryBinder.discoveryBinder(binder).bindHttpAnnouncement("contact"); }
diff --git a/AndBible/src/net/bible/android/control/page/CurrentPageManager.java b/AndBible/src/net/bible/android/control/page/CurrentPageManager.java index 10946fff..d6726beb 100644 --- a/AndBible/src/net/bible/android/control/page/CurrentPageManager.java +++ b/AndBible/src/net/bible/android/control/page/CurrentPageManager.java @@ -1,179 +1,180 @@ package net.bible.android.control.page; import net.bible.android.control.PassageChangeMediator; import net.bible.android.view.activity.base.CurrentActivityHolder; import org.apache.commons.lang.StringUtils; import org.crosswire.jsword.book.Book; import org.crosswire.jsword.book.BookCategory; import org.crosswire.jsword.passage.Key; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; public class CurrentPageManager { // use the same verse in the commentary and bible to keep them in sync private CurrentBibleVerse currentBibleVerse; private CurrentBiblePage currentBiblePage; private CurrentCommentaryPage currentCommentaryPage; private CurrentDictionaryPage currentDictionaryPage; private CurrentGeneralBookPage currentGeneralBookPage; private CurrentPage currentDisplayedPage; private static CurrentPageManager singleton; private static final String TAG = "CurrentPageManager"; static public CurrentPageManager getInstance() { if (singleton==null) { synchronized(CurrentPageManager.class) { if (singleton==null) { CurrentPageManager instance = new CurrentPageManager(); instance.currentBibleVerse = new CurrentBibleVerse(); instance.currentBiblePage = new CurrentBiblePage(instance.currentBibleVerse); instance.currentCommentaryPage = new CurrentCommentaryPage(instance.currentBibleVerse); instance.currentDictionaryPage = new CurrentDictionaryPage(); instance.currentGeneralBookPage = new CurrentGeneralBookPage(); instance.currentDisplayedPage = instance.currentBiblePage; singleton = instance; } } } return singleton; } public CurrentPage getCurrentPage() { return currentDisplayedPage; } public CurrentBiblePage getCurrentBible() { return currentBiblePage; } public CurrentCommentaryPage getCurrentCommentary() { return currentCommentaryPage; } public CurrentDictionaryPage getCurrentDictionary() { return currentDictionaryPage; } public CurrentGeneralBookPage getCurrentGeneralBook() { return currentGeneralBookPage; } - public CurrentPage setCurrentDocument(Book currentBook) { + public CurrentPage setCurrentDocument(Book nextDocument) { PassageChangeMediator.getInstance().onBeforeCurrentPageChanged(); - CurrentPage nextPage = getBookPage(currentBook.getBookCategory()); + CurrentPage nextPage = getBookPage(nextDocument.getBookCategory()); - boolean sameDoc = currentBook.equals(nextPage.getCurrentDocument()); + // is the next doc the same as the prev doc + boolean sameDoc = nextDocument.equals(nextPage.getCurrentDocument()); // must be in this order because History needs to grab the current doc before change - nextPage.setCurrentDocument(currentBook); + nextPage.setCurrentDocument(nextDocument); currentDisplayedPage = nextPage; // page will change due to above // if there is a valid share key or the doc (hence the key) in the next page is the same then show the page straight away - if (nextPage.isShareKeyBetweenDocs() || sameDoc) { + if ((nextPage.isShareKeyBetweenDocs() || sameDoc) && nextPage.getKey()!=null) { PassageChangeMediator.getInstance().onCurrentPageChanged(); } else { Context context = CurrentActivityHolder.getInstance().getCurrentActivity(); // pop up a key selection screen Intent intent = new Intent(context, nextPage.getKeyChooserActivity()); context.startActivity(intent); } return nextPage; } public CurrentPage setCurrentDocumentAndKey(Book currentBook, Key key) { PassageChangeMediator.getInstance().onBeforeCurrentPageChanged(); CurrentPage nextPage = getBookPage(currentBook.getBookCategory()); if (nextPage!=null) { try { nextPage.setInhibitChangeNotifications(true); nextPage.setCurrentDocument(currentBook); nextPage.setKey(key); currentDisplayedPage = nextPage; } finally { nextPage.setInhibitChangeNotifications(false); } } // valid key has been set so do not need to show a key chooser therefore just update main view PassageChangeMediator.getInstance().onCurrentPageChanged(); return nextPage; } private CurrentPage getBookPage(BookCategory bookCategory) { CurrentPage bookPage = null; if (bookCategory.equals(BookCategory.BIBLE)) { bookPage = currentBiblePage; } else if (bookCategory.equals(BookCategory.COMMENTARY)) { bookPage = currentCommentaryPage; } else if (bookCategory.equals(BookCategory.DICTIONARY)) { bookPage = currentDictionaryPage; } else if (bookCategory.equals(BookCategory.GENERAL_BOOK)) { bookPage = currentGeneralBookPage; } return bookPage; } /** called during app close down to save state * * @param outState */ public void saveState(SharedPreferences outState) { Log.i(TAG, "**** save state"); currentBiblePage.saveState(outState); currentCommentaryPage.saveState(outState); currentDictionaryPage.saveState(outState); currentGeneralBookPage.saveState(outState); SharedPreferences.Editor editor = outState.edit(); editor.putString("currentPageCategory", currentDisplayedPage.getBookCategory().getName()); editor.commit(); } /** called during app start-up to restore previous state * * @param inState */ public void restoreState(SharedPreferences inState) { Log.i(TAG, "**** restore state"); currentBiblePage.restoreState(inState); currentCommentaryPage.restoreState(inState); currentDictionaryPage.restoreState(inState); currentGeneralBookPage.restoreState(inState); String restoredPageCategoryName = inState.getString("currentPageCategory", null); if (StringUtils.isNotEmpty(restoredPageCategoryName)) { BookCategory restoredBookCategory = BookCategory.fromString(restoredPageCategoryName); currentDisplayedPage = getBookPage(restoredBookCategory); } // force an update here from default chapter/verse PassageChangeMediator.getInstance().onCurrentPageChanged(); PassageChangeMediator.getInstance().onCurrentPageDetailChanged(); } public boolean isCommentaryShown() { return currentCommentaryPage == currentDisplayedPage; } public boolean isBibleShown() { return currentBiblePage == currentDisplayedPage; } public boolean isDictionaryShown() { return currentDictionaryPage == currentDisplayedPage; } public boolean isGenBookShown() { return currentGeneralBookPage == currentDisplayedPage; } public void showBible() { PassageChangeMediator.getInstance().onBeforeCurrentPageChanged(); currentDisplayedPage = currentBiblePage; PassageChangeMediator.getInstance().onCurrentPageChanged(); } }
false
true
public CurrentPage setCurrentDocument(Book currentBook) { PassageChangeMediator.getInstance().onBeforeCurrentPageChanged(); CurrentPage nextPage = getBookPage(currentBook.getBookCategory()); boolean sameDoc = currentBook.equals(nextPage.getCurrentDocument()); // must be in this order because History needs to grab the current doc before change nextPage.setCurrentDocument(currentBook); currentDisplayedPage = nextPage; // page will change due to above // if there is a valid share key or the doc (hence the key) in the next page is the same then show the page straight away if (nextPage.isShareKeyBetweenDocs() || sameDoc) { PassageChangeMediator.getInstance().onCurrentPageChanged(); } else { Context context = CurrentActivityHolder.getInstance().getCurrentActivity(); // pop up a key selection screen Intent intent = new Intent(context, nextPage.getKeyChooserActivity()); context.startActivity(intent); } return nextPage; }
public CurrentPage setCurrentDocument(Book nextDocument) { PassageChangeMediator.getInstance().onBeforeCurrentPageChanged(); CurrentPage nextPage = getBookPage(nextDocument.getBookCategory()); // is the next doc the same as the prev doc boolean sameDoc = nextDocument.equals(nextPage.getCurrentDocument()); // must be in this order because History needs to grab the current doc before change nextPage.setCurrentDocument(nextDocument); currentDisplayedPage = nextPage; // page will change due to above // if there is a valid share key or the doc (hence the key) in the next page is the same then show the page straight away if ((nextPage.isShareKeyBetweenDocs() || sameDoc) && nextPage.getKey()!=null) { PassageChangeMediator.getInstance().onCurrentPageChanged(); } else { Context context = CurrentActivityHolder.getInstance().getCurrentActivity(); // pop up a key selection screen Intent intent = new Intent(context, nextPage.getKeyChooserActivity()); context.startActivity(intent); } return nextPage; }
diff --git a/src/com/orangeleap/tangerine/web/filters/OpenSpringTransactionInViewFilter.java b/src/com/orangeleap/tangerine/web/filters/OpenSpringTransactionInViewFilter.java index eb2f3ace..9812a4d0 100644 --- a/src/com/orangeleap/tangerine/web/filters/OpenSpringTransactionInViewFilter.java +++ b/src/com/orangeleap/tangerine/web/filters/OpenSpringTransactionInViewFilter.java @@ -1,117 +1,117 @@ /* * Copyright (c) 2009. Orange Leap Inc. Active Constituent * Relationship Management Platform. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.orangeleap.tangerine.web.filters; import com.orangeleap.tangerine.util.OLLogger; import com.orangeleap.tangerine.util.RulesStack; import com.orangeleap.tangerine.util.TaskStack; import org.apache.commons.logging.Log; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class OpenSpringTransactionInViewFilter extends OncePerRequestFilter { protected final Log logger = OLLogger.getLog(getClass()); private Object getBean(HttpServletRequest request, String bean) { ServletContext servletContext = request.getSession().getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); return wac.getBean(bean); } private boolean suppressStartTransaction(HttpServletRequest request) { String url = request.getRequestURL().toString(); return FilterUtil.isResourceRequest(request) || url.endsWith("/import.htm") ; } protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (TransactionSynchronizationManager.isActualTransactionActive() || suppressStartTransaction(request)) { filterChain.doFilter(request, response); return; } if (RulesStack.getStack().size() > 0) { logger.error("RulesStack not previously cleared."); RulesStack.getStack().clear(); } PlatformTransactionManager txManager = (PlatformTransactionManager) getBean(request, "transactionManager"); logger.debug(request.getRequestURL() + ", txManager = " + txManager); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("TxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null; try { status = txManager.getTransaction(def); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } try { filterChain.doFilter(request, response); } catch (Throwable ex) { try { txManager.rollback(status); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException(ex); } try { txManager.commit(status); TaskStack.execute(); } catch (Exception e) { // Don't generally log transactions marked as rollback only by service or validation exceptions; logged elsewhere. - logger.debug(e); + logger.error(e); } } }
true
true
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (TransactionSynchronizationManager.isActualTransactionActive() || suppressStartTransaction(request)) { filterChain.doFilter(request, response); return; } if (RulesStack.getStack().size() > 0) { logger.error("RulesStack not previously cleared."); RulesStack.getStack().clear(); } PlatformTransactionManager txManager = (PlatformTransactionManager) getBean(request, "transactionManager"); logger.debug(request.getRequestURL() + ", txManager = " + txManager); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("TxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null; try { status = txManager.getTransaction(def); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } try { filterChain.doFilter(request, response); } catch (Throwable ex) { try { txManager.rollback(status); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException(ex); } try { txManager.commit(status); TaskStack.execute(); } catch (Exception e) { // Don't generally log transactions marked as rollback only by service or validation exceptions; logged elsewhere. logger.debug(e); } }
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (TransactionSynchronizationManager.isActualTransactionActive() || suppressStartTransaction(request)) { filterChain.doFilter(request, response); return; } if (RulesStack.getStack().size() > 0) { logger.error("RulesStack not previously cleared."); RulesStack.getStack().clear(); } PlatformTransactionManager txManager = (PlatformTransactionManager) getBean(request, "transactionManager"); logger.debug(request.getRequestURL() + ", txManager = " + txManager); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("TxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null; try { status = txManager.getTransaction(def); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } try { filterChain.doFilter(request, response); } catch (Throwable ex) { try { txManager.rollback(status); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException(ex); } try { txManager.commit(status); TaskStack.execute(); } catch (Exception e) { // Don't generally log transactions marked as rollback only by service or validation exceptions; logged elsewhere. logger.error(e); } }
diff --git a/src/BindTest.java b/src/BindTest.java index f6ed481..d263814 100644 --- a/src/BindTest.java +++ b/src/BindTest.java @@ -1,42 +1,42 @@ import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.io.IOException; import java.lang.Integer; import java.lang.ArrayIndexOutOfBoundsException; public class BindTest { public static void main(String[] args) { try{ Integer port = Integer.valueOf(args[0]); ServerSocket ss = null; /* workaround a macos|windows problem */ String os = System.getProperty("os.name"); if(os != null && os.equalsIgnoreCase("Windows")) ss = new ServerSocket(port.intValue()); else { ss = new ServerSocket(); ss.setReuseAddress(false); + ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); + if(!ss.isBound()) + System.exit(1); } ss.setSoTimeout(200); - ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); - if(!ss.isBound()) - System.exit(1); ss.accept(); }catch (SocketTimeoutException ste){ }catch (SocketException e){ System.exit(1); }catch (IOException io){ System.exit(2); }catch (ArrayIndexOutOfBoundsException aioobe){ System.err.println("Please give a port number as the first parameter!"); System.exit(-1); } System.exit(0); } }
false
true
public static void main(String[] args) { try{ Integer port = Integer.valueOf(args[0]); ServerSocket ss = null; /* workaround a macos|windows problem */ String os = System.getProperty("os.name"); if(os != null && os.equalsIgnoreCase("Windows")) ss = new ServerSocket(port.intValue()); else { ss = new ServerSocket(); ss.setReuseAddress(false); } ss.setSoTimeout(200); ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); if(!ss.isBound()) System.exit(1); ss.accept(); }catch (SocketTimeoutException ste){ }catch (SocketException e){ System.exit(1); }catch (IOException io){ System.exit(2); }catch (ArrayIndexOutOfBoundsException aioobe){ System.err.println("Please give a port number as the first parameter!"); System.exit(-1); } System.exit(0); }
public static void main(String[] args) { try{ Integer port = Integer.valueOf(args[0]); ServerSocket ss = null; /* workaround a macos|windows problem */ String os = System.getProperty("os.name"); if(os != null && os.equalsIgnoreCase("Windows")) ss = new ServerSocket(port.intValue()); else { ss = new ServerSocket(); ss.setReuseAddress(false); ss.bind(new InetSocketAddress("127.0.0.1:", port.intValue())); if(!ss.isBound()) System.exit(1); } ss.setSoTimeout(200); ss.accept(); }catch (SocketTimeoutException ste){ }catch (SocketException e){ System.exit(1); }catch (IOException io){ System.exit(2); }catch (ArrayIndexOutOfBoundsException aioobe){ System.err.println("Please give a port number as the first parameter!"); System.exit(-1); } System.exit(0); }
diff --git a/src/GUI/GameView.java b/src/GUI/GameView.java index ca80559..2701059 100644 --- a/src/GUI/GameView.java +++ b/src/GUI/GameView.java @@ -1,214 +1,216 @@ package GUI; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Observable; import java.util.Observer; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import Character.CivilianCharacter; import Character.PlayerCharacter; import Character.ShopCharacter; import Engine.GameEngine; import Main.Main; /** * The main window that handles what should be displayed * @author kristoffer * */ public class GameView extends JFrame implements Observer, Runnable, Serializable{ // fields: private static final long serialVersionUID = 11L; private GameEngine engine; private JLayeredPane layers; private GamePanel gamePanel; private ShopPanel shopPanel; private InventoryPanel inventoryPanel; private JFileChooser dialog; // constants: private static final String GAME_TITLE = "GAMETITLE"; private static final int SCREEN_WIDTH = 800; private static final int SCREEN_HEIGHT = 640; /** * Constructor * @param engine */ public GameView(GameEngine engine){ this.engine = engine; // Create the layered panel and add each panel layers = new JLayeredPane(); layers.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); add(layers); createPanels(); // Create menubar dialog = new JFileChooser(System.getProperty("user.dir")); makeMenu(); addObservers(); makeFrame(); } /** * Create all panels and adds them to each layer */ private void createPanels(){ gamePanel = new GamePanel(engine); layers.add(gamePanel, JLayeredPane.DEFAULT_LAYER); shopPanel = new ShopPanel(); layers.add(shopPanel, JLayeredPane.MODAL_LAYER); inventoryPanel = new InventoryPanel(); layers.add(inventoryPanel, JLayeredPane.POPUP_LAYER); } /** * Creates a menubar with 3 options: Load, save and quit * @author Jimmy */ private void makeMenu(){ //create menu and menubars JMenuBar bar = new JMenuBar(); setJMenuBar(bar); JMenu fileMenu = new JMenu("File"); bar.add(fileMenu); JMenuItem open = new JMenuItem("Open"); open.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ - load(dialog.getSelectedFile().getAbsolutePath()); + if(dialog.showOpenDialog(null)== JFileChooser.APPROVE_OPTION) + load(dialog.getSelectedFile().getAbsolutePath()); } }); fileMenu.add(open); JMenuItem save = new JMenuItem("Save"); - open.addActionListener(new ActionListener(){ + save.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ - save(dialog.getSelectedFile().getAbsolutePath()); + if(dialog.showSaveDialog(null)== JFileChooser.APPROVE_OPTION) + save(dialog.getSelectedFile().getAbsolutePath()); } }); fileMenu.add(save); JMenuItem quit = new JMenuItem("Quit"); - open.addActionListener(new ActionListener(){ + quit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); fileMenu.add(quit); } /** * Saves the current state of the game * @author Jimmy * @param fileName */ private void save(String fileName){ try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName)); out.writeObject(engine); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(0); } } /** * Loads a current state of the game * @author Jimmy * @param fileName */ private void load(String fileName){ try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName)); GameEngine gE = (GameEngine)in.readObject(); in.close(); engine.setCharacterList(gE.getCharacters()); engine.setCollision(gE.getCollision()); engine.setPlayer(gE.getPlayer()); engine.setWorld(gE.getWorld()); Main.restart(); } catch(Exception e) { e.printStackTrace(); System.exit(0); } } /** * Adds all observable objects to its observer */ private void addObservers(){ for(Observable c : engine.getCharacters()){ c.addObserver(this); } // add observer to player engine.getPlayer().addObserver(this); } /** * Creates the window */ private void makeFrame(){ setTitle(GAME_TITLE); setSize(SCREEN_WIDTH, SCREEN_HEIGHT); setBackground(Color.BLACK); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); pack(); setVisible(true); } /** * Updates the window constanlty */ @Override public void run() { while(true){ // Here goes the things that should be updated constantly... gamePanel.repaint(); try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();} } } /** * If something changed by an observable object, update is called */ @Override public void update(Observable o, Object arg) { if(o instanceof ShopCharacter && arg instanceof PlayerCharacter){ shopPanel.update( (ShopCharacter) o, (PlayerCharacter) arg); }else if( o instanceof CivilianCharacter && arg instanceof PlayerCharacter){ // To-do }else if( o instanceof PlayerCharacter && arg instanceof String){ inventoryPanel.update( (PlayerCharacter) o); System.out.println("Inventory!"); } } }
false
true
private void makeMenu(){ //create menu and menubars JMenuBar bar = new JMenuBar(); setJMenuBar(bar); JMenu fileMenu = new JMenu("File"); bar.add(fileMenu); JMenuItem open = new JMenuItem("Open"); open.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ load(dialog.getSelectedFile().getAbsolutePath()); } }); fileMenu.add(open); JMenuItem save = new JMenuItem("Save"); open.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ save(dialog.getSelectedFile().getAbsolutePath()); } }); fileMenu.add(save); JMenuItem quit = new JMenuItem("Quit"); open.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); fileMenu.add(quit); }
private void makeMenu(){ //create menu and menubars JMenuBar bar = new JMenuBar(); setJMenuBar(bar); JMenu fileMenu = new JMenu("File"); bar.add(fileMenu); JMenuItem open = new JMenuItem("Open"); open.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(dialog.showOpenDialog(null)== JFileChooser.APPROVE_OPTION) load(dialog.getSelectedFile().getAbsolutePath()); } }); fileMenu.add(open); JMenuItem save = new JMenuItem("Save"); save.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(dialog.showSaveDialog(null)== JFileChooser.APPROVE_OPTION) save(dialog.getSelectedFile().getAbsolutePath()); } }); fileMenu.add(save); JMenuItem quit = new JMenuItem("Quit"); quit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); fileMenu.add(quit); }
diff --git a/module/exi/src/main/java/fabric/module/exi/cpp/ElementMetadata.java b/module/exi/src/main/java/fabric/module/exi/cpp/ElementMetadata.java index 77f8299..1eab4e0 100644 --- a/module/exi/src/main/java/fabric/module/exi/cpp/ElementMetadata.java +++ b/module/exi/src/main/java/fabric/module/exi/cpp/ElementMetadata.java @@ -1,452 +1,453 @@ /** 27.03.2012 15:01 */ package fabric.module.exi.cpp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.ArrayList; import java.util.HashMap; import fabric.wsdlschemaparser.schema.FElement; import fabric.wsdlschemaparser.schema.FList; import fabric.wsdlschemaparser.schema.FSchemaTypeHelper; import fabric.wsdlschemaparser.schema.SchemaHelper; // TODO: Remove unused imports import exi.events.ExiEventCode; import exi.events.ExiMalformedEventCodeException; /** * This class is a container for XML element metadata. While * the treewalker processes an XML Schema file, information * about XML elements is collected in a Queue of ElementMetadata * objects. The data is later used to generate the serialization * and deserialization methods in EXIConverter class dynamically. * * @author seidel, reichart */ public class ElementMetadata implements Comparable<ElementMetadata> { /** Logger object */ private static final Logger LOGGER = LoggerFactory.getLogger(ElementMetadata.class); /** Mapping from Fabric type names (FInt, FString etc.) to EXI built-in type names */ private static HashMap<String, String> typesFabricToEXI = new HashMap<String, String>(); /** Mapping from EXI built-in type names to C++ types */ private static HashMap<String, String> typesEXIToCpp = new HashMap<String, String>(); static { // Initialize type mappings ElementMetadata.createMappingFabricToEXI(); ElementMetadata.createMappingEXIToCpp(); } /** XML element is a single value */ public static final int XML_ATOMIC_VALUE = 0; /** XML element is a list that may contain multiple values */ public static final int XML_LIST = 1; /** XML element is an array that may contain multiple values */ public static final int XML_ARRAY = 2; // TODO: Constant added public static final int CUSTOM_TYPED = 3; /** Name of the XML element */ private String elementName; /** Name of the parent XML element */ private String parentName; /** EXI type of XML element content (e.g. Boolean, Integer or String) */ private String elementEXIType; /** Type of the XML element (e.g. atomic value, list or array) */ private int type; /** EXI event code within the XML Schema document structure */ private ExiEventCode exiEventCode; // TODO: EXIficient grammar builder will return event code as int /** * Parameterized constructor. * * @param elementName XML element name * @param elementEXIType EXI type of element content (e.g. Boolean, * Integer or String) * @param type XML element type (atomic value, list or array) * @param exiEventCode EXI event code */ public ElementMetadata(final String elementName, final String elementEXIType, final int type, final ExiEventCode exiEventCode) { this.elementName = elementName; this.elementEXIType = elementEXIType; this.type = type; this.exiEventCode = exiEventCode; // Validate support for EXI type ElementMetadata.checkEXITypeSupport(this.elementEXIType); } /** * Parameterized constructor creates ElementMetadata object * from an FElement object passed through from the Fabric * treewalker. * * @param element FElement object passed through from treewalker */ public ElementMetadata(final FElement element) { // Set XML element name this.elementName = element.getName(); // TODO: Line added - boolean isCustomTyped = !SchemaHelper.isBuiltinTypedElement(element); +// boolean isCustomTyped = !SchemaHelper.isBuiltinTypedElement(element); +// LOGGER.debug(">>> " + element.getName() + " is top-level: " + element.isTopLevel()); // TODO: Remove // Element is an XML list - if (FSchemaTypeHelper.isList(element) && !isCustomTyped) + if (FSchemaTypeHelper.isList(element)) { FList listType = (FList)element.getSchemaType(); this.elementEXIType = this.getEXITypeName(listType.getItemType().getClass().getSimpleName()); this.type = ElementMetadata.XML_LIST; } // Element is an XML array else if (FSchemaTypeHelper.isArray(element)) { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.XML_ARRAY; } // TODO: Block added // Element is custom typed - else if (isCustomTyped) + else if (!element.isTopLevel()) { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.CUSTOM_TYPED; } // Element is an atomic value else { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.XML_ATOMIC_VALUE; } // Set EXI event code try { this.exiEventCode = new ExiEventCode(0); } catch (ExiMalformedEventCodeException e) { e.printStackTrace(); // TODO: Properly handle exception } // Validate support for EXI type ElementMetadata.checkEXITypeSupport(this.elementEXIType); } /** * Parameterized constructor creates ElementMetadata object * from an FElement object and stores the name of the parent * XML element. * * @param element FElement object passed through from treewalker * @param parentName Name of the parent XML element */ public ElementMetadata(final FElement element, final String parentName) { // Set element metadata this(element); // Set name of parent XML element this.parentName = parentName; } /** * Setter for XML element name. * * @param elementName XML element name */ public void setElementName(final String elementName) { this.elementName = elementName; } /** * Getter for XML element name. * * @return XML element name */ public String getElementName() { return this.elementName; } /** * Setter for parent XML element name. * * @param parentName Parent XML element name */ public void setParentName(final String parentName) { this.parentName = parentName; } /** * Getter for parent XML element name. * * @return Parent XML element name */ public String getParentName() { return this.parentName; } /** * Setter for EXI element content type. * * @param elementEXIType EXI element content type */ public void setElementEXIType(final String elementEXIType) { this.elementEXIType = elementEXIType; } /** * Getter for EXI element content type. * * @return EXI element content type */ public String getElementEXIType() { return this.elementEXIType; } /** * Getter for C++ element content type. * * @return C++ element content type */ public String getElementCppType() { return this.getCppTypeName(this.elementEXIType); } /** * Setter for XML element type (e.g. atomic value, list or array). * * @param type XML element type */ public void setType(final int type) { this.type = type; } /** * Getter for XML element type. * * @return XML element type */ public int getType() { return this.type; } /** * Setter for EXI event code. * * @param exiEventCode EXI event code */ public void setEXIEventCode(final ExiEventCode exiEventCode) { this.exiEventCode = exiEventCode; } /** * Getter for EXI event code. * * @return EXI event code */ public int getEXIEventCode() { // TODO: This is probably not correct yet. Check which part of the // event code we need or how all parts must be written to EXI stream. return Integer.valueOf(this.exiEventCode.getPart(0)); } /** * Clone ElementMetadata object and return a deep copy. * * @return Cloned ElementMetadata object */ @Override public ElementMetadata clone() { ElementMetadata result = null; try { ExiEventCode c = new ExiEventCode(exiEventCode.getPart(0), exiEventCode.getPart(1), exiEventCode.getPart(2)); result = new ElementMetadata(this.elementName, this.elementEXIType, this.type, c); } catch (ExiMalformedEventCodeException e) { e.printStackTrace(); // TODO: Properly handle exception } result.setParentName(this.parentName); return result; } /** * Compare two ElementMetadata objects with each other. The * element name is used for the comparison here. * * @param elementMetadata ElementMetadata object to compare with * * @return Integer value to represent the order of two objects */ @Override public int compareTo(final ElementMetadata elementMetadata) { return this.elementName.compareTo(elementMetadata.elementName); } /** * Private helper method to get the EXI built-in type name * (e.g. Boolean, Integer or String) for one of Fabric's * XML Schema type names (e.g. FBoolean, FInt or FString). * * @param schemaTypeName Fabric type name * * @return Corresponding EXI built-in type name * * @throws IllegalArgumentException No matching mapping found */ private String getEXITypeName(final String schemaTypeName) throws IllegalArgumentException { // Return mapping if available if (typesFabricToEXI.containsKey(schemaTypeName)) { LOGGER.debug(String.format("Mapped Fabric data type '%s' to EXI built-in type '%s'.", schemaTypeName, typesFabricToEXI.get(schemaTypeName))); return typesFabricToEXI.get(schemaTypeName); } throw new IllegalArgumentException(String.format("No mapping found for XML datatype '%s'.", schemaTypeName)); } /** * Private helper method to get the C++ type name (e.g. * bool, int or char) for one of the EXI built-in type * names (e.g. Boolean, Integer or String). * * @param exiTypeName EXI built-in type name * * @return Corresponding C++ type name * * @throws IllegalArgumentException No matching mapping found */ private String getCppTypeName(final String exiTypeName) throws IllegalArgumentException { // Return mapping if available if (typesEXIToCpp.containsKey(exiTypeName)) { LOGGER.debug(String.format("Mapped EXI built-in type '%s' to C++ type '%s'.", exiTypeName, typesEXIToCpp.get(exiTypeName))); return typesEXIToCpp.get(exiTypeName); } throw new IllegalArgumentException(String.format("No mapping found for EXI datatype '%s'.", exiTypeName)); } /** * Private helper method to populate the mapping of Fabric's * XML Schema type names to EXI built-in type names. */ private static void createMappingFabricToEXI() { typesFabricToEXI.put("FBoolean", "Boolean"); typesFabricToEXI.put("FFloat", "Float"); typesFabricToEXI.put("FDouble", "Float"); typesFabricToEXI.put("FByte", "NBitUnsignedInteger"); typesFabricToEXI.put("FUnsignedByte", "NBitUnsignedInteger"); typesFabricToEXI.put("FShort", "Integer"); typesFabricToEXI.put("FUnsignedShort", "Integer"); typesFabricToEXI.put("FInt", "Integer"); typesFabricToEXI.put("FInteger", "Integer"); typesFabricToEXI.put("FPositiveInteger", "UnsignedInteger"); typesFabricToEXI.put("FUnsignedInt", "UnsignedInteger"); typesFabricToEXI.put("FLong", "Integer"); typesFabricToEXI.put("FUnsignedLong", "UnsignedInteger"); typesFabricToEXI.put("FDecimal", "Decimal"); typesFabricToEXI.put("FString", "String"); typesFabricToEXI.put("FHexBinary", "Binary"); typesFabricToEXI.put("FBase64Binary", "Binary"); typesFabricToEXI.put("FDateTime", "DateTime"); typesFabricToEXI.put("FTime", "DateTime"); typesFabricToEXI.put("FDate", "DateTime"); typesFabricToEXI.put("FDay", "DateTime"); typesFabricToEXI.put("FMonth", "DateTime"); typesFabricToEXI.put("FMonthDay", "DateTime"); typesFabricToEXI.put("FYear", "DateTime"); typesFabricToEXI.put("FYearMonth", "DateTime"); typesFabricToEXI.put("FDuration", "String"); typesFabricToEXI.put("FNOTATION", "String"); typesFabricToEXI.put("FQName", "String"); typesFabricToEXI.put("FName", "String"); typesFabricToEXI.put("FNCName", "String"); typesFabricToEXI.put("FNegativeInteger", "Integer"); typesFabricToEXI.put("FNMTOKEN", "String"); typesFabricToEXI.put("FNonNegativeInteger", "UnsignedInteger"); typesFabricToEXI.put("FNonPositiveInteger", "Integer"); typesFabricToEXI.put("FNormalizedString", "String"); typesFabricToEXI.put("FToken", "String"); typesFabricToEXI.put("FAnyURI", "String"); typesFabricToEXI.put("FAny", "String"); } /** * Private helper method to populate the mapping of EXI * built-in type names to C++ type names. */ private static void createMappingEXIToCpp() { typesEXIToCpp.put("Boolean", "bool"); typesEXIToCpp.put("Float", "xsd_float_t"); typesEXIToCpp.put("String", "const char*"); typesEXIToCpp.put("Decimal", "char*"); typesEXIToCpp.put("Integer", "int32"); typesEXIToCpp.put("UnsignedInteger", "uint32"); typesEXIToCpp.put("NBitUnsignedInteger", "unsigned int"); } /** * Private helper method to check whether a desired EXI type * is supported by our C++ EXI implementation or not. We do * currently not support all EXI types, e.g. there is no * implementation for EXI string tables yet. * * In case of an unsupported EXI type an exception is raised. * * @param exiTypeName EXI type name * * @throws UnsupportedOperationException EXI type not supported */ private static void checkEXITypeSupport(final String exiTypeName) { // Create a list of supported EXI types List<String> supportedEXITypes = new ArrayList<String>(); supportedEXITypes.add("Boolean"); supportedEXITypes.add("Float"); // supportedEXITypes.add("String"); // TODO: Add support for String // supportedEXITypes.add("Decimal"); // TODO: Add support for Decimal supportedEXITypes.add("Integer"); supportedEXITypes.add("UnsignedInteger"); supportedEXITypes.add("NBitUnsignedInteger"); // Validate desired EXI type if (!supportedEXITypes.contains(exiTypeName)) { throw new UnsupportedOperationException(String.format("EXI data type '%s' is not supported yet.", exiTypeName)); } } }
false
true
public ElementMetadata(final FElement element) { // Set XML element name this.elementName = element.getName(); // TODO: Line added boolean isCustomTyped = !SchemaHelper.isBuiltinTypedElement(element); // Element is an XML list if (FSchemaTypeHelper.isList(element) && !isCustomTyped) { FList listType = (FList)element.getSchemaType(); this.elementEXIType = this.getEXITypeName(listType.getItemType().getClass().getSimpleName()); this.type = ElementMetadata.XML_LIST; } // Element is an XML array else if (FSchemaTypeHelper.isArray(element)) { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.XML_ARRAY; } // TODO: Block added // Element is custom typed else if (isCustomTyped) { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.CUSTOM_TYPED; } // Element is an atomic value else { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.XML_ATOMIC_VALUE; } // Set EXI event code try { this.exiEventCode = new ExiEventCode(0); } catch (ExiMalformedEventCodeException e) { e.printStackTrace(); // TODO: Properly handle exception } // Validate support for EXI type ElementMetadata.checkEXITypeSupport(this.elementEXIType); }
public ElementMetadata(final FElement element) { // Set XML element name this.elementName = element.getName(); // TODO: Line added // boolean isCustomTyped = !SchemaHelper.isBuiltinTypedElement(element); // LOGGER.debug(">>> " + element.getName() + " is top-level: " + element.isTopLevel()); // TODO: Remove // Element is an XML list if (FSchemaTypeHelper.isList(element)) { FList listType = (FList)element.getSchemaType(); this.elementEXIType = this.getEXITypeName(listType.getItemType().getClass().getSimpleName()); this.type = ElementMetadata.XML_LIST; } // Element is an XML array else if (FSchemaTypeHelper.isArray(element)) { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.XML_ARRAY; } // TODO: Block added // Element is custom typed else if (!element.isTopLevel()) { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.CUSTOM_TYPED; } // Element is an atomic value else { this.elementEXIType = this.getEXITypeName(element.getSchemaType().getClass().getSimpleName()); this.type = ElementMetadata.XML_ATOMIC_VALUE; } // Set EXI event code try { this.exiEventCode = new ExiEventCode(0); } catch (ExiMalformedEventCodeException e) { e.printStackTrace(); // TODO: Properly handle exception } // Validate support for EXI type ElementMetadata.checkEXITypeSupport(this.elementEXIType); }
diff --git a/src/loader/FileBeacon.java b/src/loader/FileBeacon.java index c0b8a15..3503f49 100644 --- a/src/loader/FileBeacon.java +++ b/src/loader/FileBeacon.java @@ -1,70 +1,70 @@ /* * Copyright (c) 2009-2012 Daniel Oom, see license.txt for more info. */ package loader; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; public class FileBeacon implements Closeable { private static final String DATA_DIR = "data/"; private static final String DATA_ARCHIVE = "data.zip"; private final File dataDir, dataArchive; private final ZipFile zipFile; public FileBeacon(File dir) throws ZipException, IOException { assert dir != null; if (!dir.exists()) { throw new FileNotFoundException(dir.getAbsolutePath()); } dataDir = new File(dir, DATA_DIR); dataArchive = new File(dir, DATA_ARCHIVE); if (dataArchive.exists()) { zipFile = new ZipFile(dataArchive); } else { zipFile = null; } - if (!dataDir.exists()) { - throw new FileNotFoundException(dataDir.getAbsolutePath()); + if (zipFile == null && !dataDir.exists()) { + throw new FileNotFoundException("Data Not Found"); } } public InputStream getReader(String id) throws IOException { assert id != null; File f = new File(dataDir, id); if (f.exists()) { // Read file from directory return new FileInputStream(f); } if (zipFile != null) { ZipEntry entry = zipFile.getEntry(id); if (entry != null) { return zipFile.getInputStream(entry); } } throw new FileNotFoundException(id); } @Override public void close() throws IOException { if (zipFile != null) { zipFile.close(); } } }
true
true
public FileBeacon(File dir) throws ZipException, IOException { assert dir != null; if (!dir.exists()) { throw new FileNotFoundException(dir.getAbsolutePath()); } dataDir = new File(dir, DATA_DIR); dataArchive = new File(dir, DATA_ARCHIVE); if (dataArchive.exists()) { zipFile = new ZipFile(dataArchive); } else { zipFile = null; } if (!dataDir.exists()) { throw new FileNotFoundException(dataDir.getAbsolutePath()); } }
public FileBeacon(File dir) throws ZipException, IOException { assert dir != null; if (!dir.exists()) { throw new FileNotFoundException(dir.getAbsolutePath()); } dataDir = new File(dir, DATA_DIR); dataArchive = new File(dir, DATA_ARCHIVE); if (dataArchive.exists()) { zipFile = new ZipFile(dataArchive); } else { zipFile = null; } if (zipFile == null && !dataDir.exists()) { throw new FileNotFoundException("Data Not Found"); } }
diff --git a/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesPermissions.java b/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesPermissions.java index 7f01b90..52dd37d 100644 --- a/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesPermissions.java +++ b/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolvesPermissions.java @@ -1,45 +1,49 @@ package com.mikeprimm.bukkit.AngryWolves; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; /** * Permissions and GroupManager handling - inspired by BigBrother code * @author mike * */ public class AngryWolvesPermissions { private enum Handler { NONE, PERMISSIONS }; private static Handler our_handler; private static Permissions permissions_plugin; private static PermissionHandler handler; public static void initialize(Server server) { Plugin perm = server.getPluginManager().getPlugin("Permissions"); if(perm != null) { - our_handler = Handler.PERMISSIONS; - permissions_plugin = (Permissions)perm; - handler = permissions_plugin.getHandler(); + try { + permissions_plugin = (Permissions)perm; + handler = permissions_plugin.getHandler(); + our_handler = Handler.PERMISSIONS; + AngryWolves.log.info("[AngryWolves] Using Permissions " + permissions_plugin.getDescription().getVersion() + " for access control"); + } catch (NoClassDefFoundError ncdf) { + } } - else { - our_handler = Handler.NONE; + if(our_handler == Handler.NONE) { + AngryWolves.log.info("[AngryWolves] Using Bukkit API for access control"); } } /* Fetch specific permission for given player */ public static boolean permission(Player player, String perm) { switch(our_handler) { case PERMISSIONS: return handler.has(player, perm); case NONE: default: return player.hasPermission(perm); } } }
false
true
public static void initialize(Server server) { Plugin perm = server.getPluginManager().getPlugin("Permissions"); if(perm != null) { our_handler = Handler.PERMISSIONS; permissions_plugin = (Permissions)perm; handler = permissions_plugin.getHandler(); } else { our_handler = Handler.NONE; } }
public static void initialize(Server server) { Plugin perm = server.getPluginManager().getPlugin("Permissions"); if(perm != null) { try { permissions_plugin = (Permissions)perm; handler = permissions_plugin.getHandler(); our_handler = Handler.PERMISSIONS; AngryWolves.log.info("[AngryWolves] Using Permissions " + permissions_plugin.getDescription().getVersion() + " for access control"); } catch (NoClassDefFoundError ncdf) { } } if(our_handler == Handler.NONE) { AngryWolves.log.info("[AngryWolves] Using Bukkit API for access control"); } }
diff --git a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java index 39bd14fdd..ba9a78abc 100644 --- a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java +++ b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/tests/PlugInLoadTest.java @@ -1,204 +1,202 @@ /******************************************************************************* * Copyright (c) 2007 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.tests; import junit.framework.TestCase; import org.eclipse.core.runtime.Platform; import org.osgi.framework.Bundle; public class PlugInLoadTest extends TestCase { public static final String rhdsNS = "org.jboss.tools."; private static String jbideNS = "org.jboss.ide.eclipse."; private static String hibNS = "org.hibernate.eclipse."; private static String jbpmNS = "org.jbpm.gd.jpdl"; private static String jbwsNS = "com.eviware.soapui."; private boolean isPluginResolved (String pluginId) { Bundle bundle = Platform.getBundle(pluginId); assertNotNull(pluginId + " failed to load.",bundle); try { // In 3.3 when test case is running plug-in.getState always returns STARTING state // to move plug-in in ACTIVE state even one class should be loaded from plug-in bundle.loadClass("fake class"); } catch (Exception e) { // It happen always because loaded class is not exists } return ((bundle.getState() & Bundle.RESOLVED) > 0) || ((bundle.getState() & Bundle.ACTIVE) > 0); } private void assertPluginsResolved (String[] pluginIds) { for (int i = 0; i < pluginIds.length; i++) { assertTrue ("plugin '" + pluginIds[i] + "' is not resolved",isPluginResolved(pluginIds[i])); } } public void testCommonPluginsResolved () { assertPluginsResolved(new String[] { rhdsNS+"common", rhdsNS+"common.gef", rhdsNS+"common.kb", rhdsNS+"common.model", rhdsNS+"common.model.ui", rhdsNS+"common.projecttemplates", rhdsNS+"common.text.ext", rhdsNS+"common.text.xml", rhdsNS+"common.verification", rhdsNS+"common.verification.ui", }); } public void testJsfPluginsResolved() { assertPluginsResolved(new String[] { rhdsNS+"jsf", rhdsNS+"jsf.text.ext", rhdsNS+"jsf.text.ext.facelets", rhdsNS+"jsf.ui", rhdsNS+"jsf.verification", rhdsNS+"jsf.vpe.ajax4jsf", rhdsNS+"jsf.vpe.facelets", rhdsNS+"jsf.vpe.richfaces", rhdsNS+"jsf.vpe.seam", rhdsNS+"jsf.vpe.tomahawk" }); } public void testJstPluginsResolved () { assertPluginsResolved(new String[] { rhdsNS+"jst.jsp", rhdsNS+"jst.server.jetty", rhdsNS+"jst.server.jrun", rhdsNS+"jst.server.resin", rhdsNS+"jst.web", rhdsNS+"jst.web.debug", rhdsNS+"jst.web.debug.ui", rhdsNS+"jst.web.tiles", rhdsNS+"jst.web.tiles.ui", rhdsNS+"jst.web.ui", rhdsNS+"jst.web.verification" }); } public void testVpePluginsResolved () { assertPluginsResolved(new String[] { rhdsNS+"vpe.mozilla", rhdsNS+"vpe.ui", rhdsNS+"vpe", rhdsNS+"vpe.ui.palette" }); } public void testStrutsPluginsResolved () { assertPluginsResolved(new String[] { rhdsNS+"struts", rhdsNS+"struts.debug", rhdsNS+"struts.text.ext", rhdsNS+"struts.ui", rhdsNS+"struts.validator.ui", rhdsNS+"struts.verification" }); } public void testShalePluginsResolved () { assertPluginsResolved(new String[] { rhdsNS+"shale.ui", rhdsNS+"shale", rhdsNS+"shale.text.ext" }); } public void testCorePluginsResolved () { assertPluginsResolved(new String[] { jbideNS+"core", jbideNS+"jdt.core", jbideNS+"jdt.j2ee.core", jbideNS+"jdt.j2ee.ui", jbideNS+"jdt.j2ee.xml.ui", - jbideNS+"jdt.test.core", - jbideNS+"jdt.test.ui", jbideNS+"jdt.ui", jbideNS+"jdt.ws.core", jbideNS+"jdt.ws.ui", jbideNS+"archives.core", jbideNS+"archives.ui", jbideNS+"ui", jbideNS+"xdoclet.assist", jbideNS+"xdoclet.core", jbideNS+"xdoclet.run", jbideNS+"xdoclet.ui" }); } public void testASPluginsResolved () { assertPluginsResolved(new String[] { jbideNS+"as.core", jbideNS+"as.ui", jbideNS+"as.ui.mbeans" }); } public void testHibernatePluginsResolved () { assertPluginsResolved(new String[] { "org.hibernate.eclipse", hibNS+"console", hibNS+"help", hibNS+"mapper", hibNS+"jdt.ui", hibNS+"jdt.apt.ui" }); } public void testJbpmPluginsResolved () { assertPluginsResolved(new String[] { jbpmNS }); } public void testFreemarkerPluginsResolved () { assertPluginsResolved(new String[] { jbideNS+"freemarker" }); } public void testDroolsPluginsResolved () { // Skipped until drools migartion to 3.3 is finished // assertPluginsResolved(new String[] { // "org.drools.ide" // }); } public void testJBossWSPluginsResolved () { // assertPluginsResolved(new String[] { // jbwsNS+"core", // jbwsNS+"eclipse.core", // jbwsNS+"jbosside.wstools", // jbwsNS+"libs" // }); } }
true
true
public void testCorePluginsResolved () { assertPluginsResolved(new String[] { jbideNS+"core", jbideNS+"jdt.core", jbideNS+"jdt.j2ee.core", jbideNS+"jdt.j2ee.ui", jbideNS+"jdt.j2ee.xml.ui", jbideNS+"jdt.test.core", jbideNS+"jdt.test.ui", jbideNS+"jdt.ui", jbideNS+"jdt.ws.core", jbideNS+"jdt.ws.ui", jbideNS+"archives.core", jbideNS+"archives.ui", jbideNS+"ui", jbideNS+"xdoclet.assist", jbideNS+"xdoclet.core", jbideNS+"xdoclet.run", jbideNS+"xdoclet.ui" }); }
public void testCorePluginsResolved () { assertPluginsResolved(new String[] { jbideNS+"core", jbideNS+"jdt.core", jbideNS+"jdt.j2ee.core", jbideNS+"jdt.j2ee.ui", jbideNS+"jdt.j2ee.xml.ui", jbideNS+"jdt.ui", jbideNS+"jdt.ws.core", jbideNS+"jdt.ws.ui", jbideNS+"archives.core", jbideNS+"archives.ui", jbideNS+"ui", jbideNS+"xdoclet.assist", jbideNS+"xdoclet.core", jbideNS+"xdoclet.run", jbideNS+"xdoclet.ui" }); }
diff --git a/Core/src/java/de/hattrickorganizer/logik/xml/XMLCHPPPreParser.java b/Core/src/java/de/hattrickorganizer/logik/xml/XMLCHPPPreParser.java index 39506db2..b21c5a55 100644 --- a/Core/src/java/de/hattrickorganizer/logik/xml/XMLCHPPPreParser.java +++ b/Core/src/java/de/hattrickorganizer/logik/xml/XMLCHPPPreParser.java @@ -1,72 +1,72 @@ package de.hattrickorganizer.logik.xml; import org.w3c.dom.Document; import org.w3c.dom.Element; import de.hattrickorganizer.model.HOVerwaltung; import de.hattrickorganizer.tools.HOLogger; import de.hattrickorganizer.tools.xml.XMLManager; public class XMLCHPPPreParser { public XMLCHPPPreParser() { } public String Error(String xmlIn) { String sError = ""; Document doc = null; doc = XMLManager.instance().parseString(xmlIn); if (doc != null) { Element ele = null; Element root = doc.getDocumentElement(); try { // See if an error is found if (root.getElementsByTagName("ErrorCode").getLength() > 0) { ele = (Element) root.getElementsByTagName("ErrorCode").item(0); String sTmpError = XMLManager.instance().getFirstChildNodeValue(ele); String sErrString = ""; HOVerwaltung hov = HOVerwaltung.instance(); switch (Integer.parseInt(sTmpError)) { case -1: case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 10: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 90: case 91: case 99: - sErrString = hov.getLanguageString("CHPP.Error" + sTmpError); + sErrString = sTmpError + " - " + hov.getLanguageString("CHPP.Error" + sTmpError); break; default: - sErrString = hov.getLanguageString("CHPP.Error99"); + sErrString = sTmpError + " - " + hov.getLanguageString("CHPP.Unknown"); break; } sError = hov.getLanguageString("CHPP.Error") + " - " + sErrString; } } catch (Exception ex) { HOLogger.instance().log(getClass(),"XMLCHPPPreParser Exception: " + ex); sError = ex.getMessage(); } } else { sError = "No CHPP data found."; } return sError; } }
false
true
public String Error(String xmlIn) { String sError = ""; Document doc = null; doc = XMLManager.instance().parseString(xmlIn); if (doc != null) { Element ele = null; Element root = doc.getDocumentElement(); try { // See if an error is found if (root.getElementsByTagName("ErrorCode").getLength() > 0) { ele = (Element) root.getElementsByTagName("ErrorCode").item(0); String sTmpError = XMLManager.instance().getFirstChildNodeValue(ele); String sErrString = ""; HOVerwaltung hov = HOVerwaltung.instance(); switch (Integer.parseInt(sTmpError)) { case -1: case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 10: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 90: case 91: case 99: sErrString = hov.getLanguageString("CHPP.Error" + sTmpError); break; default: sErrString = hov.getLanguageString("CHPP.Error99"); break; } sError = hov.getLanguageString("CHPP.Error") + " - " + sErrString; } } catch (Exception ex) { HOLogger.instance().log(getClass(),"XMLCHPPPreParser Exception: " + ex); sError = ex.getMessage(); } } else { sError = "No CHPP data found."; } return sError; }
public String Error(String xmlIn) { String sError = ""; Document doc = null; doc = XMLManager.instance().parseString(xmlIn); if (doc != null) { Element ele = null; Element root = doc.getDocumentElement(); try { // See if an error is found if (root.getElementsByTagName("ErrorCode").getLength() > 0) { ele = (Element) root.getElementsByTagName("ErrorCode").item(0); String sTmpError = XMLManager.instance().getFirstChildNodeValue(ele); String sErrString = ""; HOVerwaltung hov = HOVerwaltung.instance(); switch (Integer.parseInt(sTmpError)) { case -1: case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 10: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 90: case 91: case 99: sErrString = sTmpError + " - " + hov.getLanguageString("CHPP.Error" + sTmpError); break; default: sErrString = sTmpError + " - " + hov.getLanguageString("CHPP.Unknown"); break; } sError = hov.getLanguageString("CHPP.Error") + " - " + sErrString; } } catch (Exception ex) { HOLogger.instance().log(getClass(),"XMLCHPPPreParser Exception: " + ex); sError = ex.getMessage(); } } else { sError = "No CHPP data found."; } return sError; }
diff --git a/whois-internal/src/test/java/net/ripe/db/whois/internal/logsearch/logformat/DailyLogFolderTest.java b/whois-internal/src/test/java/net/ripe/db/whois/internal/logsearch/logformat/DailyLogFolderTest.java index cef049f61..fab65e4e6 100644 --- a/whois-internal/src/test/java/net/ripe/db/whois/internal/logsearch/logformat/DailyLogFolderTest.java +++ b/whois-internal/src/test/java/net/ripe/db/whois/internal/logsearch/logformat/DailyLogFolderTest.java @@ -1,31 +1,31 @@ package net.ripe.db.whois.internal.logsearch.logformat; import net.ripe.db.whois.internal.logsearch.NewLogFormatProcessor; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class DailyLogFolderTest { @Test(expected = IllegalArgumentException.class) public void log_invalid_folder() throws IOException { new DailyLogFolder(getLogFolder("/log").toPath()); } @Test public void matcherTest() { assertFalse(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/000.audit.xml.gz").matches()); - assertFalse(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/001.ack.txt.gz").matches()); + assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/001.ack.txt.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/002.msg-in.txt.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/003.msg-out.txt.gz").matches()); } private static File getLogFolder(final String path) throws IOException { return new ClassPathResource(path).getFile(); } }
true
true
public void matcherTest() { assertFalse(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/000.audit.xml.gz").matches()); assertFalse(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/001.ack.txt.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/002.msg-in.txt.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/003.msg-out.txt.gz").matches()); }
public void matcherTest() { assertFalse(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/000.audit.xml.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/001.ack.txt.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/002.msg-in.txt.gz").matches()); assertTrue(NewLogFormatProcessor.INDEXED_LOG_ENTRIES.matcher("/log/update/20130306/123623.428054357.0.1362569782886.JavaMail.andre/003.msg-out.txt.gz").matches()); }
diff --git a/src/main/java/com/alta189/simplesave/internal/ResultSetUtils.java b/src/main/java/com/alta189/simplesave/internal/ResultSetUtils.java index 63f75df..73b88a1 100644 --- a/src/main/java/com/alta189/simplesave/internal/ResultSetUtils.java +++ b/src/main/java/com/alta189/simplesave/internal/ResultSetUtils.java @@ -1,126 +1,129 @@ /* * This file is part of SimpleSave * * SimpleSave is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SimpleSave is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.alta189.simplesave.internal; import com.alta189.simplesave.internal.reflection.EmptyInjector; import java.io.IOException; import java.io.ObjectInputStream; import java.lang.reflect.Field; import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ResultSetUtils { private static final EmptyInjector injector = new EmptyInjector(); public static <E> List<E> buildResultList(TableRegistration table, Class<E> clazz, ResultSet set) { List<E> result = new ArrayList<E>(); try { while (set.next()) { result.add(buildResult(table, clazz, set)); } } catch (SQLException e) { throw new RuntimeException(e); } return result; } public static <E> E buildResult(TableRegistration table, Class<E> clazz, ResultSet set) { E result = (E) injector.newInstance(clazz); setField(table.getId(), result, set); for (FieldRegistration field : table.getFields()) { setField(field, result, set); } return result; } public static <E> void setField(FieldRegistration fieldRegistration, E object, ResultSet set) { try { Field field = fieldRegistration.getField(); field.setAccessible(true); if (fieldRegistration.isSerializable()) { String result = set.getString(fieldRegistration.getName()); field.set(object, TableUtils.deserializeField(fieldRegistration, result)); } else { if (fieldRegistration.getType().equals(int.class)) { field.setInt(object, set.getInt(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Integer.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(long.class)) { field.setLong(object, set.getLong(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Long.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(double.class)) { field.setDouble(object, set.getDouble(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Double.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(String.class)) { field.set(object, set.getString(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(boolean.class)) { int i = set.getInt(fieldRegistration.getName()); if (i == 1) { field.setBoolean(object, true); } else { field.setBoolean(object, false); } } else if (fieldRegistration.getType().equals(Boolean.class)) { int i = set.getInt(fieldRegistration.getName()); if (i == 1) { field.set(object, Boolean.TRUE); } else { field.set(object, Boolean.FALSE); } } else if (fieldRegistration.getType().equals(short.class)) { field.setShort(object, set.getShort(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Short.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(float.class)) { field.setFloat(object, set.getFloat(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Float.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(byte.class)) { field.setByte(object, set.getByte(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Byte.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else { Blob b = set.getBlob(fieldRegistration.getName()); + if (b == null || b.length() <= 0) { + field.set(object, null); + } ObjectInputStream is = new ObjectInputStream(b.getBinaryStream()); Object o = null; try { o = is.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { is.close(); } field.set(object, o); } } } catch (SQLException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }
true
true
public static <E> void setField(FieldRegistration fieldRegistration, E object, ResultSet set) { try { Field field = fieldRegistration.getField(); field.setAccessible(true); if (fieldRegistration.isSerializable()) { String result = set.getString(fieldRegistration.getName()); field.set(object, TableUtils.deserializeField(fieldRegistration, result)); } else { if (fieldRegistration.getType().equals(int.class)) { field.setInt(object, set.getInt(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Integer.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(long.class)) { field.setLong(object, set.getLong(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Long.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(double.class)) { field.setDouble(object, set.getDouble(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Double.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(String.class)) { field.set(object, set.getString(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(boolean.class)) { int i = set.getInt(fieldRegistration.getName()); if (i == 1) { field.setBoolean(object, true); } else { field.setBoolean(object, false); } } else if (fieldRegistration.getType().equals(Boolean.class)) { int i = set.getInt(fieldRegistration.getName()); if (i == 1) { field.set(object, Boolean.TRUE); } else { field.set(object, Boolean.FALSE); } } else if (fieldRegistration.getType().equals(short.class)) { field.setShort(object, set.getShort(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Short.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(float.class)) { field.setFloat(object, set.getFloat(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Float.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(byte.class)) { field.setByte(object, set.getByte(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Byte.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else { Blob b = set.getBlob(fieldRegistration.getName()); ObjectInputStream is = new ObjectInputStream(b.getBinaryStream()); Object o = null; try { o = is.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { is.close(); } field.set(object, o); } } } catch (SQLException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
public static <E> void setField(FieldRegistration fieldRegistration, E object, ResultSet set) { try { Field field = fieldRegistration.getField(); field.setAccessible(true); if (fieldRegistration.isSerializable()) { String result = set.getString(fieldRegistration.getName()); field.set(object, TableUtils.deserializeField(fieldRegistration, result)); } else { if (fieldRegistration.getType().equals(int.class)) { field.setInt(object, set.getInt(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Integer.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(long.class)) { field.setLong(object, set.getLong(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Long.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(double.class)) { field.setDouble(object, set.getDouble(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Double.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(String.class)) { field.set(object, set.getString(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(boolean.class)) { int i = set.getInt(fieldRegistration.getName()); if (i == 1) { field.setBoolean(object, true); } else { field.setBoolean(object, false); } } else if (fieldRegistration.getType().equals(Boolean.class)) { int i = set.getInt(fieldRegistration.getName()); if (i == 1) { field.set(object, Boolean.TRUE); } else { field.set(object, Boolean.FALSE); } } else if (fieldRegistration.getType().equals(short.class)) { field.setShort(object, set.getShort(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Short.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(float.class)) { field.setFloat(object, set.getFloat(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Float.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(byte.class)) { field.setByte(object, set.getByte(fieldRegistration.getName())); } else if (fieldRegistration.getType().equals(Byte.class)) { field.set(object, set.getObject(fieldRegistration.getName())); } else { Blob b = set.getBlob(fieldRegistration.getName()); if (b == null || b.length() <= 0) { field.set(object, null); } ObjectInputStream is = new ObjectInputStream(b.getBinaryStream()); Object o = null; try { o = is.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { is.close(); } field.set(object, o); } } } catch (SQLException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/TFC_Shared/src/TFC/WorldGen/Generators/WorldGenLooseRocks.java b/TFC_Shared/src/TFC/WorldGen/Generators/WorldGenLooseRocks.java index e95909dc8..ce6b82406 100644 --- a/TFC_Shared/src/TFC/WorldGen/Generators/WorldGenLooseRocks.java +++ b/TFC_Shared/src/TFC/WorldGen/Generators/WorldGenLooseRocks.java @@ -1,53 +1,53 @@ package TFC.WorldGen.Generators; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.IChunkProvider; import TFC.TFCBlocks; import cpw.mods.fml.common.IWorldGenerator; public class WorldGenLooseRocks implements IWorldGenerator { public WorldGenLooseRocks() { } private boolean generate(World world, Random random, int var8, int var9, int var10) { if ((world.isAirBlock(var8, var9+1, var10) || world.getBlockId(var8, var9+1, var10) == Block.snow.blockID || world.getBlockId(var8, var9+1, var10) == Block.tallGrass.blockID) && (world.getBlockMaterial(var8, var9, var10) == Material.grass || world.getBlockMaterial(var8, var9, var10) == Material.rock) && world.isBlockOpaqueCube(var8, var9, var10)) { world.setBlock(var8, var9+1, var10, TFCBlocks.LooseRock.blockID, 0, 2); } return true; } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { - // chunkX *= 16; - // chunkZ *= 16; + chunkX *= 16; + chunkZ *= 16; BiomeGenBase biome = world.getBiomeGenForCoords(chunkX, chunkZ); for (int var2 = 0; var2 < 8; var2++) { int var7 = chunkX + random.nextInt(16) + 8; int var3 = chunkZ + random.nextInt(16) + 8; generate(world, random, var7, world.getTopSolidOrLiquidBlock(var7, var3)-1, var3); } } }
true
true
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { // chunkX *= 16; // chunkZ *= 16; BiomeGenBase biome = world.getBiomeGenForCoords(chunkX, chunkZ); for (int var2 = 0; var2 < 8; var2++) { int var7 = chunkX + random.nextInt(16) + 8; int var3 = chunkZ + random.nextInt(16) + 8; generate(world, random, var7, world.getTopSolidOrLiquidBlock(var7, var3)-1, var3); } }
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { chunkX *= 16; chunkZ *= 16; BiomeGenBase biome = world.getBiomeGenForCoords(chunkX, chunkZ); for (int var2 = 0; var2 < 8; var2++) { int var7 = chunkX + random.nextInt(16) + 8; int var3 = chunkZ + random.nextInt(16) + 8; generate(world, random, var7, world.getTopSolidOrLiquidBlock(var7, var3)-1, var3); } }
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchIngestSimplePanel.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchIngestSimplePanel.java index 9ba8e3e38..8af4886c8 100644 --- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchIngestSimplePanel.java +++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchIngestSimplePanel.java @@ -1,216 +1,216 @@ /* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * KeywordSearchIngestSimplePanel.java * * Created on Feb 28, 2012, 1:11:34 PM */ package org.sleuthkit.autopsy.keywordsearch; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import org.sleuthkit.autopsy.coreutils.StringExtract.StringExtractUnicodeTable.SCRIPT; /** * * @author dfickling */ public class KeywordSearchIngestSimplePanel extends javax.swing.JPanel { private final static Logger logger = Logger.getLogger(KeywordSearchIngestSimplePanel.class.getName()); private KeywordTableModel tableModel; private List<KeywordSearchList> lists; /** Creates new form KeywordSearchIngestSimplePanel */ public KeywordSearchIngestSimplePanel() { tableModel = new KeywordTableModel(); lists = new ArrayList<KeywordSearchList>(); reloadLists(); initComponents(); customizeComponents(); } private void customizeComponents() { listsTable.setModel(tableModel); listsTable.setTableHeader(null); listsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //customize column witdhs final int width = listsScrollPane.getPreferredSize().width; TableColumn column = null; for (int i = 0; i < listsTable.getColumnCount(); i++) { column = listsTable.getColumnModel().getColumn(i); if (i == 0) { column.setPreferredWidth(((int) (width * 0.15))); } else { column.setPreferredWidth(((int) (width * 0.84))); } } reloadLangs(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { listsScrollPane = new javax.swing.JScrollPane(); listsTable = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); languagesLabel = new javax.swing.JLabel(); languagesValLabel = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); setPreferredSize(new java.awt.Dimension(172, 57)); listsScrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); listsTable.setBackground(new java.awt.Color(240, 240, 240)); listsTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); listsTable.setShowHorizontalLines(false); listsTable.setShowVerticalLines(false); listsScrollPane.setViewportView(listsTable); jLabel1.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.jLabel1.text")); // NOI18N languagesLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesLabel.text")); // NOI18N languagesLabel.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesLabel.toolTipText")); // NOI18N languagesValLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesValLabel.text")); // NOI18N languagesValLabel.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesValLabel.toolTipText")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jSeparator2) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(languagesLabel) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(languagesValLabel)) .addComponent(jLabel1)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(languagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(languagesValLabel) .addGap(9, 9, 9) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) - .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(listsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JLabel languagesLabel; private javax.swing.JLabel languagesValLabel; private javax.swing.JScrollPane listsScrollPane; private javax.swing.JTable listsTable; // End of variables declaration//GEN-END:variables private void reloadLangs() { //TODO multiple SCRIPT script = KeywordSearchIngestService.getDefault().getStringExtractScript(); this.languagesValLabel.setText(script.toString()); this.languagesValLabel.setToolTipText(script.toString()); } private void reloadLists() { lists.clear(); lists.addAll(KeywordSearchListsXML.getCurrent().getListsL()); } private class KeywordTableModel extends AbstractTableModel { @Override public int getRowCount() { return KeywordSearchIngestSimplePanel.this.lists.size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { KeywordSearchList list = KeywordSearchIngestSimplePanel.this.lists.get(rowIndex); if(columnIndex == 0) { return list.getUseForIngest(); } else { return list.getName(); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { KeywordSearchList list = KeywordSearchIngestSimplePanel.this.lists.get(rowIndex); if(columnIndex == 0){ KeywordSearchListsXML loader = KeywordSearchListsXML.getCurrent(); loader.addList(list.getName(), list.getKeywords(), (Boolean) aValue, false); reloadLists(); } } @Override public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } } }
true
true
private void initComponents() { listsScrollPane = new javax.swing.JScrollPane(); listsTable = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); languagesLabel = new javax.swing.JLabel(); languagesValLabel = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); setPreferredSize(new java.awt.Dimension(172, 57)); listsScrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); listsTable.setBackground(new java.awt.Color(240, 240, 240)); listsTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); listsTable.setShowHorizontalLines(false); listsTable.setShowVerticalLines(false); listsScrollPane.setViewportView(listsTable); jLabel1.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.jLabel1.text")); // NOI18N languagesLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesLabel.text")); // NOI18N languagesLabel.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesLabel.toolTipText")); // NOI18N languagesValLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesValLabel.text")); // NOI18N languagesValLabel.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesValLabel.toolTipText")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jSeparator2) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(languagesLabel) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(languagesValLabel)) .addComponent(jLabel1)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(languagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(languagesValLabel) .addGap(9, 9, 9) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { listsScrollPane = new javax.swing.JScrollPane(); listsTable = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); languagesLabel = new javax.swing.JLabel(); languagesValLabel = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); setPreferredSize(new java.awt.Dimension(172, 57)); listsScrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); listsTable.setBackground(new java.awt.Color(240, 240, 240)); listsTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); listsTable.setShowHorizontalLines(false); listsTable.setShowVerticalLines(false); listsScrollPane.setViewportView(listsTable); jLabel1.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.jLabel1.text")); // NOI18N languagesLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesLabel.text")); // NOI18N languagesLabel.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesLabel.toolTipText")); // NOI18N languagesValLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesValLabel.text")); // NOI18N languagesValLabel.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchIngestSimplePanel.class, "KeywordSearchIngestSimplePanel.languagesValLabel.toolTipText")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(listsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jSeparator2) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(languagesLabel) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(languagesValLabel)) .addComponent(jLabel1)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(languagesLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(languagesValLabel) .addGap(9, 9, 9) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(listsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/be/ibridge/kettle/kitchen/Kitchen.java b/src/be/ibridge/kettle/kitchen/Kitchen.java index a8e7518e..5c689777 100644 --- a/src/be/ibridge/kettle/kitchen/Kitchen.java +++ b/src/be/ibridge/kettle/kitchen/Kitchen.java @@ -1,362 +1,369 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ /** * Kettle was (re-)started in March 2003 */ package be.ibridge.kettle.kitchen; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LocalVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleJobException; import be.ibridge.kettle.core.util.EnvUtil; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobEntryLoader; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.pan.CommandLineOption; import be.ibridge.kettle.repository.RepositoriesMeta; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; import be.ibridge.kettle.repository.RepositoryMeta; import be.ibridge.kettle.repository.UserInfo; import be.ibridge.kettle.trans.StepLoader; import be.ibridge.kettle.version.BuildVersion; public class Kitchen { public static final String STRING_KITCHEN = "Kitchen"; public static void main(String[] a) throws KettleException { EnvUtil.environmentInit(); Thread parentThread = Thread.currentThread(); LocalVariables.getInstance().createKettleVariables(parentThread.getName(), null, false); ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) { if (a[i].length()>0) args.add(a[i]); } RepositoryMeta repinfo = null; UserInfo userinfo = null; Job job = null; StringBuffer optionRepname, optionUsername, optionPassword, optionJobname, optionDirname, optionFilename, optionLoglevel; StringBuffer optionLogfile, optionListdir, optionListjobs, optionListrep, optionNorep, optionVersion; CommandLineOption options[] = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()), new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()), new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()), new CommandLineOption("job", "The name of the transformation to launch", optionJobname=new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()), new CommandLineOption("file", "The filename (Job XML) to launch", optionFilename=new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true), new CommandLineOption("listdir", "List the directories in the repository", optionListdir=new StringBuffer(), true, false), new CommandLineOption("listjobs", "List the jobs in the specified directory", optionListjobs=new StringBuffer(), true, false), new CommandLineOption("listrep", "List the available repositories", optionListrep=new StringBuffer(), true, false), new CommandLineOption("norep", "Do not log into the repository", optionNorep=new StringBuffer(), true, false), new CommandLineOption("version", "show the version, revision and build date", optionVersion=new StringBuffer(), true, false), }; if (args.size()==0 ) { CommandLineOption.printUsage(options); System.exit(9); } CommandLineOption.parseArguments(args, options); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname ); if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername); if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword); // System.out.println("Level="+loglevel); LogWriter log; LogWriter.setConsoleAppenderDebug(); if (Const.isEmpty(optionLogfile)) { log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC ); } else { log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC ); } if (!Const.isEmpty(optionLoglevel)) { log.setLogLevel(optionLoglevel.toString()); log.logMinimal(STRING_KITCHEN, "Logging is at level : "+log.getLogLevelDesc()); } if (!Const.isEmpty(optionVersion)) { BuildVersion buildVersion = BuildVersion.getInstance(); log.logBasic("Pan", "Kettle version "+Const.VERSION+", build "+buildVersion.getVersion()+", build date : "+buildVersion.getBuildDate()); if (a.length==1) System.exit(6); } // Start the action... // if (!Const.isEmpty(optionRepname) && !Const.isEmpty(optionUsername)) log.logDetailed(STRING_KITCHEN, "Repository and username supplied"); log.logMinimal(STRING_KITCHEN, "Start of run."); /* Load the plugins etc.*/ StepLoader steploader = StepLoader.getInstance(); if (!steploader.read()) { log.logError(STRING_KITCHEN, "Error loading steps... halting Kitchen!"); System.exit(8); } /* Load the plugins etc.*/ JobEntryLoader jeloader = JobEntryLoader.getInstance(); if (!jeloader.read()) { log.logError(STRING_KITCHEN, "Error loading job entries & plugins... halting Kitchen!"); return; } Date start, stop; Calendar cal; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal=Calendar.getInstance(); start=cal.getTime(); log.logDebug(STRING_KITCHEN, "Allocate new job."); JobMeta jobMeta = new JobMeta(log); // In case we use a repository... Repository repository = null; try { // Read kettle job specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { log.logDebug(STRING_KITCHEN, "Parsing command line options."); if (optionRepname!=null && !"Y".equalsIgnoreCase(optionNorep.toString())) { log.logDebug(STRING_KITCHEN, "Loading available repositories."); RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { log.logDebug(STRING_KITCHEN, "Finding repository ["+optionRepname+"]"); repinfo = repsinfo.findRepository(optionRepname.toString()); if (repinfo!=null) { // Define and connect to the repository... log.logDebug(STRING_KITCHEN, "Allocate & connect to repository."); repository = new Repository(log, repinfo, userinfo); if (repository.connect("Kitchen commandline")) { RepositoryDirectory directory = repository.getDirectoryTree(); // Default = root // Find the directory name if one is specified... if (!Const.isEmpty(optionDirname)) { directory = repository.getDirectoryTree().findDirectory(optionDirname.toString()); } if (directory!=null) { // Check username, password log.logDebug(STRING_KITCHEN, "Check supplied username and password."); userinfo = new UserInfo(repository, optionUsername.toString(), optionPassword.toString()); if (userinfo.getID()>0) { // Load a job if (!Const.isEmpty(optionJobname)) { log.logDebug(STRING_KITCHEN, "Load the job info..."); jobMeta = new JobMeta(log, repository, optionJobname.toString(), directory); log.logDebug(STRING_KITCHEN, "Allocate job..."); job = new Job(log, steploader, repository, jobMeta); } else // List the jobs in the repository if ("Y".equalsIgnoreCase(optionListjobs.toString())) { log.logDebug(STRING_KITCHEN, "Getting list of jobs in directory: "+directory); String jobnames[] = repository.getJobNames(directory.getID()); for (int i=0;i<jobnames.length;i++) { System.out.println(jobnames[i]); } } else // List the directories in the repository if ("Y".equalsIgnoreCase(optionListdir.toString())) { String dirnames[] = repository.getDirectoryNames(directory.getID()); for (int i=0;i<dirnames.length;i++) { System.out.println(dirnames[i]); } } } else { System.out.println("ERROR: Can't verify username and password."); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't find the supplied directory ["+optionDirname+"]"); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't connect to the repository."); } } else { System.out.println("ERROR: No repository provided, can't load job."); } } else { System.out.println("ERROR: No repositories defined on this system."); } } // Try to load if from file anyway. if (!Const.isEmpty(optionFilename) && job==null) { jobMeta = new JobMeta(log, optionFilename.toString(), null); job = new Job(log, steploader, null, jobMeta); } } else if ("Y".equalsIgnoreCase(optionListrep.toString())) { RepositoriesMeta ri = new RepositoriesMeta(log); if (ri.readData()) { System.out.println("List of repositories:"); for (int i=0;i<ri.nrRepositories();i++) { RepositoryMeta rinfo = ri.getRepository(i); System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] "); } } else { System.out.println("ERROR: Unable to read/parse the repositories XML file."); } } } catch(KettleException e) { job=null; jobMeta=null; System.out.println("Processing stopped because of an error: "+e.getMessage()); } if (job==null) { if (!"Y".equalsIgnoreCase(optionListjobs.toString()) && !"Y".equalsIgnoreCase(optionListdir.toString()) && !"Y".equalsIgnoreCase(optionListrep.toString()) ) { System.out.println("ERROR: Kitchen can't continue because the job couldn't be loaded."); } System.exit(7); } Result result = null; int returnCode=0; try { // Add Kettle variables for the job thread... LocalVariables.getInstance().createKettleVariables(job.getName(), parentThread.getName(), true); // Set the arguments on the job metadata as well... - job.getJobMeta().setArguments((String[]) args.toArray(new String[args.size()])); + if ( args.size() == 0 ) + { + job.getJobMeta().setArguments(null); + } + else + { + job.getJobMeta().setArguments((String[]) args.toArray(new String[args.size()])); + } result = job.execute(); // Execute the selected job. job.endProcessing("end", result); // The bookkeeping... } catch(KettleJobException je) { if (result==null) { result = new Result(); } result.setNrErrors(1L); try { job.endProcessing("error", result); } catch(KettleJobException je2) { log.logError(job.getName(), "A serious error occured : "+je2.getMessage()); returnCode = 2; } } finally { if (repository!=null) repository.disconnect(); } log.logMinimal(STRING_KITCHEN, "Finished!"); if (result!=null && result.getNrErrors()!=0) { log.logError(STRING_KITCHEN, "Finished with errors"); returnCode = 1; } cal=Calendar.getInstance(); stop=cal.getTime(); String begin=df.format(start).toString(); String end =df.format(stop).toString(); log.logMinimal(STRING_KITCHEN, "Start="+begin+", Stop="+end); long millis=stop.getTime()-start.getTime(); log.logMinimal(STRING_KITCHEN, "Processing ended after "+(millis/1000)+" seconds."); System.exit(returnCode); } }
true
true
public static void main(String[] a) throws KettleException { EnvUtil.environmentInit(); Thread parentThread = Thread.currentThread(); LocalVariables.getInstance().createKettleVariables(parentThread.getName(), null, false); ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) { if (a[i].length()>0) args.add(a[i]); } RepositoryMeta repinfo = null; UserInfo userinfo = null; Job job = null; StringBuffer optionRepname, optionUsername, optionPassword, optionJobname, optionDirname, optionFilename, optionLoglevel; StringBuffer optionLogfile, optionListdir, optionListjobs, optionListrep, optionNorep, optionVersion; CommandLineOption options[] = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()), new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()), new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()), new CommandLineOption("job", "The name of the transformation to launch", optionJobname=new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()), new CommandLineOption("file", "The filename (Job XML) to launch", optionFilename=new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true), new CommandLineOption("listdir", "List the directories in the repository", optionListdir=new StringBuffer(), true, false), new CommandLineOption("listjobs", "List the jobs in the specified directory", optionListjobs=new StringBuffer(), true, false), new CommandLineOption("listrep", "List the available repositories", optionListrep=new StringBuffer(), true, false), new CommandLineOption("norep", "Do not log into the repository", optionNorep=new StringBuffer(), true, false), new CommandLineOption("version", "show the version, revision and build date", optionVersion=new StringBuffer(), true, false), }; if (args.size()==0 ) { CommandLineOption.printUsage(options); System.exit(9); } CommandLineOption.parseArguments(args, options); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname ); if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername); if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword); // System.out.println("Level="+loglevel); LogWriter log; LogWriter.setConsoleAppenderDebug(); if (Const.isEmpty(optionLogfile)) { log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC ); } else { log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC ); } if (!Const.isEmpty(optionLoglevel)) { log.setLogLevel(optionLoglevel.toString()); log.logMinimal(STRING_KITCHEN, "Logging is at level : "+log.getLogLevelDesc()); } if (!Const.isEmpty(optionVersion)) { BuildVersion buildVersion = BuildVersion.getInstance(); log.logBasic("Pan", "Kettle version "+Const.VERSION+", build "+buildVersion.getVersion()+", build date : "+buildVersion.getBuildDate()); if (a.length==1) System.exit(6); } // Start the action... // if (!Const.isEmpty(optionRepname) && !Const.isEmpty(optionUsername)) log.logDetailed(STRING_KITCHEN, "Repository and username supplied"); log.logMinimal(STRING_KITCHEN, "Start of run."); /* Load the plugins etc.*/ StepLoader steploader = StepLoader.getInstance(); if (!steploader.read()) { log.logError(STRING_KITCHEN, "Error loading steps... halting Kitchen!"); System.exit(8); } /* Load the plugins etc.*/ JobEntryLoader jeloader = JobEntryLoader.getInstance(); if (!jeloader.read()) { log.logError(STRING_KITCHEN, "Error loading job entries & plugins... halting Kitchen!"); return; } Date start, stop; Calendar cal; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal=Calendar.getInstance(); start=cal.getTime(); log.logDebug(STRING_KITCHEN, "Allocate new job."); JobMeta jobMeta = new JobMeta(log); // In case we use a repository... Repository repository = null; try { // Read kettle job specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { log.logDebug(STRING_KITCHEN, "Parsing command line options."); if (optionRepname!=null && !"Y".equalsIgnoreCase(optionNorep.toString())) { log.logDebug(STRING_KITCHEN, "Loading available repositories."); RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { log.logDebug(STRING_KITCHEN, "Finding repository ["+optionRepname+"]"); repinfo = repsinfo.findRepository(optionRepname.toString()); if (repinfo!=null) { // Define and connect to the repository... log.logDebug(STRING_KITCHEN, "Allocate & connect to repository."); repository = new Repository(log, repinfo, userinfo); if (repository.connect("Kitchen commandline")) { RepositoryDirectory directory = repository.getDirectoryTree(); // Default = root // Find the directory name if one is specified... if (!Const.isEmpty(optionDirname)) { directory = repository.getDirectoryTree().findDirectory(optionDirname.toString()); } if (directory!=null) { // Check username, password log.logDebug(STRING_KITCHEN, "Check supplied username and password."); userinfo = new UserInfo(repository, optionUsername.toString(), optionPassword.toString()); if (userinfo.getID()>0) { // Load a job if (!Const.isEmpty(optionJobname)) { log.logDebug(STRING_KITCHEN, "Load the job info..."); jobMeta = new JobMeta(log, repository, optionJobname.toString(), directory); log.logDebug(STRING_KITCHEN, "Allocate job..."); job = new Job(log, steploader, repository, jobMeta); } else // List the jobs in the repository if ("Y".equalsIgnoreCase(optionListjobs.toString())) { log.logDebug(STRING_KITCHEN, "Getting list of jobs in directory: "+directory); String jobnames[] = repository.getJobNames(directory.getID()); for (int i=0;i<jobnames.length;i++) { System.out.println(jobnames[i]); } } else // List the directories in the repository if ("Y".equalsIgnoreCase(optionListdir.toString())) { String dirnames[] = repository.getDirectoryNames(directory.getID()); for (int i=0;i<dirnames.length;i++) { System.out.println(dirnames[i]); } } } else { System.out.println("ERROR: Can't verify username and password."); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't find the supplied directory ["+optionDirname+"]"); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't connect to the repository."); } } else { System.out.println("ERROR: No repository provided, can't load job."); } } else { System.out.println("ERROR: No repositories defined on this system."); } } // Try to load if from file anyway. if (!Const.isEmpty(optionFilename) && job==null) { jobMeta = new JobMeta(log, optionFilename.toString(), null); job = new Job(log, steploader, null, jobMeta); } } else if ("Y".equalsIgnoreCase(optionListrep.toString())) { RepositoriesMeta ri = new RepositoriesMeta(log); if (ri.readData()) { System.out.println("List of repositories:"); for (int i=0;i<ri.nrRepositories();i++) { RepositoryMeta rinfo = ri.getRepository(i); System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] "); } } else { System.out.println("ERROR: Unable to read/parse the repositories XML file."); } } } catch(KettleException e) { job=null; jobMeta=null; System.out.println("Processing stopped because of an error: "+e.getMessage()); } if (job==null) { if (!"Y".equalsIgnoreCase(optionListjobs.toString()) && !"Y".equalsIgnoreCase(optionListdir.toString()) && !"Y".equalsIgnoreCase(optionListrep.toString()) ) { System.out.println("ERROR: Kitchen can't continue because the job couldn't be loaded."); } System.exit(7); } Result result = null; int returnCode=0; try { // Add Kettle variables for the job thread... LocalVariables.getInstance().createKettleVariables(job.getName(), parentThread.getName(), true); // Set the arguments on the job metadata as well... job.getJobMeta().setArguments((String[]) args.toArray(new String[args.size()])); result = job.execute(); // Execute the selected job. job.endProcessing("end", result); // The bookkeeping... } catch(KettleJobException je) { if (result==null) { result = new Result(); } result.setNrErrors(1L); try { job.endProcessing("error", result); } catch(KettleJobException je2) { log.logError(job.getName(), "A serious error occured : "+je2.getMessage()); returnCode = 2; } } finally { if (repository!=null) repository.disconnect(); } log.logMinimal(STRING_KITCHEN, "Finished!"); if (result!=null && result.getNrErrors()!=0) { log.logError(STRING_KITCHEN, "Finished with errors"); returnCode = 1; } cal=Calendar.getInstance(); stop=cal.getTime(); String begin=df.format(start).toString(); String end =df.format(stop).toString(); log.logMinimal(STRING_KITCHEN, "Start="+begin+", Stop="+end); long millis=stop.getTime()-start.getTime(); log.logMinimal(STRING_KITCHEN, "Processing ended after "+(millis/1000)+" seconds."); System.exit(returnCode); }
public static void main(String[] a) throws KettleException { EnvUtil.environmentInit(); Thread parentThread = Thread.currentThread(); LocalVariables.getInstance().createKettleVariables(parentThread.getName(), null, false); ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) { if (a[i].length()>0) args.add(a[i]); } RepositoryMeta repinfo = null; UserInfo userinfo = null; Job job = null; StringBuffer optionRepname, optionUsername, optionPassword, optionJobname, optionDirname, optionFilename, optionLoglevel; StringBuffer optionLogfile, optionListdir, optionListjobs, optionListrep, optionNorep, optionVersion; CommandLineOption options[] = new CommandLineOption[] { new CommandLineOption("rep", "Repository name", optionRepname=new StringBuffer()), new CommandLineOption("user", "Repository username", optionUsername=new StringBuffer()), new CommandLineOption("pass", "Repository password", optionPassword=new StringBuffer()), new CommandLineOption("job", "The name of the transformation to launch", optionJobname=new StringBuffer()), new CommandLineOption("dir", "The directory (don't forget the leading /)", optionDirname=new StringBuffer()), new CommandLineOption("file", "The filename (Job XML) to launch", optionFilename=new StringBuffer()), new CommandLineOption("level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)", optionLoglevel=new StringBuffer()), new CommandLineOption("logfile", "The logging file to write to", optionLogfile=new StringBuffer()), new CommandLineOption("log", "The logging file to write to (deprecated)", optionLogfile=new StringBuffer(), false, true), new CommandLineOption("listdir", "List the directories in the repository", optionListdir=new StringBuffer(), true, false), new CommandLineOption("listjobs", "List the jobs in the specified directory", optionListjobs=new StringBuffer(), true, false), new CommandLineOption("listrep", "List the available repositories", optionListrep=new StringBuffer(), true, false), new CommandLineOption("norep", "Do not log into the repository", optionNorep=new StringBuffer(), true, false), new CommandLineOption("version", "show the version, revision and build date", optionVersion=new StringBuffer(), true, false), }; if (args.size()==0 ) { CommandLineOption.printUsage(options); System.exit(9); } CommandLineOption.parseArguments(args, options); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (!Const.isEmpty(kettleRepname )) optionRepname = new StringBuffer(kettleRepname ); if (!Const.isEmpty(kettleUsername)) optionUsername = new StringBuffer(kettleUsername); if (!Const.isEmpty(kettlePassword)) optionPassword = new StringBuffer(kettlePassword); // System.out.println("Level="+loglevel); LogWriter log; LogWriter.setConsoleAppenderDebug(); if (Const.isEmpty(optionLogfile)) { log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC ); } else { log=LogWriter.getInstance( optionLogfile.toString(), true, LogWriter.LOG_LEVEL_BASIC ); } if (!Const.isEmpty(optionLoglevel)) { log.setLogLevel(optionLoglevel.toString()); log.logMinimal(STRING_KITCHEN, "Logging is at level : "+log.getLogLevelDesc()); } if (!Const.isEmpty(optionVersion)) { BuildVersion buildVersion = BuildVersion.getInstance(); log.logBasic("Pan", "Kettle version "+Const.VERSION+", build "+buildVersion.getVersion()+", build date : "+buildVersion.getBuildDate()); if (a.length==1) System.exit(6); } // Start the action... // if (!Const.isEmpty(optionRepname) && !Const.isEmpty(optionUsername)) log.logDetailed(STRING_KITCHEN, "Repository and username supplied"); log.logMinimal(STRING_KITCHEN, "Start of run."); /* Load the plugins etc.*/ StepLoader steploader = StepLoader.getInstance(); if (!steploader.read()) { log.logError(STRING_KITCHEN, "Error loading steps... halting Kitchen!"); System.exit(8); } /* Load the plugins etc.*/ JobEntryLoader jeloader = JobEntryLoader.getInstance(); if (!jeloader.read()) { log.logError(STRING_KITCHEN, "Error loading job entries & plugins... halting Kitchen!"); return; } Date start, stop; Calendar cal; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal=Calendar.getInstance(); start=cal.getTime(); log.logDebug(STRING_KITCHEN, "Allocate new job."); JobMeta jobMeta = new JobMeta(log); // In case we use a repository... Repository repository = null; try { // Read kettle job specified on command-line? if (!Const.isEmpty(optionRepname) || !Const.isEmpty(optionFilename)) { log.logDebug(STRING_KITCHEN, "Parsing command line options."); if (optionRepname!=null && !"Y".equalsIgnoreCase(optionNorep.toString())) { log.logDebug(STRING_KITCHEN, "Loading available repositories."); RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { log.logDebug(STRING_KITCHEN, "Finding repository ["+optionRepname+"]"); repinfo = repsinfo.findRepository(optionRepname.toString()); if (repinfo!=null) { // Define and connect to the repository... log.logDebug(STRING_KITCHEN, "Allocate & connect to repository."); repository = new Repository(log, repinfo, userinfo); if (repository.connect("Kitchen commandline")) { RepositoryDirectory directory = repository.getDirectoryTree(); // Default = root // Find the directory name if one is specified... if (!Const.isEmpty(optionDirname)) { directory = repository.getDirectoryTree().findDirectory(optionDirname.toString()); } if (directory!=null) { // Check username, password log.logDebug(STRING_KITCHEN, "Check supplied username and password."); userinfo = new UserInfo(repository, optionUsername.toString(), optionPassword.toString()); if (userinfo.getID()>0) { // Load a job if (!Const.isEmpty(optionJobname)) { log.logDebug(STRING_KITCHEN, "Load the job info..."); jobMeta = new JobMeta(log, repository, optionJobname.toString(), directory); log.logDebug(STRING_KITCHEN, "Allocate job..."); job = new Job(log, steploader, repository, jobMeta); } else // List the jobs in the repository if ("Y".equalsIgnoreCase(optionListjobs.toString())) { log.logDebug(STRING_KITCHEN, "Getting list of jobs in directory: "+directory); String jobnames[] = repository.getJobNames(directory.getID()); for (int i=0;i<jobnames.length;i++) { System.out.println(jobnames[i]); } } else // List the directories in the repository if ("Y".equalsIgnoreCase(optionListdir.toString())) { String dirnames[] = repository.getDirectoryNames(directory.getID()); for (int i=0;i<dirnames.length;i++) { System.out.println(dirnames[i]); } } } else { System.out.println("ERROR: Can't verify username and password."); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't find the supplied directory ["+optionDirname+"]"); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't connect to the repository."); } } else { System.out.println("ERROR: No repository provided, can't load job."); } } else { System.out.println("ERROR: No repositories defined on this system."); } } // Try to load if from file anyway. if (!Const.isEmpty(optionFilename) && job==null) { jobMeta = new JobMeta(log, optionFilename.toString(), null); job = new Job(log, steploader, null, jobMeta); } } else if ("Y".equalsIgnoreCase(optionListrep.toString())) { RepositoriesMeta ri = new RepositoriesMeta(log); if (ri.readData()) { System.out.println("List of repositories:"); for (int i=0;i<ri.nrRepositories();i++) { RepositoryMeta rinfo = ri.getRepository(i); System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] "); } } else { System.out.println("ERROR: Unable to read/parse the repositories XML file."); } } } catch(KettleException e) { job=null; jobMeta=null; System.out.println("Processing stopped because of an error: "+e.getMessage()); } if (job==null) { if (!"Y".equalsIgnoreCase(optionListjobs.toString()) && !"Y".equalsIgnoreCase(optionListdir.toString()) && !"Y".equalsIgnoreCase(optionListrep.toString()) ) { System.out.println("ERROR: Kitchen can't continue because the job couldn't be loaded."); } System.exit(7); } Result result = null; int returnCode=0; try { // Add Kettle variables for the job thread... LocalVariables.getInstance().createKettleVariables(job.getName(), parentThread.getName(), true); // Set the arguments on the job metadata as well... if ( args.size() == 0 ) { job.getJobMeta().setArguments(null); } else { job.getJobMeta().setArguments((String[]) args.toArray(new String[args.size()])); } result = job.execute(); // Execute the selected job. job.endProcessing("end", result); // The bookkeeping... } catch(KettleJobException je) { if (result==null) { result = new Result(); } result.setNrErrors(1L); try { job.endProcessing("error", result); } catch(KettleJobException je2) { log.logError(job.getName(), "A serious error occured : "+je2.getMessage()); returnCode = 2; } } finally { if (repository!=null) repository.disconnect(); } log.logMinimal(STRING_KITCHEN, "Finished!"); if (result!=null && result.getNrErrors()!=0) { log.logError(STRING_KITCHEN, "Finished with errors"); returnCode = 1; } cal=Calendar.getInstance(); stop=cal.getTime(); String begin=df.format(start).toString(); String end =df.format(stop).toString(); log.logMinimal(STRING_KITCHEN, "Start="+begin+", Stop="+end); long millis=stop.getTime()-start.getTime(); log.logMinimal(STRING_KITCHEN, "Processing ended after "+(millis/1000)+" seconds."); System.exit(returnCode); }
diff --git a/api/src/main/java/com/github/podd/utils/OntologyUtils.java b/api/src/main/java/com/github/podd/utils/OntologyUtils.java index 9bc57483..b368d1b0 100644 --- a/api/src/main/java/com/github/podd/utils/OntologyUtils.java +++ b/api/src/main/java/com/github/podd/utils/OntologyUtils.java @@ -1,137 +1,137 @@ package com.github.podd.utils; import java.util.ArrayList; import java.util.Collection; import org.openrdf.model.Model; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.model.vocabulary.OWL; import org.openrdf.model.vocabulary.RDF; import org.openrdf.rio.RDFHandler; import org.openrdf.rio.RDFHandlerException; /** * Utilities for working with {@link InferredOWLOntologyID} * * @author Peter Ansell [email protected] */ public class OntologyUtils { private OntologyUtils() { } /** * Serialises the given collection of {@link InferredOWLOntologyID} objects to RDF, adding the * {@link Statement}s to the given {@link Model}, or creating a new Model if the given model is * null. * <p> * This method wraps the serialisation from {@link InferredOWLOntologyID#toRDF()}. * * @param input * The collection of {@link InferredOWLOntologyID} objects to render to RDF. * @param result * The Model to contain the resulting statements, or null to have one created * internally * @return A model containing the RDF statements about the given ontologies. * @throws RDFHandlerException * If there is an error while handling the statements. */ public static Model ontologyIDsToModel(Collection<InferredOWLOntologyID> input, Model result) { Model results = result; if(results == null) { results = new LinkedHashModel(); } for(InferredOWLOntologyID nextOntology : input) { results.addAll(nextOntology.toRDF()); } return results; } /** * Serialises the given collection of {@link InferredOWLOntologyID} objects to RDF, adding the * {@link Statement}s to the given {@link RDFHandler}. * <p> * This method wraps the serialisation from {@link InferredOWLOntologyID#toRDF()}. * * @param input * The collection of {@link InferredOWLOntologyID} objects to render to RDF. * @param handler * The handler for handling the RDF statements. * @throws RDFHandlerException * If there is an error while handling the statements. */ public static void ontologyIDsToHandler(Collection<InferredOWLOntologyID> input, RDFHandler handler) throws RDFHandlerException { for(InferredOWLOntologyID nextOntology : input) { for(Statement nextStatement : nextOntology.toRDF()) { handler.handleStatement(nextStatement); } } } /** * Extracts the {@link InferredOWLOntologyID} instances that are represented as RDF * {@link Statement}s in the given {@link Model}. * * @param input * The input model containing RDF statements. * @return A Collection of {@link InferredOWLOntologyID} instances derived from the statements * in the model. */ public static Collection<InferredOWLOntologyID> modelToOntologyIDs(Model input) { Collection<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>(); Model typedOntologies = input.filter(null, RDF.TYPE, OWL.ONTOLOGY); for(Statement nextTypeStatement : typedOntologies) { if(nextTypeStatement.getSubject() instanceof URI) { Model versions = input.filter((URI)nextTypeStatement.getSubject(), OWL.VERSIONIRI, null); for(Statement nextVersion : versions) { if(nextVersion.getObject() instanceof URI) { Model inferredOntologies = input.filter((URI)nextVersion.getObject(), PoddRdfConstants.PODD_BASE_INFERRED_VERSION, null); if(inferredOntologies.isEmpty()) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextTypeStatement.getObject(), null)); } else { for(Statement nextInferredOntology : inferredOntologies) { - if(nextInferredOntology instanceof URI) + if(nextInferredOntology.getObject() instanceof URI) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextTypeStatement.getObject(), (URI)nextInferredOntology.getObject())); } } } } } } } return results; } }
true
true
public static Collection<InferredOWLOntologyID> modelToOntologyIDs(Model input) { Collection<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>(); Model typedOntologies = input.filter(null, RDF.TYPE, OWL.ONTOLOGY); for(Statement nextTypeStatement : typedOntologies) { if(nextTypeStatement.getSubject() instanceof URI) { Model versions = input.filter((URI)nextTypeStatement.getSubject(), OWL.VERSIONIRI, null); for(Statement nextVersion : versions) { if(nextVersion.getObject() instanceof URI) { Model inferredOntologies = input.filter((URI)nextVersion.getObject(), PoddRdfConstants.PODD_BASE_INFERRED_VERSION, null); if(inferredOntologies.isEmpty()) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextTypeStatement.getObject(), null)); } else { for(Statement nextInferredOntology : inferredOntologies) { if(nextInferredOntology instanceof URI) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextTypeStatement.getObject(), (URI)nextInferredOntology.getObject())); } } } } } } } return results; }
public static Collection<InferredOWLOntologyID> modelToOntologyIDs(Model input) { Collection<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>(); Model typedOntologies = input.filter(null, RDF.TYPE, OWL.ONTOLOGY); for(Statement nextTypeStatement : typedOntologies) { if(nextTypeStatement.getSubject() instanceof URI) { Model versions = input.filter((URI)nextTypeStatement.getSubject(), OWL.VERSIONIRI, null); for(Statement nextVersion : versions) { if(nextVersion.getObject() instanceof URI) { Model inferredOntologies = input.filter((URI)nextVersion.getObject(), PoddRdfConstants.PODD_BASE_INFERRED_VERSION, null); if(inferredOntologies.isEmpty()) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextTypeStatement.getObject(), null)); } else { for(Statement nextInferredOntology : inferredOntologies) { if(nextInferredOntology.getObject() instanceof URI) { results.add(new InferredOWLOntologyID((URI)nextTypeStatement.getSubject(), (URI)nextTypeStatement.getObject(), (URI)nextInferredOntology.getObject())); } } } } } } } return results; }
diff --git a/src/com/josephblough/sbt/criteria/AwardsSearchCriteria.java b/src/com/josephblough/sbt/criteria/AwardsSearchCriteria.java index 2924cba..aa979ab 100644 --- a/src/com/josephblough/sbt/criteria/AwardsSearchCriteria.java +++ b/src/com/josephblough/sbt/criteria/AwardsSearchCriteria.java @@ -1,153 +1,153 @@ package com.josephblough.sbt.criteria; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; public class AwardsSearchCriteria implements Parcelable { private final static String TAG = "AwardsSearchCriteria"; private final static String SEARCHES_JSON_ARRAY = "searches"; private final static String NAME_JSON_ELEMENT = "name"; private final static String DOWLOAD_ALL_JSON_ELEMENT = "download_all"; private final static String SEARCH_TERM_JSON_ELEMENT = "search_term"; private final static String AGENCY_JSON_ELEMENT = "agency"; private final static String COMPANY_JSON_ELEMENT = "company"; private final static String INSTITUTION_JSON_ELEMENT = "institution"; private final static String YEAR_JSON_ELEMENT = "year"; public boolean downloadAll; public String searchTerm; public String agency; public String company; public String institution; public int year; public AwardsSearchCriteria(boolean downloadAll, String searchTerm, String agency, String company, String institution, int year) { this.downloadAll = downloadAll; this.searchTerm = (searchTerm == null) ? null : searchTerm.trim(); this.agency = (agency == null) ? null : agency.trim(); this.company = (company == null) ? null : company.trim(); this.institution = (institution == null) ? null : institution.trim(); this.year = year; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(downloadAll ? 1 : 0); dest.writeString(searchTerm == null ? "" : searchTerm); dest.writeString(agency == null ? "" : agency); dest.writeString(company == null ? "" : company); dest.writeString(institution == null ? "" : institution); dest.writeInt(year); } public static final Parcelable.Creator<AwardsSearchCriteria> CREATOR = new Parcelable.Creator<AwardsSearchCriteria>() { public AwardsSearchCriteria createFromParcel(Parcel in) { return new AwardsSearchCriteria(in); } public AwardsSearchCriteria[] newArray(int size) { return new AwardsSearchCriteria[size]; } }; private AwardsSearchCriteria(Parcel in) { downloadAll = in.readInt() == 1; searchTerm = in.readString(); agency = in.readString(); company = in.readString(); institution = in.readString(); year = in.readInt(); } public static Map<String, AwardsSearchCriteria> convertFromJson(final String jsonString) { Map<String, AwardsSearchCriteria> searches = new HashMap<String, AwardsSearchCriteria>(); if (jsonString != null && !"".equals(jsonString)) { try { JSONObject json = new JSONObject(jsonString); JSONArray jsonSearches = json.optJSONArray(SEARCHES_JSON_ARRAY); if (jsonSearches != null) { int length = jsonSearches.length(); for (int i=0; i<length; i++) { JSONObject jsonSearch = jsonSearches.getJSONObject(i); - String name = json.getString(NAME_JSON_ELEMENT); + String name = jsonSearch.getString(NAME_JSON_ELEMENT); AwardsSearchCriteria search = new AwardsSearchCriteria(jsonSearch); searches.put(name, search); } } } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } } return searches; } public static String convertToJson(final Map<String, AwardsSearchCriteria> criteria) { JSONObject json = new JSONObject(); try { JSONArray jsonSearches = new JSONArray(); for (Entry<String, AwardsSearchCriteria> entry : criteria.entrySet()) { AwardsSearchCriteria search = entry.getValue(); JSONObject jsonSearch = search.toJson(); jsonSearch.put(NAME_JSON_ELEMENT, entry.getKey()); jsonSearches.put(jsonSearch); } json.put(SEARCHES_JSON_ARRAY, jsonSearches); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } return json.toString(); } public AwardsSearchCriteria(final String jsonString) throws JSONException { this(new JSONObject(jsonString)); } public AwardsSearchCriteria(final JSONObject json) { try { downloadAll = json.getBoolean(DOWLOAD_ALL_JSON_ELEMENT); searchTerm = json.getString(SEARCH_TERM_JSON_ELEMENT); agency = json.getString(AGENCY_JSON_ELEMENT); company = json.getString(COMPANY_JSON_ELEMENT); institution = json.getString(INSTITUTION_JSON_ELEMENT); year = json.optInt(YEAR_JSON_ELEMENT, 0); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } } public JSONObject toJson() { JSONObject json = new JSONObject(); try { json.put(DOWLOAD_ALL_JSON_ELEMENT, downloadAll); json.put(SEARCH_TERM_JSON_ELEMENT, searchTerm); json.put(AGENCY_JSON_ELEMENT, agency); json.put(COMPANY_JSON_ELEMENT, company); json.put(INSTITUTION_JSON_ELEMENT, institution); json.put(YEAR_JSON_ELEMENT, year); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } return json; } }
true
true
public static Map<String, AwardsSearchCriteria> convertFromJson(final String jsonString) { Map<String, AwardsSearchCriteria> searches = new HashMap<String, AwardsSearchCriteria>(); if (jsonString != null && !"".equals(jsonString)) { try { JSONObject json = new JSONObject(jsonString); JSONArray jsonSearches = json.optJSONArray(SEARCHES_JSON_ARRAY); if (jsonSearches != null) { int length = jsonSearches.length(); for (int i=0; i<length; i++) { JSONObject jsonSearch = jsonSearches.getJSONObject(i); String name = json.getString(NAME_JSON_ELEMENT); AwardsSearchCriteria search = new AwardsSearchCriteria(jsonSearch); searches.put(name, search); } } } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } } return searches; }
public static Map<String, AwardsSearchCriteria> convertFromJson(final String jsonString) { Map<String, AwardsSearchCriteria> searches = new HashMap<String, AwardsSearchCriteria>(); if (jsonString != null && !"".equals(jsonString)) { try { JSONObject json = new JSONObject(jsonString); JSONArray jsonSearches = json.optJSONArray(SEARCHES_JSON_ARRAY); if (jsonSearches != null) { int length = jsonSearches.length(); for (int i=0; i<length; i++) { JSONObject jsonSearch = jsonSearches.getJSONObject(i); String name = jsonSearch.getString(NAME_JSON_ELEMENT); AwardsSearchCriteria search = new AwardsSearchCriteria(jsonSearch); searches.put(name, search); } } } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } } return searches; }
diff --git a/src/test/java/mikera/expresso/TestExpresso.java b/src/test/java/mikera/expresso/TestExpresso.java index 13ef991..634233e 100644 --- a/src/test/java/mikera/expresso/TestExpresso.java +++ b/src/test/java/mikera/expresso/TestExpresso.java @@ -1,11 +1,11 @@ package mikera.expresso; import mikera.cljunit.ClojureTest; public class TestExpresso extends ClojureTest { @Override public String filter() { - return "mikera.expresso"; + return "numeric.expresso"; } }
true
true
public String filter() { return "mikera.expresso"; }
public String filter() { return "numeric.expresso"; }
diff --git a/nuxeo-core/src/main/java/org/nuxeo/ecm/core/versioning/StandardVersioningService.java b/nuxeo-core/src/main/java/org/nuxeo/ecm/core/versioning/StandardVersioningService.java index 1928f5629..d0ce5604a 100644 --- a/nuxeo-core/src/main/java/org/nuxeo/ecm/core/versioning/StandardVersioningService.java +++ b/nuxeo-core/src/main/java/org/nuxeo/ecm/core/versioning/StandardVersioningService.java @@ -1,283 +1,281 @@ /* * (C) Copyright 2010 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Florent Guillaume */ package org.nuxeo.ecm.core.versioning; import static org.nuxeo.ecm.core.api.VersioningOption.MAJOR; import static org.nuxeo.ecm.core.api.VersioningOption.MINOR; import static org.nuxeo.ecm.core.api.VersioningOption.NONE; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.DocumentException; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.VersioningOption; import org.nuxeo.ecm.core.api.model.PropertyNotFoundException; import org.nuxeo.ecm.core.lifecycle.LifeCycleException; import org.nuxeo.ecm.core.model.Document; import org.nuxeo.ecm.core.model.NoSuchPropertyException; import org.nuxeo.ecm.core.schema.FacetNames; /** * Implementation of the versioning service that follows standard checkout / * checkin semantics. */ public class StandardVersioningService implements VersioningService { private static final Log log = LogFactory.getLog(StandardVersioningService.class); public static final String FILE_TYPE = "File"; public static final String NOTE_TYPE = "Note"; public static final String PROJECT_STATE = "project"; public static final String APPROVED_STATE = "approved"; public static final String OBSOLETE_STATE = "obsolete"; public static final String BACK_TO_PROJECT_TRANSITION = "backToProject"; protected static final String AUTO_CHECKED_OUT = "AUTO_CHECKED_OUT"; /** Key for major version in Document API. */ protected static final String MAJOR_VERSION = "major_version"; /** Key for minor version in Document API. */ protected static final String MINOR_VERSION = "minor_version"; @Override public String getVersionLabel(DocumentModel docModel) { String label; try { label = getMajor(docModel) + "." + getMinor(docModel); if (docModel.isCheckedOut() && !"0.0".equals(label)) { label += "+"; } } catch (PropertyNotFoundException e) { label = ""; } catch (ClientException e) { log.debug("No version label", e); label = ""; } return label; } protected long getMajor(DocumentModel docModel) throws ClientException { return getVersion(docModel, VersioningService.MAJOR_VERSION_PROP); } protected long getMinor(DocumentModel docModel) throws ClientException { return getVersion(docModel, VersioningService.MINOR_VERSION_PROP); } protected long getVersion(DocumentModel docModel, String prop) throws ClientException { Object propVal = docModel.getPropertyValue(prop); if (propVal == null || !(propVal instanceof Long)) { return 0; } else { return ((Long) propVal).longValue(); } } protected long getMajor(Document doc) throws DocumentException { return getVersion(doc, MAJOR_VERSION); } protected long getMinor(Document doc) throws DocumentException { return getVersion(doc, MINOR_VERSION); } protected long getVersion(Document doc, String prop) throws DocumentException { Object propVal = doc.getPropertyValue(prop); if (propVal == null || !(propVal instanceof Long)) { return 0; } else { return ((Long) propVal).longValue(); } } protected void setVersion(Document doc, long major, long minor) throws DocumentException { doc.setPropertyValue(MAJOR_VERSION, Long.valueOf(major)); doc.setPropertyValue(MINOR_VERSION, Long.valueOf(minor)); } protected void incrementMajor(Document doc) throws DocumentException { setVersion(doc, getMajor(doc) + 1, 0); } protected void incrementMinor(Document doc) throws DocumentException { doc.setPropertyValue("minor_version", Long.valueOf(getMinor(doc) + 1)); } protected void incrementByOption(Document doc, VersioningOption option) throws DocumentException { try { if (option == MAJOR) { incrementMajor(doc); } else if (option == MINOR) { incrementMinor(doc); } // else nothing } catch (NoSuchPropertyException e) { // ignore } } @Override public void doPostCreate(Document doc) throws DocumentException { if (doc.isVersion() || doc.isProxy()) { return; } try { setInitialVersion(doc); } catch (DocumentException e) { // ignore } } /** * Sets the initial version on a document. Can be overridden. */ protected void setInitialVersion(Document doc) throws DocumentException { setVersion(doc, 0, 0); } @Override public List<VersioningOption> getSaveOptions(DocumentModel docModel) throws ClientException { boolean versionable = docModel.isVersionable(); String lifecycleState; try { lifecycleState = docModel.getCoreSession().getCurrentLifeCycleState( docModel.getRef()); } catch (ClientException e) { lifecycleState = null; } String type = docModel.getType(); return getSaveOptions(versionable, lifecycleState, type); } protected List<VersioningOption> getSaveOptions(Document doc) throws DocumentException { boolean versionable = doc.getType().getFacets().contains( FacetNames.VERSIONABLE); String lifecycleState; try { lifecycleState = doc.getCurrentLifeCycleState(); } catch (LifeCycleException e) { lifecycleState = null; } String type = doc.getType().getName(); return getSaveOptions(versionable, lifecycleState, type); } protected List<VersioningOption> getSaveOptions(boolean versionable, String lifecycleState, String type) { if (!versionable) { return Arrays.asList(NONE); } if (lifecycleState == null) { return Arrays.asList(NONE); } - if (APPROVED_STATE.equals(lifecycleState) + if (PROJECT_STATE.equals(lifecycleState) + || APPROVED_STATE.equals(lifecycleState) || OBSOLETE_STATE.equals(lifecycleState)) { - return Arrays.asList(MAJOR, MINOR); - } - if (PROJECT_STATE.equals(lifecycleState)) { return Arrays.asList(NONE, MINOR, MAJOR); } if (FILE_TYPE.equals(type) || NOTE_TYPE.equals(type)) { return Arrays.asList(NONE, MINOR, MAJOR); } return Arrays.asList(NONE); } protected VersioningOption validateOption(Document doc, VersioningOption option) throws DocumentException { List<VersioningOption> options = getSaveOptions(doc); if (!options.contains(option)) { option = options.get(0); } return option; } @Override public VersioningOption doPreSave(Document doc, boolean isDirty, VersioningOption option, String checkinComment) throws DocumentException { option = validateOption(doc, option); if (!doc.isCheckedOut() && isDirty) { doc.checkOut(); followTransitionByOption(doc, option); } // transition follow shouldn't change what postSave options will be return option; } protected void followTransitionByOption(Document doc, VersioningOption option) throws DocumentException { try { String lifecycleState = doc.getCurrentLifeCycleState(); if (APPROVED_STATE.equals(lifecycleState) || OBSOLETE_STATE.equals(lifecycleState)) { doc.followTransition(BACK_TO_PROJECT_TRANSITION); } } catch (LifeCycleException e) { throw new DocumentException(e); } } @Override public void doPostSave(Document doc, VersioningOption option, String checkinComment) throws DocumentException { // option = validateOption(doc, option); // validated before boolean increment = option != NONE; if (doc.isCheckedOut() && increment) { incrementByOption(doc, option); doc.checkIn(null, checkinComment); // auto-label } } @Override public DocumentVersion doCheckIn(Document doc, VersioningOption option, String checkinComment) throws DocumentException { incrementByOption(doc, option == MAJOR ? MAJOR : MINOR); return doc.checkIn(null, checkinComment); // auto-label } @Override public void doCheckOut(Document doc) throws DocumentException { doc.checkOut(); // set version number to that of the last version try { DocumentVersion last = doc.getLastVersion(); if (last != null) { setVersion(doc, getMajor(last), getMinor(last)); } } catch (NoSuchPropertyException e) { // ignore } } }
false
true
protected List<VersioningOption> getSaveOptions(boolean versionable, String lifecycleState, String type) { if (!versionable) { return Arrays.asList(NONE); } if (lifecycleState == null) { return Arrays.asList(NONE); } if (APPROVED_STATE.equals(lifecycleState) || OBSOLETE_STATE.equals(lifecycleState)) { return Arrays.asList(MAJOR, MINOR); } if (PROJECT_STATE.equals(lifecycleState)) { return Arrays.asList(NONE, MINOR, MAJOR); } if (FILE_TYPE.equals(type) || NOTE_TYPE.equals(type)) { return Arrays.asList(NONE, MINOR, MAJOR); } return Arrays.asList(NONE); }
protected List<VersioningOption> getSaveOptions(boolean versionable, String lifecycleState, String type) { if (!versionable) { return Arrays.asList(NONE); } if (lifecycleState == null) { return Arrays.asList(NONE); } if (PROJECT_STATE.equals(lifecycleState) || APPROVED_STATE.equals(lifecycleState) || OBSOLETE_STATE.equals(lifecycleState)) { return Arrays.asList(NONE, MINOR, MAJOR); } if (FILE_TYPE.equals(type) || NOTE_TYPE.equals(type)) { return Arrays.asList(NONE, MINOR, MAJOR); } return Arrays.asList(NONE); }
diff --git a/src/impl/java/org/wyona/security/impl/util/UserUtil.java b/src/impl/java/org/wyona/security/impl/util/UserUtil.java index f23091c..7c1deea 100644 --- a/src/impl/java/org/wyona/security/impl/util/UserUtil.java +++ b/src/impl/java/org/wyona/security/impl/util/UserUtil.java @@ -1,26 +1,26 @@ package org.wyona.security.impl.util; import org.wyona.security.core.api.User; import org.apache.log4j.Logger; /** * Utility class for various user operations */ public class UserUtil { private static Logger log = Logger.getLogger(UserUtil.class); /** * Check whether user is expired */ - public boolean isExpired(User user){ + public static boolean isExpired(User user){ boolean expired = false; if(user.getExpirationDate() != null){ expired = user.getExpirationDate().before(new java.util.Date()); // INFO: Compare with NOW/Today } else { - log.warn("DEBUG: User '' has no expiration date and hence never expires."); + log.debug("User '' has no expiration date and hence never expires."); } return expired; } }
false
true
public boolean isExpired(User user){ boolean expired = false; if(user.getExpirationDate() != null){ expired = user.getExpirationDate().before(new java.util.Date()); // INFO: Compare with NOW/Today } else { log.warn("DEBUG: User '' has no expiration date and hence never expires."); } return expired; }
public static boolean isExpired(User user){ boolean expired = false; if(user.getExpirationDate() != null){ expired = user.getExpirationDate().before(new java.util.Date()); // INFO: Compare with NOW/Today } else { log.debug("User '' has no expiration date and hence never expires."); } return expired; }
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus502/Nexus502MavenExecutionTest.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus502/Nexus502MavenExecutionTest.java index 63e759fac..cf7fccc46 100644 --- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus502/Nexus502MavenExecutionTest.java +++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus502/Nexus502MavenExecutionTest.java @@ -1,113 +1,112 @@ package org.sonatype.nexus.integrationtests.nexus502; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.apache.commons.io.FileUtils; import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; import org.junit.Before; import org.junit.Test; import org.restlet.data.MediaType; import org.sonatype.nexus.integrationtests.AbstractNexusIntegrationTest; import org.sonatype.nexus.integrationtests.TestContainer; import org.sonatype.nexus.rest.model.UserResource; import org.sonatype.nexus.rest.xstream.XStreamInitializer; import org.sonatype.nexus.test.utils.UserMessageUtil; import com.thoughtworks.xstream.XStream; public class Nexus502MavenExecutionTest extends AbstractNexusIntegrationTest { static { TestContainer.getInstance().getTestContext().setSecureTest( true ); printKnownErrorButDoNotFail( Nexus502MavenExecutionTest.class, "dependencyDownloadProtectedServer" ); } private Verifier verifier; @Before public void createVerifier() throws VerificationException, IOException { verifier = new Verifier( getTestFile( "maven-project" ).getAbsolutePath(), false ); verifier.deleteArtifact( "nexus502", "artifact-1", "1.0.0", "jar" ); verifier.deleteArtifact( "nexus502", "artifact-1", "1.0.0", "pom" ); verifier.deleteArtifact( "nexus502", "artifact-2", "1.0.0", "jar" ); verifier.deleteArtifact( "nexus502", "artifact-2", "1.0.0", "pom" ); verifier.deleteArtifact( "nexus502", "artifact-3", "1.0.0", "jar" ); verifier.deleteArtifact( "nexus502", "artifact-3", "1.0.0", "pom" ); verifier.deleteArtifact( "nexus502", "maven-execution", "1.0.0", "jar" ); verifier.deleteArtifact( "nexus502", "maven-execution", "1.0.0", "pom" ); verifier.resetStreams(); List<String> options = new ArrayList<String>(); options.add( "-s " + getTestFile( "repositories.xml" ).getAbsolutePath() ); verifier.setCliOptions( options ); } @Test public void dependencyDownload() throws Exception { verifier.executeGoal( "dependency:resolve" ); verifier.verifyErrorFreeLog(); } @Test public void dependencyDownloadPrivateServer() throws Exception { // Disable anonymous disableUser( "anonymous" ); verifier = new Verifier( getTestFile( "maven-project2" ).getAbsolutePath(), false ); verifier.resetStreams(); try { verifier.executeGoal( "dependency:resolve" ); verifier.verifyErrorFreeLog(); File logFile = new File( verifier.getBasedir(), "log.txt" ); String log = FileUtils.readFileToString( logFile ); - System.out.println( log ); - Assert.fail(); + Assert.fail(log); } catch ( VerificationException e ) { } } private UserResource disableUser( String userId ) throws IOException { UserMessageUtil util = new UserMessageUtil( XStreamInitializer.initialize( new XStream() ), MediaType.APPLICATION_XML ); return util.disableUser( userId ); } // Depends on nexus-508 // @Test // public void dependencyDownloadProtectedServer() // throws Exception // { // // Disable anonymous // disableUser( "anonymous" ); // // List<String> options = new ArrayList<String>(); // options.add( "-s " + getTestFile( "repositoriesWithAuthentication.xml" ).getAbsolutePath() ); // verifier.setCliOptions( options ); // verifier.executeGoal( "dependency:resolve" ); // verifier.verifyErrorFreeLog(); // } }
true
true
public void dependencyDownloadPrivateServer() throws Exception { // Disable anonymous disableUser( "anonymous" ); verifier = new Verifier( getTestFile( "maven-project2" ).getAbsolutePath(), false ); verifier.resetStreams(); try { verifier.executeGoal( "dependency:resolve" ); verifier.verifyErrorFreeLog(); File logFile = new File( verifier.getBasedir(), "log.txt" ); String log = FileUtils.readFileToString( logFile ); System.out.println( log ); Assert.fail(); } catch ( VerificationException e ) { } }
public void dependencyDownloadPrivateServer() throws Exception { // Disable anonymous disableUser( "anonymous" ); verifier = new Verifier( getTestFile( "maven-project2" ).getAbsolutePath(), false ); verifier.resetStreams(); try { verifier.executeGoal( "dependency:resolve" ); verifier.verifyErrorFreeLog(); File logFile = new File( verifier.getBasedir(), "log.txt" ); String log = FileUtils.readFileToString( logFile ); Assert.fail(log); } catch ( VerificationException e ) { } }
diff --git a/java/server/src/org/openqa/selenium/server/commands/CaptureNetworkTrafficCommand.java b/java/server/src/org/openqa/selenium/server/commands/CaptureNetworkTrafficCommand.java index 71a5853af..b79309771 100644 --- a/java/server/src/org/openqa/selenium/server/commands/CaptureNetworkTrafficCommand.java +++ b/java/server/src/org/openqa/selenium/server/commands/CaptureNetworkTrafficCommand.java @@ -1,287 +1,287 @@ package org.openqa.selenium.server.commands; import org.openqa.jetty.http.HttpRequest; import org.openqa.jetty.http.HttpResponse; import java.util.*; import java.text.SimpleDateFormat; public class CaptureNetworkTrafficCommand extends Command { private static final List<Entry> entries = Collections.synchronizedList(new ArrayList<Entry>()); public static void clear() { entries.clear(); } public static void capture(Entry entry) { entries.add(entry); } private String type; // ie: XML, JSON, plain text, etc public CaptureNetworkTrafficCommand(String type) { this.type = type; } public String execute() { StringBuilder sb = new StringBuilder(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); if ("json".equalsIgnoreCase(type)) { /* [{ statusCode: 200, method: 'GET', url: 'http://foo.com/index.html', bytes: 12422, start: '2009-03-15T14:23:00.000-0700', end: '2009-03-15T14:23:00.102-0700', timeInMillis: 102, requestHeaders: [{ name: 'Foo', value: 'Bar' }], responseHeaders: [{ name: 'Baz', value: 'Blah' }] },{ ... }] */ sb.append("["); synchronized(entries) { for (final Iterator<Entry> iterator = entries.iterator(); iterator.hasNext();) { final Entry entry = iterator.next(); sb.append("{\n"); sb.append(jsonKey("statusCode")).append(entry.statusCode).append(",\n"); sb.append(jsonKey("method")).append(json(entry.method)).append(",\n"); sb.append(jsonKey("url")).append(json(entry.url)).append(",\n"); sb.append(jsonKey("bytes")).append(entry.bytes).append(",\n"); sb.append(jsonKey("start")).append(json(sdf.format(entry.start))).append(",\n"); sb.append(jsonKey("end")).append(json(sdf.format(entry.end))).append(",\n"); sb.append(jsonKey("timeInMillis")).append((entry.end.getTime() - entry.start.getTime())).append(",\n"); sb.append(jsonKey("requestHeaders")).append("["); jsonHeaders(sb, entry.requestHeaders); sb.append("],\n"); sb.append(jsonKey("responseHeaders")).append("["); jsonHeaders(sb, entry.responseHeaders); sb.append("]\n"); sb.append("}"); if (iterator.hasNext()) { sb.append(",\n"); } } } sb.append("]"); } else if ("xml".equalsIgnoreCase(type)) { /* <traffic> <entry statusCode="200" method="GET" url="http://foo.com/index.html" bytes="12422" start="2009-03-15T14:23:00.000-0700" end="2009-03-15T14:23:00.102-0700" timeInMillis="102"> <requestHeaders> <header name=""></header> </requestHeaders> <responseHeaders> <header name=""></header> </responseHeaders> </entry> </traffic> */ sb.append("<traffic>\n"); synchronized(entries) { for (final Entry entry : entries) { sb.append("<entry "); sb.append("statusCode=\"").append(entry.statusCode).append("\" "); - sb.append("method=\"").append(json(entry.method)).append("\" "); + sb.append("method=\"").append(xml(entry.method)).append("\" "); sb.append("url=\"").append(xml(entry.url)).append("\" "); sb.append("bytes=\"").append(entry.bytes).append("\" "); sb.append("start=\"").append(sdf.format(entry.start)).append("\" "); sb.append("end=\"").append(sdf.format(entry.end)).append("\" "); sb.append("timeInMillis=\"").append((entry.end.getTime() - entry.start.getTime())).append("\">\n"); sb.append(" <requestHeaders>\n"); xmlHeaders(sb, entry.requestHeaders); sb.append(" </requestHeaders>\n"); sb.append(" <responseHeaders>\n"); xmlHeaders(sb, entry.responseHeaders); sb.append(" </responseHeaders>\n"); sb.append("</entry>\n"); } } sb.append("</traffic>\n"); } else { /* 200 GET http://foo.com/index.html 12422 bytes 102ms (2009-03-15T14:23:00.000-0700 - 2009-03-15T14:23:00.102-0700) Request Headers - Foo => Bar Response Headers - Baz => Blah ================================================================ */ synchronized(entries) { for (final Entry entry : entries) { sb.append(entry.statusCode).append(" ").append(entry.method).append(" ").append(entry.url).append("\n"); sb.append(entry.bytes).append(" bytes\n"); sb.append(entry.end.getTime() - entry.start.getTime()).append("ms (").append(sdf.format(entry.start)).append(" - ").append(sdf.format(entry.end)).append("\n"); sb.append("\n"); sb.append("Request Headers\n"); for (Header header : entry.requestHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("Response Headers\n"); for (Header header : entry.responseHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("================================================================\n"); sb.append("\n"); } } } clear(); return "OK," + sb.toString(); } private void xmlHeaders(final StringBuilder sb, final List<Header> headers) { for (final Header header : headers) { sb.append(" <header name=\"").append(xml(header.name)).append("\">").append(xml(header.value)).append("</header>\n"); } } private void jsonHeaders(final StringBuilder sb, final List<Header> headers) { for (final Iterator<Header> headItr = headers.iterator(); headItr.hasNext();) { final Header header = headItr.next(); sb.append("{\n"); sb.append(" ").append(jsonKey("name")).append(json(header.name)).append(",\n"); sb.append(" ").append(jsonKey("value")).append(json(header.value)).append("\n"); if (headItr.hasNext()) { sb.append(" },"); } else { sb.append(" }"); } } } private String xml(String s) { s = s.replaceAll("&", "&amp;"); s = s.replaceAll("\"", "&quot;"); s = s.replaceAll("\\<", "&lt;"); s = s.replaceAll("\\>", "&gt;"); return s; } private String jsonKey(final String key) { final StringBuilder ret = new StringBuilder(); ret.append(" \"").append(key).append("\"").append(":"); return ret.toString(); } private Object json(String s) { s = s.replaceAll("\\'", "\\\\'"); s = s.replaceAll("\\\"", "\\\\\""); s = s.replaceAll("\n", "\\\\n"); final StringBuilder ret = new StringBuilder(); ret.append("\"").append(s).append("\""); return ret.toString(); } public static class Entry { private String method; private String url; private int statusCode; private Date start; private Date end; private long bytes; private List<Header> requestHeaders = new ArrayList<Header>(); private List<Header> responseHeaders = new ArrayList<Header>(); public Entry(String method, String url) { this.method = method; this.url = url; this.start = new Date(); } public void finish(int statusCode, long bytes) { this.statusCode = statusCode; this.bytes = bytes; this.end = new Date(); } public void addRequestHeaders(HttpRequest request) { Enumeration names = request.getFieldNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = request.getField(name); requestHeaders.add(new Header(name, value)); } } public void addResponseHeader(HttpResponse response) { Enumeration names = response.getFieldNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = response.getField(name); responseHeaders.add(new Header(name, value)); } } public void setStart(Date start) { this.start = start; } public void setEnd(Date end) { this.end = end; } @Override public String toString() { return method + "|" + statusCode + "|" + url + "|" + requestHeaders.size() + "|" + responseHeaders.size() + "\n"; } public void addRequestHeader(String key, String value) { this.requestHeaders.add(new Header(key, value)); } } public static class Header { private String name; private String value; public Header(String name, String value) { this.name = name; this.value = value; } } }
true
true
public String execute() { StringBuilder sb = new StringBuilder(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); if ("json".equalsIgnoreCase(type)) { /* [{ statusCode: 200, method: 'GET', url: 'http://foo.com/index.html', bytes: 12422, start: '2009-03-15T14:23:00.000-0700', end: '2009-03-15T14:23:00.102-0700', timeInMillis: 102, requestHeaders: [{ name: 'Foo', value: 'Bar' }], responseHeaders: [{ name: 'Baz', value: 'Blah' }] },{ ... }] */ sb.append("["); synchronized(entries) { for (final Iterator<Entry> iterator = entries.iterator(); iterator.hasNext();) { final Entry entry = iterator.next(); sb.append("{\n"); sb.append(jsonKey("statusCode")).append(entry.statusCode).append(",\n"); sb.append(jsonKey("method")).append(json(entry.method)).append(",\n"); sb.append(jsonKey("url")).append(json(entry.url)).append(",\n"); sb.append(jsonKey("bytes")).append(entry.bytes).append(",\n"); sb.append(jsonKey("start")).append(json(sdf.format(entry.start))).append(",\n"); sb.append(jsonKey("end")).append(json(sdf.format(entry.end))).append(",\n"); sb.append(jsonKey("timeInMillis")).append((entry.end.getTime() - entry.start.getTime())).append(",\n"); sb.append(jsonKey("requestHeaders")).append("["); jsonHeaders(sb, entry.requestHeaders); sb.append("],\n"); sb.append(jsonKey("responseHeaders")).append("["); jsonHeaders(sb, entry.responseHeaders); sb.append("]\n"); sb.append("}"); if (iterator.hasNext()) { sb.append(",\n"); } } } sb.append("]"); } else if ("xml".equalsIgnoreCase(type)) { /* <traffic> <entry statusCode="200" method="GET" url="http://foo.com/index.html" bytes="12422" start="2009-03-15T14:23:00.000-0700" end="2009-03-15T14:23:00.102-0700" timeInMillis="102"> <requestHeaders> <header name=""></header> </requestHeaders> <responseHeaders> <header name=""></header> </responseHeaders> </entry> </traffic> */ sb.append("<traffic>\n"); synchronized(entries) { for (final Entry entry : entries) { sb.append("<entry "); sb.append("statusCode=\"").append(entry.statusCode).append("\" "); sb.append("method=\"").append(json(entry.method)).append("\" "); sb.append("url=\"").append(xml(entry.url)).append("\" "); sb.append("bytes=\"").append(entry.bytes).append("\" "); sb.append("start=\"").append(sdf.format(entry.start)).append("\" "); sb.append("end=\"").append(sdf.format(entry.end)).append("\" "); sb.append("timeInMillis=\"").append((entry.end.getTime() - entry.start.getTime())).append("\">\n"); sb.append(" <requestHeaders>\n"); xmlHeaders(sb, entry.requestHeaders); sb.append(" </requestHeaders>\n"); sb.append(" <responseHeaders>\n"); xmlHeaders(sb, entry.responseHeaders); sb.append(" </responseHeaders>\n"); sb.append("</entry>\n"); } } sb.append("</traffic>\n"); } else { /* 200 GET http://foo.com/index.html 12422 bytes 102ms (2009-03-15T14:23:00.000-0700 - 2009-03-15T14:23:00.102-0700) Request Headers - Foo => Bar Response Headers - Baz => Blah ================================================================ */ synchronized(entries) { for (final Entry entry : entries) { sb.append(entry.statusCode).append(" ").append(entry.method).append(" ").append(entry.url).append("\n"); sb.append(entry.bytes).append(" bytes\n"); sb.append(entry.end.getTime() - entry.start.getTime()).append("ms (").append(sdf.format(entry.start)).append(" - ").append(sdf.format(entry.end)).append("\n"); sb.append("\n"); sb.append("Request Headers\n"); for (Header header : entry.requestHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("Response Headers\n"); for (Header header : entry.responseHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("================================================================\n"); sb.append("\n"); } } } clear(); return "OK," + sb.toString(); }
public String execute() { StringBuilder sb = new StringBuilder(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); if ("json".equalsIgnoreCase(type)) { /* [{ statusCode: 200, method: 'GET', url: 'http://foo.com/index.html', bytes: 12422, start: '2009-03-15T14:23:00.000-0700', end: '2009-03-15T14:23:00.102-0700', timeInMillis: 102, requestHeaders: [{ name: 'Foo', value: 'Bar' }], responseHeaders: [{ name: 'Baz', value: 'Blah' }] },{ ... }] */ sb.append("["); synchronized(entries) { for (final Iterator<Entry> iterator = entries.iterator(); iterator.hasNext();) { final Entry entry = iterator.next(); sb.append("{\n"); sb.append(jsonKey("statusCode")).append(entry.statusCode).append(",\n"); sb.append(jsonKey("method")).append(json(entry.method)).append(",\n"); sb.append(jsonKey("url")).append(json(entry.url)).append(",\n"); sb.append(jsonKey("bytes")).append(entry.bytes).append(",\n"); sb.append(jsonKey("start")).append(json(sdf.format(entry.start))).append(",\n"); sb.append(jsonKey("end")).append(json(sdf.format(entry.end))).append(",\n"); sb.append(jsonKey("timeInMillis")).append((entry.end.getTime() - entry.start.getTime())).append(",\n"); sb.append(jsonKey("requestHeaders")).append("["); jsonHeaders(sb, entry.requestHeaders); sb.append("],\n"); sb.append(jsonKey("responseHeaders")).append("["); jsonHeaders(sb, entry.responseHeaders); sb.append("]\n"); sb.append("}"); if (iterator.hasNext()) { sb.append(",\n"); } } } sb.append("]"); } else if ("xml".equalsIgnoreCase(type)) { /* <traffic> <entry statusCode="200" method="GET" url="http://foo.com/index.html" bytes="12422" start="2009-03-15T14:23:00.000-0700" end="2009-03-15T14:23:00.102-0700" timeInMillis="102"> <requestHeaders> <header name=""></header> </requestHeaders> <responseHeaders> <header name=""></header> </responseHeaders> </entry> </traffic> */ sb.append("<traffic>\n"); synchronized(entries) { for (final Entry entry : entries) { sb.append("<entry "); sb.append("statusCode=\"").append(entry.statusCode).append("\" "); sb.append("method=\"").append(xml(entry.method)).append("\" "); sb.append("url=\"").append(xml(entry.url)).append("\" "); sb.append("bytes=\"").append(entry.bytes).append("\" "); sb.append("start=\"").append(sdf.format(entry.start)).append("\" "); sb.append("end=\"").append(sdf.format(entry.end)).append("\" "); sb.append("timeInMillis=\"").append((entry.end.getTime() - entry.start.getTime())).append("\">\n"); sb.append(" <requestHeaders>\n"); xmlHeaders(sb, entry.requestHeaders); sb.append(" </requestHeaders>\n"); sb.append(" <responseHeaders>\n"); xmlHeaders(sb, entry.responseHeaders); sb.append(" </responseHeaders>\n"); sb.append("</entry>\n"); } } sb.append("</traffic>\n"); } else { /* 200 GET http://foo.com/index.html 12422 bytes 102ms (2009-03-15T14:23:00.000-0700 - 2009-03-15T14:23:00.102-0700) Request Headers - Foo => Bar Response Headers - Baz => Blah ================================================================ */ synchronized(entries) { for (final Entry entry : entries) { sb.append(entry.statusCode).append(" ").append(entry.method).append(" ").append(entry.url).append("\n"); sb.append(entry.bytes).append(" bytes\n"); sb.append(entry.end.getTime() - entry.start.getTime()).append("ms (").append(sdf.format(entry.start)).append(" - ").append(sdf.format(entry.end)).append("\n"); sb.append("\n"); sb.append("Request Headers\n"); for (Header header : entry.requestHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("Response Headers\n"); for (Header header : entry.responseHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("================================================================\n"); sb.append("\n"); } } } clear(); return "OK," + sb.toString(); }